[IMP]: base_action_rule: Applied reverted changes of changes related to create/write...
[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 m.model, r.id  from base_action_rule r left join ir_model m on (m.id = r.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 new_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 new_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 create(self, cr, uid, vals, context=None):
172         if not context:
173             context = {}
174         res_id = super(base_action_rule, self).create(cr, uid, vals, context)
175         model_pool = self.pool.get('ir.model')
176         model = model_pool.browse(cr, uid, vals.get('name'), context=context).model
177         obj_pool = self.pool.get(model)
178         obj_pool.__setattr__('old_create', obj_pool.create)
179         obj_pool.__setattr__('old_write', obj_pool.write)
180         obj_pool.__setattr__('create', self.new_create(obj_pool.create, model, context=context))
181         obj_pool.__setattr__('write', self.new_write(obj_pool.write, model, context=context))
182         return res_id
183     
184     def write(self, cr, uid, ids, vals, context=None):
185         res = super(base_action_rule, self).write(cr, uid, ids, vals, context)
186         model_pool = self.pool.get('ir.model')
187         if not context:
188             context = {}
189         for rule in self.browse(cr, uid, ids, context=context):
190             model = model_pool.browse(cr, uid, rule.name.id, context=context).model
191             obj_pool = self.pool.get(model)
192             obj_pool.__setattr__('old_create', obj_pool.create)
193             obj_pool.__setattr__('old_write', obj_pool.write)
194             obj_pool.__setattr__('create', self.new_create(obj_pool.create, model, context=context))
195             obj_pool.__setattr__('write', self.new_write(obj_pool.write, model, context=context))
196         return res
197
198     def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
199                        context=None):
200         rule_pool= self.pool.get('base.action.rule')
201         rule_ids = rule_pool.search(cr, uid, [], context=context)
202         return rule_pool.write(cr, uid, rule_ids, {}, context=context)
203         
204
205     def format_body(self, body):
206         """ Foramat Action rule's body
207             @param self: The object pointer """
208
209         return body and tools.ustr(body) or ''
210
211     def format_mail(self, obj, body):
212         """ Foramat Mail
213             @param self: The object pointer """
214
215         data = {
216             'object_id': obj.id, 
217             'object_subject': hasattr(obj, 'name') and obj.name or False, 
218             'object_date': hasattr(obj, 'date') and obj.date or False, 
219             'object_description': hasattr(obj, 'description') and obj.description or False, 
220             'object_user': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.name) or '/', 
221             'object_user_email': hasattr(obj, 'user_id') and (obj.user_id and \
222                                     obj.user_id.address_id and obj.user_id.address_id.email) or '/', 
223             'object_user_phone': hasattr(obj, 'user_id') and (obj.user_id and\
224                                      obj.user_id.address_id and obj.user_id.address_id.phone) or '/', 
225             'partner': hasattr(obj, 'partner_id') and (obj.partner_id and obj.partner_id.name) or '/', 
226             'partner_email': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and\
227                                          obj.partner_address_id.email) or '/', 
228         }
229         return self.format_body(body % data)
230
231     def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context={}):
232         """ send email
233             @param self: The object pointer
234             @param cr: the current row, from the database cursor,
235             @param uid: the current user’s ID for security checks,
236             @param email: pass the emails
237             @param emailfrom: Pass name the email From else False
238             @param context: A standard dictionary for contextual values """
239
240         body = self.format_mail(obj, body)
241         if not emailfrom:
242             if hasattr(obj, 'user_id')  and obj.user_id and obj.user_id.address_id and\
243                         obj.user_id.address_id.email:
244                 emailfrom = obj.user_id.address_id.email
245
246         name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
247         emailfrom = tools.ustr(emailfrom)
248         reply_to = emailfrom
249         if not emailfrom:
250             raise osv.except_osv(_('Error!'), 
251                     _("No E-Mail ID Found for your Company address!"))
252         return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
253
254
255     def do_check(self, cr, uid, action, obj, context={}):
256         """ check Action
257             @param self: The object pointer
258             @param cr: the current row, from the database cursor,
259             @param uid: the current user’s ID for security checks,
260             @param context: A standard dictionary for contextual values """
261
262         ok = True
263         if eval(action.domain):
264             obj_ids = obj._table.search(cr, uid, eval(action.domain), context=context)
265             if not obj.id in obj_ids:
266                 ok = False
267         if hasattr(obj, 'user_id'):
268             ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
269         if hasattr(obj, 'partner_id'):
270             ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
271             ok = ok and (
272                 not action.trg_partner_categ_id.id or
273                 (
274                     obj.partner_id.id and
275                     (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
276                 )
277             )
278         state_to = context.get('state_to', False)
279         if hasattr(obj, 'state'):
280             ok = ok and (not action.trg_state_from or action.trg_state_from==obj.state)
281         if state_to:
282             ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
283
284         reg_name = action.regex_name
285         result_name = True
286         if reg_name:
287             ptrn = re.compile(str(reg_name))
288             _result = ptrn.search(str(obj.name))
289             if not _result:
290                 result_name = False
291         regex_n = not reg_name or result_name
292         ok = ok and regex_n
293         return ok
294
295     def do_action(self, cr, uid, action, model_obj, obj, context={}):
296         """ Do Action
297             @param self: The object pointer
298             @param cr: the current row, from the database cursor,
299             @param uid: the current user’s ID for security checks,
300             @param action: pass action
301             @param model_obj: pass Model object
302             @param context: A standard dictionary for contextual values """
303
304         if action.server_action_id:
305             context.update({'active_id':obj.id, 'active_ids':[obj.id]})
306             self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
307         write = {}
308
309         if hasattr(obj, 'user_id') and action.act_user_id:
310             obj.user_id = action.act_user_id
311             write['user_id'] = action.act_user_id.id
312         if hasattr(obj, 'date_action_last'):
313             write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
314         if hasattr(obj, 'state') and action.act_state:
315             obj.state = action.act_state
316             write['state'] = action.act_state
317
318         if hasattr(obj, 'categ_id') and action.act_categ_id:
319             obj.categ_id = action.act_categ_id
320             write['categ_id'] = action.act_categ_id.id
321
322         model_obj.write(cr, uid, [obj.id], write, context)
323
324         if hasattr(model_obj, 'remind_user') and action.act_remind_user:
325             model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
326         if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
327             model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
328         if action.act_method:
329             getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
330         emails = []
331         if hasattr(obj, 'user_id') and action.act_mail_to_user:
332             if obj.user_id and obj.user_id.address_id:
333                 emails.append(obj.user_id.address_id.email)
334
335         if action.act_mail_to_watchers:
336             emails += (action.act_email_cc or '').split(',')
337         if action.act_mail_to_email:
338             emails += (action.act_mail_to_email or '').split(',')
339         emails = filter(None, emails)
340         if len(emails) and action.act_mail_body:
341             emails = list(set(emails))
342             self.email_send(cr, uid, obj, emails, action.act_mail_body)
343         return True
344
345     def _action(self, cr, uid, ids, objects, scrit=None, context={}):
346         """ Do Action
347             @param self: The object pointer
348             @param cr: the current row, from the database cursor,
349             @param uid: the current user’s ID for security checks,
350             @param ids: List of Basic Action Rule’s IDs,
351             @param objects: pass objects
352             @param context: A standard dictionary for contextual values """
353         context.update({'action': True})
354         if not scrit:
355             scrit = []
356         for action in self.browse(cr, uid, ids):
357             level = action.max_level
358             if not level:
359                 break
360             model_obj = self.pool.get(action.name.model)
361             for obj in objects:
362                 ok = self.do_check(cr, uid, action, obj, context=context)
363                 if not ok:
364                     continue
365
366                 base = False
367                 if hasattr(obj, 'create_date') and action.trg_date_type=='create':
368                     base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
369                 elif hasattr(obj, 'create_date') and action.trg_date_type=='action_last':
370                     if hasattr(obj, 'date_action_last') and obj.date_action_last:
371                         base = mx.DateTime.strptime(obj.date_action_last, '%Y-%m-%d %H:%M:%S')
372                     else:
373                         base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
374                 elif hasattr(obj, 'date_deadline') and action.trg_date_type=='deadline' \
375                                 and obj.date_deadline:
376                     base = mx.DateTime.strptime(obj.date_deadline, '%Y-%m-%d %H:%M:%S')
377                 elif hasattr(obj, 'date') and action.trg_date_type=='date' and obj.date:
378                     base = mx.DateTime.strptime(obj.date, '%Y-%m-%d %H:%M:%S')
379                 if base:
380                     fnct = {
381                         'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval), 
382                         'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval), 
383                         'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval), 
384                         'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval), 
385                     }
386                     d = base + fnct[action.trg_date_range_type](action.trg_date_range)
387                     dt = d.strftime('%Y-%m-%d %H:%M:%S')
388                     ok = False
389                     if hasattr(obj, 'date_action_last') and hasattr(obj, 'date_action_next'):
390                         ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
391                                 ((not obj.date_action_next) or \
392                                 (dt >= obj.date_action_next and \
393                                 obj.date_action_last < obj.date_action_next))
394                         if not ok:
395                             if not obj.date_action_next or dt < obj.date_action_next:
396                                 obj.date_action_next = dt
397                                 model_obj.write(cr, uid, [obj.id], {'date_action_next': dt}, context)
398                 else:
399                     ok = action.trg_date_type=='none'
400
401                 if ok:
402                     self.do_action(cr, uid, action, model_obj, obj, context)
403                     break
404             level -= 1
405         context.update({'action': False})
406         return True
407
408     def _check_mail(self, cr, uid, ids, context=None):
409         """ Check Mail
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 Action Rule’s IDs
414             @param context: A standard dictionary for contextual values """
415
416         empty = orm.browse_null()
417         rule_obj = self.pool.get('base.action.rule')
418         for rule in self.browse(cr, uid, ids):
419             if rule.act_mail_body:
420                 try:
421                     rule_obj.format_mail(empty, rule.act_mail_body)
422                 except (ValueError, KeyError, TypeError):
423                     return False
424         return True
425
426     _constraints = [
427         (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']), 
428     ]
429
430 base_action_rule()
431
432
433 class ir_cron(osv.osv):
434     _inherit = 'ir.cron' 
435     
436     def _poolJobs(self, db_name, check=False):
437         try:
438             db, pool = pooler.get_db_and_pool(db_name)
439         except:
440             return False
441         cr = db.cursor()
442         try:
443             next = datetime.now().strftime('%Y-%m-%d %H:00:00')
444             # Putting nextcall always less than current time in order to call it every time
445             cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
446             cr.commit()
447             res = super(ir_cron, self)._poolJobs(db_name, check=check)
448         finally:
449             cr.commit()
450             cr.close()
451
452 ir_cron()
453
454
455 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: