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