[MERGE] addons 16 survey
[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
23 from datetime import timedelta
24 import re
25 import time
26
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
31 import pooler
32 import tools
33
34
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"
41
42     return datetime.strptime(date_field[:19], '%Y-%m-%d %H:%M:%S')
43
44
45 class base_action_rule(osv.osv):
46     """ Base Action Rules """
47
48     _name = 'base.action.rule'
49     _description = 'Action Rules'
50
51     def _state_get(self, cr, uid, context=None):
52         """ Get State """
53         return self.state_get(cr, uid, context=context)
54
55     def state_get(self, cr, uid, context=None):
56         """ Get State """
57         return [('', '')]
58
59     def priority_get(self, cr, uid, context=None):
60         """ Get Priority """
61         return [('', '')]
62
63     _columns = {
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([
73             ('none', 'None'),
74             ('create', 'Creation Date'),
75             ('write', 'Last Modified Date'),
76             ('action_last', 'Last Action Date'),
77             ('date', '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),
91
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),
101     }
102
103     _defaults = {
104         'active': True,
105         'trg_date_type': 'none',
106         'trg_date_range_type': 'day',
107     }
108
109     _order = 'sequence'
110
111
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,))
117         res = cr.fetchall()
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)
125         return True
126
127     def _create(self, old_create, model, context=None):
128         """
129         Return a wrapper around `old_create` calling both `old_create` and
130         `post_action`, in that order.
131         """
132         def wrapper(cr, uid, vals, context=context):
133             if context is None:
134                 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)
138             return new_id
139         return wrapper
140
141     def _write(self, old_write, model, context=None):
142         """
143         Return a wrapper around `old_write` calling both `old_write` and
144         `post_action`, in that order.
145         """
146         def wrapper(cr, uid, ids, vals, context=context):
147             if context is None:
148                 context = {}
149             if isinstance(ids, (str, int, long)):
150                 ids = [ids]
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)
154             return True
155         return wrapper
156
157     def _register_hook(self, cr, uid, ids, context=None):
158         """
159         Wrap every `create` and `write` methods of the models specified by
160         the rules (given by `ids`).
161         """
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
169
170         return True
171
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)
175         return res_id
176
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)
180         return True
181
182     def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
183                        context=None):
184         """
185         This Function is call by scheduler.
186         """
187         rule_ids = self.search(cr, uid, [], context=context)
188         self._register_hook(cr, uid, rule_ids, context=context)
189         if context is None:
190             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)
194             last_run = False
195             if rule.last_run:
196                 last_run = get_datetime(rule.last_run)
197             now = datetime.now()
198             ctx = dict(context)            
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)
202             else:
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
206                 base = False
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
215                     else:
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')
223                         and obj.date):
224                     base = obj.date
225                 if base:
226                     fnct = {
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),
231                     }
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)):
236                         try:
237                             self._action(cr, uid, [rule.id], obj, context=ctx)
238                             self.write(cr, uid, [rule.id], {'last_run': now}, context=context)
239                         except Exception, e:
240                             import traceback
241                             print traceback.format_exc()
242                         
243                         
244
245     def do_check(self, cr, uid, action, obj, context=None):
246         """ check Action """
247         if context is None:
248             context = {}
249         ok = True
250         if action.filter_id and action.model_id.model == action.filter_id.model_id:
251             ctx = dict(context)
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)
259             ok = ok and (
260                 not action.trg_partner_categ_id.id or
261                 (
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 []))
264                 )
265             )
266         state_to = context.get('state_to', False)
267         state = getattr(obj, 'state', False)
268         if state:
269             ok = ok and (not action.trg_state_from or action.trg_state_from==state)
270         if state_to:
271             ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
272         elif action.trg_state_to:
273             ok = False
274         reg_name = action.regex_name
275         result_name = True
276         if reg_name:
277             ptrn = re.compile(ustr(reg_name))
278             _result = ptrn.search(ustr(obj.name))
279             if not _result:
280                 result_name = False
281         regex_n = not reg_name or result_name
282         ok = ok and regex_n
283         return ok
284
285     def do_action(self, cr, uid, action, obj, context=None):
286         """ Do Action """
287         if context is None:
288             context = {}
289         ctx = dict(context)
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)
295
296         write = {}
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
303         
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)
307         
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]
311             if new_followers:
312                 model_obj.message_subscribe(cr, uid, [obj.id], new_followers, context=context)
313         return True
314
315     def _action(self, cr, uid, ids, objects, scrit=None, context=None):
316         """ Do Action """
317         if context is None:
318             context = {}
319
320         context.update({'action': True})
321         if not scrit:
322             scrit = []
323         if not isinstance(objects, list):
324             objects = [objects]
325         for action in self.browse(cr, uid, ids, context=context):
326             for obj in objects:
327                 if self.do_check(cr, uid, action, obj, context=context):
328                     self.do_action(cr, uid, action, obj, context=context)
329
330         context.update({'action': False})
331         return True
332
333 base_action_rule()
334
335 class actions_server(osv.osv):
336     _inherit = 'ir.actions.server'
337     _columns = {
338         'action_rule_id': fields.many2one("base.action.rule", string="Action Rule")
339     }
340 actions_server()
341
342 class ir_cron(osv.osv):
343     _inherit = 'ir.cron'
344     _init_done = False
345
346     def _poolJobs(self, db_name, check=False):
347         if not self._init_done:
348             self._init_done = True
349             try:
350                 db = pooler.get_db(db_name)
351             except:
352                 return False
353             cr = db.cursor()
354             try:
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))
358             finally:
359                 cr.commit()
360                 cr.close()
361
362         super(ir_cron, self)._poolJobs(db_name, check=check)
363
364 ir_cron()
365
366
367 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: