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