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