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, timedelta
27 from openerp import SUPERUSER_ID
28 from openerp.osv import fields, osv
29 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
31 _logger = logging.getLogger(__name__)
33 DATE_RANGE_FUNCTION = {
34 'minutes': lambda interval: timedelta(minutes=interval),
35 'hour': lambda interval: timedelta(hours=interval),
36 'day': lambda interval: timedelta(days=interval),
37 'month': lambda interval: timedelta(months=interval),
38 False: lambda interval: timedelta(0),
41 def get_datetime(date_str):
42 '''Return a datetime from a date string or a datetime string'''
43 # complete date time if date_str contains only a date
44 if ' ' not in date_str:
45 date_str = date_str + " 00:00:00"
46 return datetime.strptime(date_str, DEFAULT_SERVER_DATETIME_FORMAT)
49 class base_action_rule(osv.osv):
50 """ Base Action Rules """
52 _name = 'base.action.rule'
53 _description = 'Action Rules'
56 'name': fields.char('Rule Name', size=64, required=True),
57 'model_id': fields.many2one('ir.model', 'Related Document Model',
58 required=True, domain=[('osv_memory', '=', False)]),
59 'model': fields.related('model_id', 'model', type="char", size=256, string='Model'),
60 'create_date': fields.datetime('Create Date', readonly=1),
61 'active': fields.boolean('Active',
62 help="When unchecked, the rule is hidden and will not be executed."),
63 'sequence': fields.integer('Sequence',
64 help="Gives the sequence order when displaying a list of rules."),
65 'trg_date_id': fields.many2one('ir.model.fields', string='Trigger Date',
66 help="When should the condition be triggered. If present, will be checked by the scheduler. If empty, will be checked at creation and update.",
67 domain="[('model_id', '=', model_id), ('ttype', 'in', ('date', 'datetime'))]"),
68 'trg_date_range': fields.integer('Delay after trigger date',
69 help="Delay after the trigger date." \
70 "You can put a negative number if you need a delay before the" \
71 "trigger date, like sending a reminder 15 minutes before a meeting."),
72 'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'),
73 ('day', 'Days'), ('month', 'Months')], 'Delay type'),
74 'act_user_id': fields.many2one('res.users', 'Set Responsible'),
75 'act_followers': fields.many2many("res.partner", string="Add Followers"),
76 'server_action_ids': fields.many2many('ir.actions.server', string='Server Actions',
77 domain="[('model_id', '=', model_id)]",
78 help="Examples: email reminders, call object service, etc."),
79 'filter_pre_id': fields.many2one('ir.filters', string='Before Update Filter',
81 domain="[('model_id', '=', model_id.model)]",
82 help="If present, this condition must be satisfied before the update of the record."),
83 'filter_id': fields.many2one('ir.filters', string='After Update Filter',
85 domain="[('model_id', '=', model_id.model)]",
86 help="If present, this condition must be satisfied after the update of the record."),
87 'last_run': fields.datetime('Last Run', readonly=1),
92 'trg_date_range_type': 'day',
97 def _filter(self, cr, uid, action, action_filter, record_ids, context=None):
98 """ filter the list record_ids that satisfy the action filter """
99 if record_ids and action_filter:
100 assert action.model == action_filter.model_id, "Filter model different from action rule model"
101 model = self.pool.get(action_filter.model_id)
102 domain = [('id', 'in', record_ids)] + eval(action_filter.domain)
103 ctx = dict(context or {})
104 ctx.update(eval(action_filter.context))
105 record_ids = model.search(cr, uid, domain, context=ctx)
108 def _process(self, cr, uid, action, record_ids, context=None):
109 """ process the given action on the records """
110 # execute server actions
111 model = self.pool.get(action.model_id.model)
112 if action.server_action_ids:
113 server_action_ids = map(int, action.server_action_ids)
114 for record in model.browse(cr, uid, record_ids, context):
115 action_server_obj = self.pool.get('ir.actions.server')
116 ctx = dict(context, active_model=model._name, active_ids=[record.id], active_id=record.id)
117 action_server_obj.run(cr, uid, server_action_ids, context=ctx)
121 if 'date_action_last' in model._all_columns:
122 values['date_action_last'] = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
123 if action.act_user_id and 'user_id' in model._all_columns:
124 values['user_id'] = action.act_user_id.id
126 model.write(cr, uid, record_ids, values, context=context)
128 if action.act_followers and hasattr(model, 'message_subscribe'):
129 follower_ids = map(int, action.act_followers)
130 model.message_subscribe(cr, uid, record_ids, follower_ids, context=context)
134 def _wrap_create(self, old_create, model):
135 """ Return a wrapper around `old_create` calling both `old_create` and
136 `_process`, in that order.
138 def wrapper(cr, uid, vals, context=None):
139 # avoid loops or cascading actions
140 if context and context.get('action'):
141 return old_create(cr, uid, vals, context=context)
143 context = dict(context or {}, action=True)
144 new_id = old_create(cr, uid, vals, context=context)
146 # as it is a new record, we do not consider the actions that have a prefilter
147 action_dom = [('model', '=', model), ('trg_date_id', '=', False), ('filter_pre_id', '=', False)]
148 action_ids = self.search(cr, uid, action_dom, context=context)
150 # check postconditions, and execute actions on the records that satisfy them
151 for action in self.browse(cr, uid, action_ids, context=context):
152 if self._filter(cr, uid, action, action.filter_id, [new_id], context=context):
153 self._process(cr, uid, action, [new_id], context=context)
158 def _wrap_write(self, old_write, model):
159 """ Return a wrapper around `old_write` calling both `old_write` and
160 `_process`, in that order.
162 def wrapper(cr, uid, ids, vals, context=None):
163 # avoid loops or cascading actions
164 if context and context.get('action'):
165 return old_write(cr, uid, ids, vals, context=context)
167 context = dict(context or {}, action=True)
168 ids = [ids] if isinstance(ids, (int, long, str)) else ids
170 # retrieve the action rules to possibly execute
171 action_dom = [('model', '=', model), ('trg_date_id', '=', False)]
172 action_ids = self.search(cr, uid, action_dom, context=context)
173 actions = self.browse(cr, uid, action_ids, context=context)
175 # check preconditions
177 for action in actions:
178 pre_ids[action] = self._filter(cr, uid, action, action.filter_pre_id, ids, context=context)
181 old_write(cr, uid, ids, vals, context=context)
183 # check postconditions, and execute actions on the records that satisfy them
184 for action in actions:
185 post_ids = self._filter(cr, uid, action, action.filter_id, pre_ids[action], context=context)
187 self._process(cr, uid, action, post_ids, context=context)
192 def _register_hook(self, cr, ids=None):
193 """ Wrap the methods `create` and `write` of the models specified by
194 the rules given by `ids` (or all existing rules if `ids` is `None`.)
198 ids = self.search(cr, SUPERUSER_ID, [])
199 for action_rule in self.browse(cr, SUPERUSER_ID, ids):
200 model = action_rule.model_id.model
201 model_obj = self.pool.get(model)
202 if not hasattr(model_obj, 'base_action_ruled'):
203 model_obj.create = self._wrap_create(model_obj.create, model)
204 model_obj.write = self._wrap_write(model_obj.write, model)
205 model_obj.base_action_ruled = True
209 def create(self, cr, uid, vals, context=None):
210 res_id = super(base_action_rule, self).create(cr, uid, vals, context=context)
211 if self._register_hook(cr, [res_id]):
212 openerp.modules.registry.RegistryManager.signal_registry_change(cr.dbname)
215 def write(self, cr, uid, ids, vals, context=None):
216 if isinstance(ids, (int, long)):
218 super(base_action_rule, self).write(cr, uid, ids, vals, context=context)
219 if self._register_hook(cr, ids):
220 openerp.modules.registry.RegistryManager.signal_registry_change(cr.dbname)
223 def onchange_model_id(self, cr, uid, ids, model_id, context=None):
224 data = {'model': False, 'filter_pre_id': False, 'filter_id': False}
226 model = self.pool.get('ir.model').browse(cr, uid, model_id, context=context)
227 data.update({'model': model.model})
228 return {'value': data}
230 def _check(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
231 """ This Function is called by scheduler. """
232 context = context or {}
233 # retrieve all the action rules that have a trg_date_id and no precondition
234 action_dom = [('trg_date_id', '!=', False), ('filter_pre_id', '=', False)]
235 action_ids = self.search(cr, uid, action_dom, context=context)
236 for action in self.browse(cr, uid, action_ids, context=context):
238 last_run = get_datetime(action.last_run) if action.last_run else False
240 # retrieve all the records that satisfy the action's condition
241 model = self.pool.get(action.model_id.model)
245 domain = eval(action.filter_id.domain)
246 ctx.update(eval(action.filter_id.context))
247 if 'lang' not in ctx:
248 # Filters might be language-sensitive, attempt to reuse creator lang
249 # as we are usually running this as super-user in background
250 [filter_meta] = action.filter_id.perm_read()
251 user_id = filter_meta['write_uid'] and filter_meta['write_uid'][0] or \
252 filter_meta['create_uid'][0]
253 ctx['lang'] = self.pool['res.users'].browse(cr, uid, user_id).lang
254 record_ids = model.search(cr, uid, domain, context=ctx)
256 # determine when action should occur for the records
257 date_field = action.trg_date_id.name
258 if date_field == 'date_action_last' and 'create_date' in model._all_columns:
259 get_record_dt = lambda record: record[date_field] or record.create_date
261 get_record_dt = lambda record: record[date_field]
263 delay = DATE_RANGE_FUNCTION[action.trg_date_range_type](action.trg_date_range)
265 # process action on the records that should be executed
266 for record in model.browse(cr, uid, record_ids, context=context):
267 record_dt = get_record_dt(record)
270 action_dt = get_datetime(record_dt) + delay
271 if last_run and (last_run <= action_dt < now) or (action_dt < now):
273 self._process(cr, uid, action, [record.id], context=context)
276 _logger.error(traceback.format_exc())
278 action.write({'last_run': now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})