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