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