1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
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
33 def get_datetime(date_field):
34 '''Return a datetime from a date string or a datetime string'''
35 #complete date time if date_field contains only a date
36 date_split = date_field.split(' ')
37 if len(date_split) == 1:
38 date_field = date_split[0] + " 00:00:00"
40 return datetime.strptime(date_field[:19], '%Y-%m-%d %H:%M:%S')
43 class base_action_rule(osv.osv):
44 """ Base Action Rules """
46 _name = 'base.action.rule'
47 _description = 'Action Rules'
49 def _state_get(self, cr, uid, context=None):
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 return self.state_get(cr, uid, context=context)
57 def state_get(self, cr, uid, context=None):
59 @param self: The object pointer
60 @param cr: the current row, from the database cursor,
61 @param uid: the current user’s ID for security checks,
62 @param context: A standard dictionary for contextual values """
65 def priority_get(self, cr, uid, context=None):
67 @param self: The object pointer
68 @param cr: the current row, from the database cursor,
69 @param uid: the current user’s ID for security checks,
70 @param context: A standard dictionary for contextual values """
74 'name': fields.char('Rule Name', size=64, required=True),
75 'model_id': fields.many2one('ir.model', 'Object', required=True),
76 'create_date': fields.datetime('Create Date', readonly=1),
77 'active': fields.boolean('Active', help="If the active field is set to False,\
78 it will allow you to hide the rule without removing it."),
79 'sequence': fields.integer('Sequence', help="Gives the sequence order \
80 when displaying a list of rules."),
81 'trg_date_type': fields.selection([
83 ('create', 'Creation Date'),
84 ('action_last', 'Last Action Date'),
86 ('deadline', 'Deadline'),
87 ], 'Trigger Date', size=16),
88 'trg_date_range': fields.integer('Delay after trigger date', \
89 help="Delay After Trigger Date,\
90 specifies you can put a negative number. If you need a delay before the \
91 trigger date, like sending a reminder 15 minutes before a meeting."),
92 'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'), \
93 ('day', 'Days'), ('month', 'Months')], 'Delay type'),
94 'trg_user_id': fields.many2one('res.users', 'Responsible'),
95 'trg_partner_id': fields.many2one('res.partner', 'Partner'),
96 'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
97 'trg_state_from': fields.selection(_state_get, 'State', size=16),
98 'trg_state_to': fields.selection(_state_get, 'Button Pressed', size=16),
100 'act_method': fields.char('Call Object Method', size=64),
101 'act_user_id': fields.many2one('res.users', 'Set Responsible to'),
102 'act_state': fields.selection(_state_get, 'Set State to', size=16),
103 'act_email_cc': fields.char('Add Watchers (Cc)', size=250, help="\
104 These people will receive a copy of the future communication between partner \
105 and users by email"),
106 'act_remind_partner': fields.boolean('Remind Partner', help="Check \
107 this if you want the rule to send a reminder by email to the partner."),
108 'act_remind_user': fields.boolean('Remind Responsible', help="Check \
109 this if you want the rule to send a reminder by email to the user."),
110 'act_reply_to': fields.char('Reply-To', size=64),
111 '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."),
112 'act_mail_to_user': fields.boolean('Mail to Responsible', help="Check\
113 this if you want the rule to send an email to the responsible person."),
114 'act_mail_to_watchers': fields.boolean('Mail to Watchers (CC)',
115 help="Check this if you want \
116 the rule to mark CC(mail to any other person defined in actions)."),
117 'act_mail_to_email': fields.char('Mail to these Emails', size=128, \
118 help="Email-id of the persons whom mail is to be sent"),
119 'act_mail_body': fields.text('Mail body', help="Content of mail"),
120 'regex_name': fields.char('Regex on Resource Name', size=128, help="Regular expression for matching name of the resource\
121 \ne.g.: 'urgent.*' will search for records having name starting with the string 'urgent'\
122 \nNote: This is case sensitive search."),
123 '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"),
124 'filter_id':fields.many2one('ir.filters', 'Filter', required=False),
125 'act_email_from' : fields.char('Email From', size=64, required=False,
126 help="Use a python expression to specify the right field on which one than we will use for the 'From' field of the header"),
127 'act_email_to' : fields.char('Email To', size=64, required=False,
128 help="Use a python expression to specify the right field on which one than we will use for the 'To' field of the header"),
129 'last_run': fields.datetime('Last Run', readonly=1),
133 'active': lambda *a: True,
134 'trg_date_type': lambda *a: 'none',
135 'trg_date_range_type': lambda *a: 'day',
136 'act_mail_to_user': lambda *a: 0,
137 'act_remind_partner': lambda *a: 0,
138 'act_remind_user': lambda *a: 0,
139 'act_mail_to_watchers': lambda *a: 0,
144 def onchange_model_id(self, cr, uid, ids, name):
145 #This is not a good solution as it will affect the domain only on onchange
146 res = {'domain':{'filter_id':[]}}
148 model_name = self.pool.get('ir.model').read(cr, uid, [name], ['model'])
150 mod_name = model_name[0]['model']
151 res['domain'] = {'filter_id': [('model_id','=',mod_name)]}
153 res['value'] = {'filter_id':False}
156 def post_action(self, cr, uid, ids, model, context=None):
157 # Searching for action rules
158 cr.execute("SELECT model.model, rule.id FROM base_action_rule rule \
159 LEFT JOIN ir_model model on (model.id = rule.model_id) \
162 # Check if any rule matching with current object
163 for obj_name, rule_id in res:
164 if not (model == obj_name):
165 continue # TODO add this condition in the WHERE clause above.
167 obj = self.pool.get(obj_name)
168 # If the rule doesn't involve a time condition, run it immediately
169 # Otherwise we let the scheduler run the action
170 if self.browse(cr, uid, rule_id, context=context).trg_date_type == 'none':
171 self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context), context=context)
174 def _create(self, old_create, model, context=None):
176 Return a wrapper around `old_create` calling both `old_create` and
177 `post_action`, in that order.
179 def wrapper(cr, uid, vals, context=context):
182 new_id = old_create(cr, uid, vals, context=context)
183 if not context.get('action'):
184 self.post_action(cr, uid, [new_id], model, context=context)
188 def _write(self, old_write, model, context=None):
190 Return a wrapper around `old_write` calling both `old_write` and
191 `post_action`, in that order.
193 def wrapper(cr, uid, ids, vals, context=context):
196 if isinstance(ids, (str, int, long)):
198 old_write(cr, uid, ids, vals, context=context)
199 if not context.get('action'):
200 self.post_action(cr, uid, ids, model, context=context)
204 def _register_hook(self, cr, uid, ids, context=None):
206 Wrap every `create` and `write` methods of the models specified by
207 the rules (given by `ids`).
209 for action_rule in self.browse(cr, uid, ids, context=context):
210 model = action_rule.model_id.model
211 obj_pool = self.pool.get(model)
212 if not hasattr(obj_pool, 'base_action_ruled'):
213 obj_pool.create = self._create(obj_pool.create, model, context=context)
214 obj_pool.write = self._write(obj_pool.write, model, context=context)
215 obj_pool.base_action_ruled = True
219 def create(self, cr, uid, vals, context=None):
220 res_id = super(base_action_rule, self).create(cr, uid, vals, context=context)
221 self._register_hook(cr, uid, [res_id], context=context)
224 def write(self, cr, uid, ids, vals, context=None):
225 super(base_action_rule, self).write(cr, uid, ids, vals, context=context)
226 self._register_hook(cr, uid, ids, context=context)
229 def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
232 This Function is call by scheduler.
234 rule_pool = self.pool.get('base.action.rule')
235 rule_ids = rule_pool.search(cr, uid, [], context=context)
236 self._register_hook(cr, uid, rule_ids, context=context)
238 rules = self.browse(cr, uid, rule_ids, context=context)
240 model = rule.model_id.model
241 model_pool = self.pool.get(model)
244 last_run = get_datetime(rule.last_run)
246 for obj_id in model_pool.search(cr, uid, [], context=context):
247 obj = model_pool.browse(cr, uid, obj_id, context=context)
248 # Calculate when this action should next occur for this object
250 if rule.trg_date_type=='create' and hasattr(obj, 'create_date'):
251 base = obj.create_date
252 elif (rule.trg_date_type=='action_last'
253 and hasattr(obj, 'create_date')):
254 if hasattr(obj, 'date_action_last') and obj.date_action_last:
255 base = obj.date_action_last
257 base = obj.create_date
258 elif (rule.trg_date_type=='deadline'
259 and hasattr(obj, 'date_deadline')
260 and obj.date_deadline):
261 base = obj.date_deadline
262 elif (rule.trg_date_type=='date'
263 and hasattr(obj, 'date')
268 'minutes': lambda interval: timedelta(minutes=interval),
269 'day': lambda interval: timedelta(days=interval),
270 'hour': lambda interval: timedelta(hours=interval),
271 'month': lambda interval: timedelta(months=interval),
273 base = get_datetime(base)
274 delay = fnct[rule.trg_date_range_type](rule.trg_date_range)
275 action_date = base + delay
276 if (not last_run or (last_run <= action_date < now)):
277 self._action(cr, uid, [rule.id], [obj], context=context)
278 rule_pool.write(cr, uid, [rule.id], {'last_run': now},
281 def format_body(self, body):
282 """ Foramat Action rule's body
283 @param self: The object pointer """
284 return body and tools.ustr(body) or ''
286 def format_mail(self, obj, body):
289 'object_subject': hasattr(obj, 'name') and obj.name or False,
290 'object_date': hasattr(obj, 'date') and obj.date or False,
291 'object_description': hasattr(obj, 'description') and obj.description or False,
292 'object_user': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.name) or '/',
293 'object_user_email': hasattr(obj, 'user_id') and (obj.user_id and \
294 obj.user_id.user_email) or '/',
295 'object_user_phone': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and \
296 obj.partner_address_id.phone) or '/',
297 'partner': hasattr(obj, 'partner_id') and (obj.partner_id and obj.partner_id.name) or '/',
298 'partner_email': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and\
299 obj.partner_address_id.email) or '/',
301 return self.format_body(body % data)
303 def email_send(self, cr, uid, obj, emails, body, emailfrom=None, context=None):
305 @param self: The object pointer
306 @param cr: the current row, from the database cursor,
307 @param uid: the current user’s ID for security checks,
308 @param email: pass the emails
309 @param emailfrom: Pass name the email From else False
310 @param context: A standard dictionary for contextual values """
313 emailfrom = tools.config.get('email_from', False)
318 mail_message = self.pool.get('mail.message')
319 body = self.format_mail(obj, body)
321 if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.user_email:
322 emailfrom = obj.user_id.user_email
324 name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
325 emailfrom = tools.ustr(emailfrom)
328 raise osv.except_osv(_('Error!'),
329 _("No E-Mail ID Found for your Company address!"))
330 return mail_message.schedule_with_attach(cr, uid, emailfrom, emails, name, body, model='base.action.rule', reply_to=reply_to, res_id=obj.id)
333 def do_check(self, cr, uid, action, obj, context=None):
335 @param self: The object pointer
336 @param cr: the current row, from the database cursor,
337 @param uid: the current user’s ID for security checks,
338 @param context: A standard dictionary for contextual values """
343 if action.model_id.model == action.filter_id.model_id:
344 context.update(eval(action.filter_id.context))
345 obj_ids = obj._table.search(cr, uid, eval(action.filter_id.domain), context=context)
346 if not obj.id in obj_ids:
350 if getattr(obj, 'user_id', False):
351 ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
352 if getattr(obj, 'partner_id', False):
353 ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
355 not action.trg_partner_categ_id.id or
357 obj.partner_id.id and
358 (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
361 state_to = context.get('state_to', False)
362 state = getattr(obj, 'state', False)
364 ok = ok and (not action.trg_state_from or action.trg_state_from==state)
366 ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
367 elif action.trg_state_to:
369 reg_name = action.regex_name
372 ptrn = re.compile(str(reg_name))
373 _result = ptrn.search(str(obj.name))
376 regex_n = not reg_name or result_name
380 def do_action(self, cr, uid, action, model_obj, obj, context=None):
382 @param self: The object pointer
383 @param cr: the current row, from the database cursor,
384 @param uid: the current user’s ID for security checks,
385 @param action: pass action
386 @param model_obj: pass Model object
387 @param context: A standard dictionary for contextual values """
391 if action.server_action_id:
392 context.update({'active_id':obj.id, 'active_ids':[obj.id]})
393 self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
396 if hasattr(obj, 'user_id') and action.act_user_id:
397 obj.user_id = action.act_user_id
398 write['user_id'] = action.act_user_id.id
399 if hasattr(obj, 'date_action_last'):
400 write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
401 if hasattr(obj, 'state') and action.act_state:
402 obj.state = action.act_state
403 write['state'] = action.act_state
405 if hasattr(obj, 'categ_id') and action.act_categ_id:
406 obj.categ_id = action.act_categ_id
407 write['categ_id'] = action.act_categ_id.id
409 model_obj.write(cr, uid, [obj.id], write, context)
411 if hasattr(model_obj, 'remind_user') and action.act_remind_user:
412 model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
413 if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
414 model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
415 if action.act_method:
416 getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
419 if hasattr(obj, 'user_id') and action.act_mail_to_user:
421 emails.append(obj.user_id.user_email)
423 if action.act_mail_to_watchers:
424 emails += (action.act_email_cc or '').split(',')
425 if action.act_mail_to_email:
426 emails += (action.act_mail_to_email or '').split(',')
428 locals_for_emails = {
429 'user' : self.pool.get('res.users').browse(cr, uid, uid, context=context),
433 if action.act_email_to:
434 emails.append(safe_eval(action.act_email_to, {}, locals_for_emails))
436 emails = filter(None, emails)
437 if len(emails) and action.act_mail_body:
438 emails = list(set(emails))
439 email_from = safe_eval(action.act_email_from, {}, locals_for_emails)
442 return re.findall(r'([^ ,<@]+@[^> ,]+)', text or '')
443 emails = to_email(','.join(filter(None, emails)))
444 email_froms = to_email(email_from)
446 self.email_send(cr, uid, obj, emails, action.act_mail_body, emailfrom=email_froms[0])
449 def _action(self, cr, uid, ids, objects, scrit=None, context=None):
451 @param self: The object pointer
452 @param cr: the current row, from the database cursor,
453 @param uid: the current user’s ID for security checks,
454 @param ids: List of Basic Action Rule’s IDs,
455 @param objects: pass objects
456 @param context: A standard dictionary for contextual values """
460 context.update({'action': True})
464 for action in self.browse(cr, uid, ids, context=context):
466 if self.do_check(cr, uid, action, obj, context=context):
467 model_obj = self.pool.get(action.model_id.model)
468 self.do_action(cr, uid, action, model_obj, obj, context=context)
470 context.update({'action': False})
473 def _check_mail(self, cr, uid, ids, context=None):
475 @param self: The object pointer
476 @param cr: the current row, from the database cursor,
477 @param uid: the current user’s ID for security checks,
478 @param ids: List of Action Rule’s IDs
479 @param context: A standard dictionary for contextual values """
481 empty = orm.browse_null()
482 rule_obj = self.pool.get('base.action.rule')
483 for rule in self.browse(cr, uid, ids, context=context):
484 if rule.act_mail_body:
486 rule_obj.format_mail(empty, rule.act_mail_body)
487 except (ValueError, KeyError, TypeError):
492 (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
498 class ir_cron(osv.osv):
502 def _poolJobs(self, db_name, check=False):
503 if not self._init_done:
504 self._init_done = True
506 db = pooler.get_db(db_name)
511 next = datetime.now().strftime('%Y-%m-%d %H:00:00')
512 # Putting nextcall always less than current time in order to call it every time
513 cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
518 super(ir_cron, self)._poolJobs(db_name, check=check)
523 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: