[FIX] bugin view inheritancy
[odoo/odoo.git] / addons / base_action_rule / base_action_rule.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 from datetime import datetime, timedelta
23 import time
24 import logging
25
26 from openerp import SUPERUSER_ID
27 from openerp.osv import fields, osv
28 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
29
30 _logger = logging.getLogger(__name__)
31
32 DATE_RANGE_FUNCTION = {
33     'minutes': lambda interval: timedelta(minutes=interval),
34     'hour': lambda interval: timedelta(hours=interval),
35     'day': lambda interval: timedelta(days=interval),
36     'month': lambda interval: timedelta(months=interval),
37     False: lambda interval: timedelta(0),
38 }
39
40 def get_datetime(date_str):
41     '''Return a datetime from a date string or a datetime string'''
42     # complete date time if date_str contains only a date
43     if ' ' not in date_str:
44         date_str = date_str + " 00:00:00"
45     return datetime.strptime(date_str, DEFAULT_SERVER_DATETIME_FORMAT)
46
47
48 class base_action_rule(osv.osv):
49     """ Base Action Rules """
50
51     _name = 'base.action.rule'
52     _description = 'Action Rules'
53     _order = 'sequence'
54
55     _columns = {
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         'kind': fields.selection(
66             [('on_create', 'On Creation'),
67              ('on_write', 'On Update'),
68              ('on_create_or_write', 'On Creation & Update'),
69              ('on_time', 'Based on Timed Condition')],
70             string='When to Run'),
71         'trg_date_id': fields.many2one('ir.model.fields', string='Trigger Date',
72             help="When should the condition be triggered. If present, will be checked by the scheduler. If empty, will be checked at creation and update.",
73             domain="[('model_id', '=', model_id), ('ttype', 'in', ('date', 'datetime'))]"),
74         'trg_date_range': fields.integer('Delay after trigger date',
75             help="Delay after the trigger date." \
76             "You can put a negative number if you need a delay before the" \
77             "trigger date, like sending a reminder 15 minutes before a meeting."),
78         'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'),
79                                 ('day', 'Days'), ('month', 'Months')], 'Delay type'),
80         'act_user_id': fields.many2one('res.users', 'Set Responsible'),
81         'act_followers': fields.many2many("res.partner", string="Add Followers"),
82         'server_action_ids': fields.many2many('ir.actions.server', string='Server Actions',
83             domain="[('model_id', '=', model_id)]",
84             help="Examples: email reminders, call object service, etc."),
85         'filter_pre_id': fields.many2one('ir.filters', string='Before Update Filter',
86             ondelete='restrict',
87             domain="[('model_id', '=', model_id.model)]",
88             help="If present, this condition must be satisfied before the update of the record."),
89         'filter_id': fields.many2one('ir.filters', string='Filter',
90             ondelete='restrict',
91             domain="[('model_id', '=', model_id.model)]",
92             help="If present, this condition must be satisfied before executing the action rule."),
93         'last_run': fields.datetime('Last Run', readonly=1),
94     }
95
96     _defaults = {
97         'active': True,
98         'trg_date_range_type': 'day',
99     }
100
101     def onchange_kind(self, cr, uid, ids, kind, context=None):
102         clear_fields = []
103         if kind in ['on_create', 'on_create_or_write']:
104             clear_fields = ['filter_pre_id', 'trg_date_id', 'trg_date_range', 'trg_date_range_type']
105         elif kind in ['on_write', 'on_create_or_write']:
106             clear_fields = ['trg_date_id', 'trg_date_range', 'trg_date_range_type']
107         elif kind == 'on_time':
108             clear_fields = ['filter_pre_id']
109         return {'value': dict.fromkeys(clear_fields, False)}
110
111     def _filter(self, cr, uid, action, action_filter, record_ids, context=None):
112         """ filter the list record_ids that satisfy the action filter """
113         if record_ids and action_filter:
114             assert action.model == action_filter.model_id, "Filter model different from action rule model"
115             model = self.pool[action_filter.model_id]
116             domain = [('id', 'in', record_ids)] + eval(action_filter.domain)
117             ctx = dict(context or {})
118             ctx.update(eval(action_filter.context))
119             record_ids = model.search(cr, uid, domain, context=ctx)
120         return record_ids
121
122     def _process(self, cr, uid, action, record_ids, context=None):
123         """ process the given action on the records """
124         model = self.pool[action.model_id.model]
125
126         # modify records
127         values = {}
128         if 'date_action_last' in model._all_columns:
129             values['date_action_last'] = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
130         if action.act_user_id and 'user_id' in model._all_columns:
131             values['user_id'] = action.act_user_id.id
132         if values:
133             model.write(cr, uid, record_ids, values, context=context)
134
135         if action.act_followers and hasattr(model, 'message_subscribe'):
136             follower_ids = map(int, action.act_followers)
137             model.message_subscribe(cr, uid, record_ids, follower_ids, context=context)
138
139         # execute server actions
140         if action.server_action_ids:
141             server_action_ids = map(int, action.server_action_ids)
142             for record in model.browse(cr, uid, record_ids, context):
143                 action_server_obj = self.pool.get('ir.actions.server')
144                 ctx = dict(context, active_model=model._name, active_ids=[record.id], active_id=record.id)
145                 action_server_obj.run(cr, uid, server_action_ids, context=ctx)
146
147         return True
148
149     def _wrap_create(self, old_create, model):
150         """ Return a wrapper around `old_create` calling both `old_create` and
151             `_process`, in that order.
152         """
153         def create(cr, uid, vals, context=None):
154             # avoid loops or cascading actions
155             if context and context.get('action'):
156                 return old_create(cr, uid, vals, context=context)
157
158             context = dict(context or {}, action=True)
159             new_id = old_create(cr, uid, vals, context=context)
160
161             # retrieve the action rules to run on creation
162             action_dom = [('model', '=', model), ('kind', 'in', ['on_create', 'on_create_or_write'])]
163             action_ids = self.search(cr, uid, action_dom, context=context)
164
165             # check postconditions, and execute actions on the records that satisfy them
166             for action in self.browse(cr, uid, action_ids, context=context):
167                 if self._filter(cr, uid, action, action.filter_id, [new_id], context=context):
168                     self._process(cr, uid, action, [new_id], context=context)
169             return new_id
170
171         return create
172
173     def _wrap_write(self, old_write, model):
174         """ Return a wrapper around `old_write` calling both `old_write` and
175             `_process`, in that order.
176         """
177         def write(cr, uid, ids, vals, context=None):
178             # avoid loops or cascading actions
179             if context and context.get('action'):
180                 return old_write(cr, uid, ids, vals, context=context)
181
182             context = dict(context or {}, action=True)
183             ids = [ids] if isinstance(ids, (int, long, str)) else ids
184
185             # retrieve the action rules to run on update
186             action_dom = [('model', '=', model), ('kind', 'in', ['on_write', 'on_create_or_write'])]
187             action_ids = self.search(cr, uid, action_dom, context=context)
188             actions = self.browse(cr, uid, action_ids, context=context)
189
190             # check preconditions
191             pre_ids = {}
192             for action in actions:
193                 pre_ids[action] = self._filter(cr, uid, action, action.filter_pre_id, ids, context=context)
194
195             # execute write
196             old_write(cr, uid, ids, vals, context=context)
197
198             # check postconditions, and execute actions on the records that satisfy them
199             for action in actions:
200                 post_ids = self._filter(cr, uid, action, action.filter_id, pre_ids[action], context=context)
201                 if post_ids:
202                     self._process(cr, uid, action, post_ids, context=context)
203             return True
204
205         return write
206
207     def _register_hook(self, cr, ids=None):
208         """ Wrap the methods `create` and `write` of the models specified by
209             the rules given by `ids` (or all existing rules if `ids` is `None`.)
210         """
211         if ids is None:
212             ids = self.search(cr, SUPERUSER_ID, [])
213         for action_rule in self.browse(cr, SUPERUSER_ID, ids):
214             model = action_rule.model_id.model
215             model_obj = self.pool[model]
216             if not hasattr(model_obj, 'base_action_ruled'):
217                 model_obj.create = self._wrap_create(model_obj.create, model)
218                 model_obj.write = self._wrap_write(model_obj.write, model)
219                 model_obj.base_action_ruled = True
220         return True
221
222     def create(self, cr, uid, vals, context=None):
223         res_id = super(base_action_rule, self).create(cr, uid, vals, context=context)
224         self._register_hook(cr, [res_id])
225         return res_id
226
227     def write(self, cr, uid, ids, vals, context=None):
228         if isinstance(ids, (int, long)):
229             ids = [ids]
230         super(base_action_rule, self).write(cr, uid, ids, vals, context=context)
231         self._register_hook(cr, ids)
232         return True
233
234     def onchange_model_id(self, cr, uid, ids, model_id, context=None):
235         data = {'model': False, 'filter_pre_id': False, 'filter_id': False}
236         if model_id:
237             model = self.pool.get('ir.model').browse(cr, uid, model_id, context=context)
238             data.update({'model': model.model})
239         return {'value': data}
240
241     def _check(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
242         """ This Function is called by scheduler. """
243         context = context or {}
244         # retrieve all the action rules to run based on a timed condition
245         action_dom = [('kind', '=', 'on_time')]
246         action_ids = self.search(cr, uid, action_dom, context=context)
247         for action in self.browse(cr, uid, action_ids, context=context):
248             now = datetime.now()
249             last_run = get_datetime(action.last_run) if action.last_run else False
250
251             # retrieve all the records that satisfy the action's condition
252             model = self.pool[action.model_id.model]
253             domain = []
254             ctx = dict(context)
255             if action.filter_id:
256                 domain = eval(action.filter_id.domain)
257                 ctx.update(eval(action.filter_id.context))
258             record_ids = model.search(cr, uid, domain, context=ctx)
259
260             # determine when action should occur for the records
261             date_field = action.trg_date_id.name
262             if date_field == 'date_action_last' and 'create_date' in model._all_columns:
263                 get_record_dt = lambda record: record[date_field] or record.create_date
264             else:
265                 get_record_dt = lambda record: record[date_field]
266
267             delay = DATE_RANGE_FUNCTION[action.trg_date_range_type](action.trg_date_range)
268
269             # process action on the records that should be executed
270             for record in model.browse(cr, uid, record_ids, context=context):
271                 record_dt = get_record_dt(record)
272                 if not record_dt:
273                     continue
274                 action_dt = get_datetime(record_dt) + delay
275                 if last_run and (last_run <= action_dt < now) or (action_dt < now):
276                     try:
277                         self._process(cr, uid, action, [record.id], context=context)
278                     except Exception:
279                         import traceback
280                         _logger.error(traceback.format_exc())
281
282             action.write({'last_run': now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})