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 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
32 class base_action_rule(osv.osv):
33 """ Base Action Rules """
35 _name = 'base.action.rule'
36 _description = 'Action Rules'
38 def _state_get(self, cr, uid, context={}):
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)
46 def state_get(self, cr, uid, context={}):
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 """
54 def priority_get(self, cr, uid, context={}):
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 """
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([
72 ('create', 'Creation Date'),
73 ('action_last', 'Last Action 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),
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 \
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),
117 'active': lambda *a: True,
118 'trg_date_type': lambda *a: 'none',
119 'trg_date_range_type': lambda *a: 'day',
120 'act_mail_to_user': lambda *a: 0,
121 'act_remind_partner': lambda *a: 0,
122 'act_remind_user': lambda *a: 0,
123 'act_mail_to_watchers': lambda *a: 0,
128 def onchange_model_id(self, cr, uid, ids, name):
129 #This is not a good solution as it will affect the domain only on onchange
130 res = {'domain':{'filter_id':[]}}
132 model_name = self.pool.get('ir.model').read(cr, uid, [name], ['model'])
134 mod_name = model_name[0]['model']
135 res['domain'] = {'filter_id': [('model_id','=',mod_name)]}
137 res['value'] = {'filter_id':False}
140 def pre_action(self, cr, uid, ids, model, context=None):
141 # Searching for action rules
142 cr.execute("SELECT model.model, rule.id FROM base_action_rule rule \
143 LEFT JOIN ir_model model on (model.id = rule.model_id) \
146 # Check if any rule matching with current object
147 for obj_name, rule_id in res:
148 if not (model == obj_name):
151 obj = self.pool.get(obj_name)
152 self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context))
155 def _create(self, old_create, model, context=None):
158 def make_call_old(cr, uid, vals, context=context):
159 new_id = old_create(cr, uid, vals, context=context)
160 if not context.get('action'):
161 self.pre_action(cr, uid, [new_id], model, context=context)
165 def _write(self, old_write, model, context=None):
168 def make_call_old(cr, uid, ids, vals, context=context):
169 if isinstance(ids, (str, int, long)):
171 if not context.get('action'):
172 self.pre_action(cr, uid, ids, model, context=context)
173 return old_write(cr, uid, ids, vals, context=context)
176 def _register_hook(self, cr, uid, ids, context=None):
179 for action_rule in self.browse(cr, uid, ids, context=context):
180 model = action_rule.model_id.model
181 obj_pool = self.pool.get(model)
182 obj_pool.__setattr__('create', self._create(obj_pool.create, model, context=context))
183 obj_pool.__setattr__('write', self._write(obj_pool.write, model, context=context))
186 def create(self, cr, uid, vals, context=None):
187 res_id = super(base_action_rule, self).create(cr, uid, vals, context)
188 self._register_hook(cr, uid, [res_id], context=context)
191 def write(self, cr, uid, ids, vals, context=None):
192 res = super(base_action_rule, self).write(cr, uid, ids, vals, context)
193 self._register_hook(cr, uid, ids, context=context)
196 def _check(self, cr, uid, automatic=False, use_new_cursor=False, \
199 This Function is call by scheduler.
201 rule_pool = self.pool.get('base.action.rule')
202 rule_ids = rule_pool.search(cr, uid, [], context=context)
203 return self._register_hook(cr, uid, rule_ids, context=context)
206 def format_body(self, body):
207 """ Foramat Action rule's body
208 @param self: The object pointer """
209 return body and tools.ustr(body) or ''
211 def format_mail(self, obj, body):
213 @param self: The object pointer """
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 '/',
229 return self.format_body(body % data)
231 def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context={}):
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 body = self.format_mail(obj, body)
241 if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.address_id and\
242 obj.user_id.address_id.email:
243 emailfrom = obj.user_id.address_id.email
245 name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
246 emailfrom = tools.ustr(emailfrom)
249 raise osv.except_osv(_('Error!'),
250 _("No E-Mail ID Found for your Company address!"))
251 return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
254 def do_check(self, cr, uid, action, obj, context={}):
256 @param self: The object pointer
257 @param cr: the current row, from the database cursor,
258 @param uid: the current user’s ID for security checks,
259 @param context: A standard dictionary for contextual values """
262 if action.model_id.model == action.filter_id.model_id:
263 context.update(eval(action.filter_id.context))
264 obj_ids = obj._table.search(cr, uid, eval(action.filter_id.domain), context=context)
265 if not obj.id in obj_ids:
269 if hasattr(obj, 'user_id'):
270 ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
271 if hasattr(obj, 'partner_id'):
272 ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
274 not action.trg_partner_categ_id.id or
276 obj.partner_id.id and
277 (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
280 state_to = context.get('state_to', False)
281 if hasattr(obj, 'state'):
282 ok = ok and (not action.trg_state_from or action.trg_state_from==obj.state)
284 ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
285 elif action.trg_state_to:
287 reg_name = action.regex_name
290 ptrn = re.compile(str(reg_name))
291 _result = ptrn.search(str(obj.name))
294 regex_n = not reg_name or result_name
298 def do_action(self, cr, uid, action, model_obj, obj, context={}):
300 @param self: The object pointer
301 @param cr: the current row, from the database cursor,
302 @param uid: the current user’s ID for security checks,
303 @param action: pass action
304 @param model_obj: pass Model object
305 @param context: A standard dictionary for contextual values """
307 if action.server_action_id:
308 context.update({'active_id':obj.id, 'active_ids':[obj.id]})
309 self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
312 if hasattr(obj, 'user_id') and action.act_user_id:
313 obj.user_id = action.act_user_id
314 write['user_id'] = action.act_user_id.id
315 if hasattr(obj, 'date_action_last'):
316 write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
317 if hasattr(obj, 'state') and action.act_state:
318 obj.state = action.act_state
319 write['state'] = action.act_state
321 if hasattr(obj, 'categ_id') and action.act_categ_id:
322 obj.categ_id = action.act_categ_id
323 write['categ_id'] = action.act_categ_id.id
325 model_obj.write(cr, uid, [obj.id], write, context)
327 if hasattr(model_obj, 'remind_user') and action.act_remind_user:
328 model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
329 if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
330 model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
331 if action.act_method:
332 getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
334 if hasattr(obj, 'user_id') and action.act_mail_to_user:
335 if obj.user_id and obj.user_id.address_id:
336 emails.append(obj.user_id.address_id.email)
338 if action.act_mail_to_watchers:
339 emails += (action.act_email_cc or '').split(',')
340 if action.act_mail_to_email:
341 emails += (action.act_mail_to_email or '').split(',')
342 emails = filter(None, emails)
343 if len(emails) and action.act_mail_body:
344 emails = list(set(emails))
345 self.email_send(cr, uid, obj, emails, action.act_mail_body)
348 def _action(self, cr, uid, ids, objects, scrit=None, context={}):
350 @param self: The object pointer
351 @param cr: the current row, from the database cursor,
352 @param uid: the current user’s ID for security checks,
353 @param ids: List of Basic Action Rule’s IDs,
354 @param objects: pass objects
355 @param context: A standard dictionary for contextual values """
356 context.update({'action': True})
359 for action in self.browse(cr, uid, ids):
360 model_obj = self.pool.get(action.model_id.model)
362 ok = self.do_check(cr, uid, action, obj, context=context)
367 if action.trg_date_type=='create' and hasattr(obj, 'create_date'):
368 base = datetime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
369 elif action.trg_date_type=='action_last' and hasattr(obj, 'create_date'):
370 if hasattr(obj, 'date_action_last') and obj.date_action_last:
371 base = datetime.strptime(obj.date_action_last, '%Y-%m-%d %H:%M:%S')
373 base = datetime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
374 elif action.trg_date_type=='deadline' and hasattr(obj, 'date_deadline') \
375 and obj.date_deadline:
376 base = datetime.strptime(obj.date_deadline, '%Y-%m-%d %H:%M:%S')
377 elif action.trg_date_type=='date' and hasattr(obj, 'date') and obj.date:
378 base = datetime.strptime(obj.date, '%Y-%m-%d %H:%M:%S')
381 'minutes': lambda interval: timedelta(minutes=interval),
382 'day': lambda interval: timedelta(days=interval),
383 'hour': lambda interval: timedelta(hours=interval),
384 'month': lambda interval: timedelta(months=interval),
386 d = base + fnct[action.trg_date_range_type](action.trg_date_range)
387 dt = d.strftime('%Y-%m-%d %H:%M:%S')
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))
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)
399 ok = action.trg_date_type == 'none'
402 self.do_action(cr, uid, action, model_obj, obj, context)
404 context.update({'action': False})
407 def _check_mail(self, cr, uid, ids, context=None):
409 @param self: The object pointer
410 @param cr: the current row, from the database cursor,
411 @param uid: the current user’s ID for security checks,
412 @param ids: List of Action Rule’s IDs
413 @param context: A standard dictionary for contextual values """
415 empty = orm.browse_null()
416 rule_obj = self.pool.get('base.action.rule')
417 for rule in self.browse(cr, uid, ids):
418 if rule.act_mail_body:
420 rule_obj.format_mail(empty, rule.act_mail_body)
421 except (ValueError, KeyError, TypeError):
426 (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
432 class ir_cron(osv.osv):
435 def _poolJobs(self, db_name, check=False):
437 db = pooler.get_db(db_name)
442 next = datetime.now().strftime('%Y-%m-%d %H:00:00')
443 # Putting nextcall always less than current time in order to call it every time
444 cr.execute('UPDATE ir_cron set nextcall = \'%s\' where numbercall<>0 and active and model=\'base.action.rule\' ' % (next))
449 super(ir_cron, self)._poolJobs(db_name, check=check)
454 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: