[IMP] base_action_rule: add scheduler to check rules every 4 hours
[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 osv import fields, osv, orm
24 from osv.orm import except_orm
25 from osv.osv import osv_pool
26 from tools.translate import _
27 import mx.DateTime
28 import pooler 
29 import re
30 import time
31 import tools
32
33 class base_action_rule(osv.osv):
34     """ Base Action Rules """
35
36     _name = 'base.action.rule'
37     _description = 'Action Rules'
38     
39     def _state_get(self, cr, uid, context={}):
40         """ Get State
41             @param self: The object pointer
42             @param cr: the current row, from the database cursor,
43             @param uid: the current user’s ID for security checks,
44             @param context: A standard dictionary for contextual values """
45
46         return self.state_get(cr, uid, context=context)
47
48    
49     def state_get(self, cr, uid, context={}):
50         """ Get State
51             @param self: The object pointer
52             @param cr: the current row, from the database cursor,
53             @param uid: the current user’s ID for security checks,
54             @param context: A standard dictionary for contextual values """
55
56         return [('', '')]
57   
58     def priority_get(self, cr, uid, context={}):
59         """ Get Priority
60             @param self: The object pointer
61             @param cr: the current row, from the database cursor,
62             @param uid: the current user’s ID for security checks,
63             @param context: A standard dictionary for contextual values """
64
65         return [('', '')]
66
67     _columns = {
68         'name': fields.many2one('ir.model', 'Object', required=True), 
69         'max_level': fields.integer('Max Level', help='Specifies maximum level.'), 
70         'create_date': fields.datetime('Create Date', readonly=1), 
71         'active': fields.boolean('Active', help="If the active field is set to true,\
72  it will allow you to hide the rule without removing it."), 
73         'sequence': fields.integer('Sequence', help="Gives the sequence order \
74 when displaying a list of rules."), 
75         'trg_date_type':  fields.selection([
76             ('none', 'None'), 
77             ('create', 'Creation Date'), 
78             ('action_last', 'Last Action Date'), 
79             ('date', 'Date'), 
80             ('deadline', 'Deadline'), 
81             ], 'Trigger Date', size=16), 
82         'trg_date_range': fields.integer('Delay after trigger date', \
83                                          help="Delay After Trigger Date,\
84 specifies you can put a negative number. If you need a delay before the \
85 trigger date, like sending a reminder 15 minutes before a meeting."), 
86         'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'), \
87                                 ('day', 'Days'), ('month', 'Months')], 'Delay type'), 
88
89
90         'trg_user_id':  fields.many2one('res.users', 'Responsible'), 
91
92         'trg_partner_id': fields.many2one('res.partner', 'Partner'), 
93         'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'), 
94         'trg_state_from': fields.selection(_state_get, 'State', size=16), 
95         'trg_state_to': fields.selection(_state_get, 'Button Pressed', size=16), 
96
97         'act_method': fields.char('Call Object Method', size=64), 
98         'act_user_id': fields.many2one('res.users', 'Set responsible to'), 
99         'act_state': fields.selection(_state_get, 'Set state to', size=16), 
100         'act_email_cc': fields.char('Add watchers (Cc)', size=250, help="\
101 These people will receive a copy of the future communication between partner \
102 and users by email"), 
103         'act_remind_partner': fields.boolean('Remind Partner', help="Check \
104 this if you want the rule to send a reminder by email to the partner."), 
105         'act_remind_user': fields.boolean('Remind responsible', help="Check \
106 this if you want the rule to send a reminder by email to the user."), 
107         'act_reply_to': fields.char('Reply-To', size=64), 
108         'act_remind_attach': fields.boolean('Remind with attachment', help="Check this if you want that all documents attached to the object be attached to the reminder email sent."), 
109         'act_mail_to_user': fields.boolean('Mail to responsible', help="Check\
110  this if you want the rule to send an email to the responsible person."), 
111         'act_mail_to_watchers': fields.boolean('Mail to watchers (CC)', 
112                                                 help="Check this if you want \
113 the rule to mark CC(mail to any other person defined in actions)."), 
114         'act_mail_to_email': fields.char('Mail to these emails', size=128, \
115         help="Email-id of the persons whom mail is to be sent"), 
116         'act_mail_body': fields.text('Mail body', help="Content of mail"), 
117         'regex_name': fields.char('Regular Expression on Model Name', size=128), 
118         'server_action_id': fields.many2one('ir.actions.server', 'Server Action', help="Describes the action name.\neg:on which object which action to be taken on basis of which condition"), 
119         'filter_id':fields.many2one('ir.filters', 'Filter', required=False), 
120         'domain':fields.char('Domain', size=124, required=False, readonly=False),
121     }
122
123     _defaults = {
124         'active': lambda *a: True, 
125         'max_level': lambda *a: 15, 
126         'trg_date_type': lambda *a: 'none', 
127         'trg_date_range_type': lambda *a: 'day', 
128         'act_mail_to_user': lambda *a: 0, 
129         'act_remind_partner': lambda *a: 0, 
130         'act_remind_user': lambda *a: 0, 
131         'act_mail_to_watchers': lambda *a: 0, 
132         'domain': lambda *a: '[]'
133     }
134     
135     _order = 'sequence'
136     
137     def pre_action(self, cr, uid, ids, model, context=None):
138         # Searching for action rules
139         cr.execute("SELECT model.model, rule.id  FROM base_action_rule rule LEFT JOIN ir_model model on (model.id = rule.name)")
140         res = cr.fetchall()
141         # Check if any rule matching with current object
142         for obj_name, rule_id in res:
143             if not (model == obj_name):
144                 continue
145             else:
146                 obj = self.pool.get(obj_name)
147                 self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context))
148         return True
149
150     def new_create(self, old_create, model, context=None):
151         if not context:
152             context  = {}
153         def make_call_old(cr, uid, vals, context=context):
154             new_id = old_create(cr, uid, vals, context=context)
155             if not context.get('action'):
156                 self.pre_action(cr, uid, [new_id], model, context=context)
157             return new_id
158         return make_call_old
159     
160     def new_write(self, old_write, model, context=None):
161         if not context:
162             context  = {}
163         def make_call_old(cr, uid, ids, vals, context=context):
164             if isinstance(ids, (str, int, long)):
165                 ids = [ids]
166             if not context.get('action'):
167                 self.pre_action(cr, uid, ids, model, context=context)
168             return old_write(cr, uid, ids, vals, context=context)
169         return make_call_old
170
171     def create(self, cr, uid, vals, context=None):
172         if not context:
173             context = {}
174         res_id = super(base_action_rule, self).create(cr, uid, vals, context)
175         model_pool = self.pool.get('ir.model')
176         model = model_pool.browse(cr, uid, vals.get('name'), context=context).model
177         obj_pool = self.pool.get(model)
178         obj_pool.__setattr__('old_create', obj_pool.create)
179         obj_pool.__setattr__('old_write', obj_pool.write)
180         obj_pool.__setattr__('create', self.new_create(obj_pool.create, model, context=context))
181         obj_pool.__setattr__('write', self.new_write(obj_pool.write, model, context=context))
182         return res_id
183     
184     def write(self, cr, uid, ids, vals, context=None):
185         res = super(base_action_rule, self).write(cr, uid, ids, vals, context)
186         model_pool = self.pool.get('ir.model')
187         if not context:
188             context = {}
189         for rule in self.browse(cr, uid, ids, context=context):
190             model = model_pool.browse(cr, uid, rule.name.id, context=context).model
191             obj_pool = self.pool.get(model)
192             obj_pool.__setattr__('old_create', obj_pool.create)
193             obj_pool.__setattr__('old_write', obj_pool.write)
194             obj_pool.__setattr__('create', self.new_create(obj_pool.create, model, context=context))
195             obj_pool.__setattr__('write', self.new_write(obj_pool.write, model, context=context))
196         return res
197
198     def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
199                        context=None):
200         """
201         This Function is call by scheduler.
202         """
203         rule_pool= self.pool.get('base.action.rule')
204         rule_ids = rule_pool.search(cr, uid, [], context=context)
205         return rule_pool.write(cr, uid, rule_ids, {}, context=context)
206         
207
208     def format_body(self, body):
209         """ Foramat Action rule's body
210             @param self: The object pointer """
211
212         return body and tools.ustr(body) or ''
213
214     def format_mail(self, obj, body):
215         """ Foramat Mail
216             @param self: The object pointer """
217
218         data = {
219             'object_id': obj.id, 
220             'object_subject': hasattr(obj, 'name') and obj.name or False, 
221             'object_date': hasattr(obj, 'date') and obj.date or False, 
222             'object_description': hasattr(obj, 'description') and obj.description or False, 
223             'object_user': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.name) or '/', 
224             'object_user_email': hasattr(obj, 'user_id') and (obj.user_id and \
225                                     obj.user_id.address_id and obj.user_id.address_id.email) or '/', 
226             'object_user_phone': hasattr(obj, 'user_id') and (obj.user_id and\
227                                      obj.user_id.address_id and obj.user_id.address_id.phone) or '/', 
228             'partner': hasattr(obj, 'partner_id') and (obj.partner_id and obj.partner_id.name) or '/', 
229             'partner_email': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and\
230                                          obj.partner_address_id.email) or '/', 
231         }
232         return self.format_body(body % data)
233
234     def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context={}):
235         """ send email
236             @param self: The object pointer
237             @param cr: the current row, from the database cursor,
238             @param uid: the current user’s ID for security checks,
239             @param email: pass the emails
240             @param emailfrom: Pass name the email From else False
241             @param context: A standard dictionary for contextual values """
242
243         body = self.format_mail(obj, body)
244         if not emailfrom:
245             if hasattr(obj, 'user_id')  and obj.user_id and obj.user_id.address_id and\
246                         obj.user_id.address_id.email:
247                 emailfrom = obj.user_id.address_id.email
248
249         name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
250         emailfrom = tools.ustr(emailfrom)
251         reply_to = emailfrom
252         if not emailfrom:
253             raise osv.except_osv(_('Error!'), 
254                     _("No E-Mail ID Found for your Company address!"))
255         return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
256
257
258     def do_check(self, cr, uid, action, obj, context={}):
259         """ check Action
260             @param self: The object pointer
261             @param cr: the current row, from the database cursor,
262             @param uid: the current user’s ID for security checks,
263             @param context: A standard dictionary for contextual values """
264
265         ok = True
266         if eval(action.domain):
267             obj_ids = obj._table.search(cr, uid, eval(action.domain), context=context)
268             if not obj.id in obj_ids:
269                 ok = False
270         if hasattr(obj, 'user_id'):
271             ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
272         if hasattr(obj, 'partner_id'):
273             ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
274             ok = ok and (
275                 not action.trg_partner_categ_id.id or
276                 (
277                     obj.partner_id.id and
278                     (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
279                 )
280             )
281         state_to = context.get('state_to', False)
282         if hasattr(obj, 'state'):
283             ok = ok and (not action.trg_state_from or action.trg_state_from==obj.state)
284         if state_to:
285             ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
286
287         reg_name = action.regex_name
288         result_name = True
289         if reg_name:
290             ptrn = re.compile(str(reg_name))
291             _result = ptrn.search(str(obj.name))
292             if not _result:
293                 result_name = False
294         regex_n = not reg_name or result_name
295         ok = ok and regex_n
296         return ok
297
298     def do_action(self, cr, uid, action, model_obj, obj, context={}):
299         """ Do Action
300             @param self: The object pointer
301             @param cr: the current row, from the database cursor,
302             @param uid: the current user’s ID for security checks,
303             @param action: pass action
304             @param model_obj: pass Model object
305             @param context: A standard dictionary for contextual values """
306
307         if action.server_action_id:
308             context.update({'active_id':obj.id, 'active_ids':[obj.id]})
309             self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
310         write = {}
311
312         if hasattr(obj, 'user_id') and action.act_user_id:
313             obj.user_id = action.act_user_id
314             write['user_id'] = action.act_user_id.id
315         if hasattr(obj, 'date_action_last'):
316             write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
317         if hasattr(obj, 'state') and action.act_state:
318             obj.state = action.act_state
319             write['state'] = action.act_state
320
321         if hasattr(obj, 'categ_id') and action.act_categ_id:
322             obj.categ_id = action.act_categ_id
323             write['categ_id'] = action.act_categ_id.id
324
325         model_obj.write(cr, uid, [obj.id], write, context)
326
327         if hasattr(model_obj, 'remind_user') and action.act_remind_user:
328             model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
329         if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
330             model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
331         if action.act_method:
332             getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
333         emails = []
334         if hasattr(obj, 'user_id') and action.act_mail_to_user:
335             if obj.user_id and obj.user_id.address_id:
336                 emails.append(obj.user_id.address_id.email)
337
338         if action.act_mail_to_watchers:
339             emails += (action.act_email_cc or '').split(',')
340         if action.act_mail_to_email:
341             emails += (action.act_mail_to_email or '').split(',')
342         emails = filter(None, emails)
343         if len(emails) and action.act_mail_body:
344             emails = list(set(emails))
345             self.email_send(cr, uid, obj, emails, action.act_mail_body)
346         return True
347
348     def _action(self, cr, uid, ids, objects, scrit=None, context={}):
349         """ Do Action
350             @param self: The object pointer
351             @param cr: the current row, from the database cursor,
352             @param uid: the current user’s ID for security checks,
353             @param ids: List of Basic Action Rule’s IDs,
354             @param objects: pass objects
355             @param context: A standard dictionary for contextual values """
356         context.update({'action': True})
357         if not scrit:
358             scrit = []
359         for action in self.browse(cr, uid, ids):
360             level = action.max_level
361             if not level:
362                 break
363             model_obj = self.pool.get(action.name.model)
364             for obj in objects:
365                 ok = self.do_check(cr, uid, action, obj, context=context)
366                 if not ok:
367                     continue
368
369                 base = False
370                 if hasattr(obj, 'create_date') and action.trg_date_type=='create':
371                     base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
372                 elif hasattr(obj, 'create_date') and action.trg_date_type=='action_last':
373                     if hasattr(obj, 'date_action_last') and obj.date_action_last:
374                         base = mx.DateTime.strptime(obj.date_action_last, '%Y-%m-%d %H:%M:%S')
375                     else:
376                         base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
377                 elif hasattr(obj, 'date_deadline') and action.trg_date_type=='deadline' \
378                                 and obj.date_deadline:
379                     base = mx.DateTime.strptime(obj.date_deadline, '%Y-%m-%d %H:%M:%S')
380                 elif hasattr(obj, 'date') and action.trg_date_type=='date' and obj.date:
381                     base = mx.DateTime.strptime(obj.date, '%Y-%m-%d %H:%M:%S')
382                 if base:
383                     fnct = {
384                         'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval), 
385                         'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval), 
386                         'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval), 
387                         'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval), 
388                     }
389                     d = base + fnct[action.trg_date_range_type](action.trg_date_range)
390                     dt = d.strftime('%Y-%m-%d %H:%M:%S')
391                     ok = False
392                     if hasattr(obj, 'date_action_last') and hasattr(obj, 'date_action_next'):
393                         ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
394                                 ((not obj.date_action_next) or \
395                                 (dt >= obj.date_action_next and \
396                                 obj.date_action_last < obj.date_action_next))
397                         if not ok:
398                             if not obj.date_action_next or dt < obj.date_action_next:
399                                 obj.date_action_next = dt
400                                 model_obj.write(cr, uid, [obj.id], {'date_action_next': dt}, context)
401                 else:
402                     ok = action.trg_date_type=='none'
403
404                 if ok:
405                     self.do_action(cr, uid, action, model_obj, obj, context)
406                     break
407             level -= 1
408         context.update({'action': False})
409         return True
410
411     def _check_mail(self, cr, uid, ids, context=None):
412         """ Check Mail
413             @param self: The object pointer
414             @param cr: the current row, from the database cursor,
415             @param uid: the current user’s ID for security checks,
416             @param ids: List of Action Rule’s IDs
417             @param context: A standard dictionary for contextual values """
418
419         empty = orm.browse_null()
420         rule_obj = self.pool.get('base.action.rule')
421         for rule in self.browse(cr, uid, ids):
422             if rule.act_mail_body:
423                 try:
424                     rule_obj.format_mail(empty, rule.act_mail_body)
425                 except (ValueError, KeyError, TypeError):
426                     return False
427         return True
428
429     _constraints = [
430         (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']), 
431     ]
432
433 base_action_rule()
434
435
436 class ir_cron(osv.osv):
437     _inherit = 'ir.cron' 
438     
439     def _poolJobs(self, db_name, check=False):
440         try:
441             db, pool = pooler.get_db_and_pool(db_name)
442         except:
443             return False
444         cr = db.cursor()
445         try:
446             next = datetime.now().strftime('%Y-%m-%d %H:00:00')
447             # Putting nextcall always less than current time in order to call it every time
448             cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
449             cr.commit()
450             res = super(ir_cron, self)._poolJobs(db_name, check=check)
451         finally:
452             cr.commit()
453             cr.close()
454
455 ir_cron()
456
457
458 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: