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