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