1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from datetime import datetime
23 from datetime import timedelta
27 from osv import fields, osv, orm
28 from tools.translate import _
29 from tools.safe_eval import safe_eval
30 from tools import ustr
35 def get_datetime(date_field):
36 '''Return a datetime from a date string or a datetime string'''
37 #complete date time if date_field contains only a date
38 date_split = date_field.split(' ')
39 if len(date_split) == 1:
40 date_field = date_split[0] + " 00:00:00"
42 return datetime.strptime(date_field[:19], '%Y-%m-%d %H:%M:%S')
45 class base_action_rule(osv.osv):
46 """ Base Action Rules """
48 _name = 'base.action.rule'
49 _description = 'Action Rules'
51 def _state_get(self, cr, uid, context=None):
53 return self.state_get(cr, uid, context=context)
55 def state_get(self, cr, uid, context=None):
59 def priority_get(self, cr, uid, context=None):
64 'name': fields.char('Rule Name', size=64, required=True),
65 'model_id': fields.many2one('ir.model', 'Related Document Model', required=True, domain=[('osv_memory','=', False)]),
66 'model': fields.related('model_id', 'model', type="char", size=256, string='Model'),
67 'create_date': fields.datetime('Create Date', readonly=1),
68 'active': fields.boolean('Active', help="If the active field is set to False,\
69 it will allow you to hide the rule without removing it."),
70 'sequence': fields.integer('Sequence', help="Gives the sequence order \
71 when displaying a list of rules."),
72 'trg_date_type': fields.selection([
74 ('create', 'Creation Date'),
75 ('write', 'Last Modified Date'),
76 ('action_last', 'Last Action Date'),
78 ('deadline', 'Deadline'),
79 ], 'Trigger Date', size=16),
80 'trg_date_range': fields.integer('Delay after trigger date', \
81 help="Delay After Trigger Date,\
82 specifies you can put a negative number. If you need a delay before the \
83 trigger date, like sending a reminder 15 minutes before a meeting."),
84 'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'), \
85 ('day', 'Days'), ('month', 'Months')], 'Delay type'),
86 'trg_user_id': fields.many2one('res.users', 'Responsible'),
87 'trg_partner_id': fields.many2one('res.partner', 'Partner'),
88 'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
89 'trg_state_from': fields.selection(_state_get, 'Status', size=16),
90 'trg_state_to': fields.selection(_state_get, 'Button Pressed', size=16),
92 'act_user_id': fields.many2one('res.users', 'Set Responsible to'),
93 'act_state': fields.selection(_state_get, 'Set State to', size=16),
94 'act_followers': fields.many2many("res.partner", string="Set Followers"),
95 'regex_name': fields.char('Regex on Resource Name', size=128, help="Regular expression for matching name of the resource\
96 \ne.g.: 'urgent.*' will search for records having name starting with the string 'urgent'\
97 \nNote: This is case sensitive search."),
98 'server_action_ids': fields.one2many('ir.actions.server', 'action_rule_id', 'Server Action', help="Define Server actions.\neg:Email Reminders, Call Object Service, etc.."), #TODO: set domain [('model_id','=',model_id)]
99 'filter_id':fields.many2one('ir.filters', 'Filter', required=False), #TODO: set domain [('model_id','=',model_id.model)]
100 'last_run': fields.datetime('Last Run', readonly=1),
105 'trg_date_type': 'none',
106 'trg_date_range_type': 'day',
112 def post_action(self, cr, uid, ids, model, context=None):
113 # Searching for action rules
114 cr.execute("SELECT model.model, rule.id FROM base_action_rule rule \
115 LEFT JOIN ir_model model on (model.id = rule.model_id) \
116 WHERE active and model = %s", (model,))
118 # Check if any rule matching with current object
119 for obj_name, rule_id in res:
120 obj = self.pool.get(obj_name)
121 # If the rule doesn't involve a time condition, run it immediately
122 # Otherwise we let the scheduler run the action
123 if self.browse(cr, uid, rule_id, context=context).trg_date_type == 'none':
124 self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context), context=context)
127 def _create(self, old_create, model, context=None):
129 Return a wrapper around `old_create` calling both `old_create` and
130 `post_action`, in that order.
132 def wrapper(cr, uid, vals, context=context):
135 new_id = old_create(cr, uid, vals, context=context)
136 if not context.get('action'):
137 self.post_action(cr, uid, [new_id], model, context=context)
141 def _write(self, old_write, model, context=None):
143 Return a wrapper around `old_write` calling both `old_write` and
144 `post_action`, in that order.
146 def wrapper(cr, uid, ids, vals, context=context):
149 if isinstance(ids, (str, int, long)):
151 old_write(cr, uid, ids, vals, context=context)
152 if not context.get('action'):
153 self.post_action(cr, uid, ids, model, context=context)
157 def _register_hook(self, cr, uid, ids, context=None):
159 Wrap every `create` and `write` methods of the models specified by
160 the rules (given by `ids`).
162 for action_rule in self.browse(cr, uid, ids, context=context):
163 model = action_rule.model_id.model
164 obj_pool = self.pool.get(model)
165 if not hasattr(obj_pool, 'base_action_ruled'):
166 obj_pool.create = self._create(obj_pool.create, model, context=context)
167 obj_pool.write = self._write(obj_pool.write, model, context=context)
168 obj_pool.base_action_ruled = True
172 def create(self, cr, uid, vals, context=None):
173 res_id = super(base_action_rule, self).create(cr, uid, vals, context=context)
174 self._register_hook(cr, uid, [res_id], context=context)
177 def write(self, cr, uid, ids, vals, context=None):
178 super(base_action_rule, self).write(cr, uid, ids, vals, context=context)
179 self._register_hook(cr, uid, ids, context=context)
182 def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
185 This Function is call by scheduler.
187 rule_ids = self.search(cr, uid, [], context=context)
188 self._register_hook(cr, uid, rule_ids, context=context)
191 for rule in self.browse(cr, uid, rule_ids, context=context):
192 model = rule.model_id.model
193 model_pool = self.pool.get(model)
196 last_run = get_datetime(rule.last_run)
199 if rule.filter_id and rule.model_id.model == rule.filter_id.model_id:
200 ctx.update(eval(rule.filter_id.context))
201 obj_ids = model_pool.search(cr, uid, eval(rule.filter_id.domain), context=ctx)
203 obj_ids = model_pool.search(cr, uid, [], context=ctx)
204 for obj in model_pool.browse(cr, uid, obj_ids, context=ctx):
205 # Calculate when this action should next occur for this object
207 if rule.trg_date_type=='create' and hasattr(obj, 'create_date'):
208 base = obj.create_date
209 elif rule.trg_date_type=='write' and hasattr(obj, 'write_date'):
210 base = obj.write_date
211 elif (rule.trg_date_type=='action_last'
212 and hasattr(obj, 'create_date')):
213 if hasattr(obj, 'date_action_last') and obj.date_action_last:
214 base = obj.date_action_last
216 base = obj.create_date
217 elif (rule.trg_date_type=='deadline'
218 and hasattr(obj, 'date_deadline')
219 and obj.date_deadline):
220 base = obj.date_deadline
221 elif (rule.trg_date_type=='date'
222 and hasattr(obj, 'date')
227 'minutes': lambda interval: timedelta(minutes=interval),
228 'day': lambda interval: timedelta(days=interval),
229 'hour': lambda interval: timedelta(hours=interval),
230 'month': lambda interval: timedelta(months=interval),
232 base = get_datetime(base)
233 delay = fnct[rule.trg_date_range_type](rule.trg_date_range)
234 action_date = base + delay
235 if (not last_run or (last_run <= action_date < now)):
237 self._action(cr, uid, [rule.id], obj, context=ctx)
238 self.write(cr, uid, [rule.id], {'last_run': now}, context=context)
241 print traceback.format_exc()
245 def do_check(self, cr, uid, action, obj, context=None):
250 if action.filter_id and action.model_id.model == action.filter_id.model_id:
252 ctx.update(eval(action.filter_id.context))
253 obj_ids = self.pool.get(action.model_id.model).search(cr, uid, eval(action.filter_id.domain), context=ctx)
254 ok = ok and obj.id in obj_ids
255 if getattr(obj, 'user_id', False):
256 ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
257 if getattr(obj, 'partner_id', False):
258 ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
260 not action.trg_partner_categ_id.id or
262 obj.partner_id.id and
263 (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
266 state_to = context.get('state_to', False)
267 state = getattr(obj, 'state', False)
269 ok = ok and (not action.trg_state_from or action.trg_state_from==state)
271 ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
272 elif action.trg_state_to:
274 reg_name = action.regex_name
277 ptrn = re.compile(ustr(reg_name))
278 _result = ptrn.search(ustr(obj.name))
281 regex_n = not reg_name or result_name
285 def do_action(self, cr, uid, action, obj, context=None):
290 model_obj = self.pool.get(action.model_id.model)
291 action_server_obj = self.pool.get('ir.actions.server')
292 if action.server_action_ids:
293 ctx.update({'active_model': action.model_id.model, 'active_id':obj.id, 'active_ids':[obj.id]})
294 action_server_obj.run(cr, uid, [x.id for x in action.server_action_ids], context=ctx)
297 if hasattr(obj, 'user_id') and action.act_user_id:
298 write['user_id'] = action.act_user_id.id
299 if hasattr(obj, 'date_action_last'):
300 write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
301 if hasattr(obj, 'state') and action.act_state:
302 write['state'] = action.act_state
304 model_obj.write(cr, uid, [obj.id], write, context)
305 if hasattr(obj, 'state') and hasattr(obj, 'message_post') and action.act_state:
306 model_obj.message_post(cr, uid, [obj], _(action.act_state), context=context)
308 if hasattr(obj, 'message_subscribe') and action.act_followers:
309 exits_followers = [x.id for x in obj.message_follower_ids]
310 new_followers = [x.id for x in action.act_followers if x.id not in exits_followers]
312 model_obj.message_subscribe(cr, uid, [obj.id], new_followers, context=context)
315 def _action(self, cr, uid, ids, objects, scrit=None, context=None):
320 context.update({'action': True})
323 if not isinstance(objects, list):
325 for action in self.browse(cr, uid, ids, context=context):
327 if self.do_check(cr, uid, action, obj, context=context):
328 self.do_action(cr, uid, action, obj, context=context)
330 context.update({'action': False})
335 class actions_server(osv.osv):
336 _inherit = 'ir.actions.server'
338 'action_rule_id': fields.many2one("base.action.rule", string="Action Rule")
342 class ir_cron(osv.osv):
346 def _poolJobs(self, db_name, check=False):
347 if not self._init_done:
348 self._init_done = True
350 db = pooler.get_db(db_name)
355 next = datetime.now().strftime('%Y-%m-%d %H:00:00')
356 # Putting nextcall always less than current time in order to call it every time
357 cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
362 super(ir_cron, self)._poolJobs(db_name, check=check)
367 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: