6 from osv import fields, osv, orm
7 from osv.orm import except_orm
8 from tools.translate import _
13 ('cancel', 'Cancelled'),
18 AVAILABLE_PRIORITIES = [
26 class base_action_rule(osv.osv):
27 _name = 'base.action.rule'
28 _description = 'Action Rules'
30 def _get_max_level(self, cr, uid, ids, field_name, arg, context=None):
32 for check in self.browse(cr, uid, ids):
33 if check.rule_lines and len(check.rule_lines) < 15:
34 res[check.id] = len(check.rule_lines)
35 elif len(check.rule_lines) > 15:
36 raise osv.except_osv(_('Error !'), _('Max Level exceeded.'))
40 'name': fields.many2one('ir.model', 'Model', required=True, states={'activate': [('readonly', True)]}),
41 'max_level': fields.function(_get_max_level, method=True, string='Max Level',
42 type='integer', store=True, help='Specifies maximum rule lines can be entered.'),
43 'rule_lines': fields.one2many('base.action.rule.line','rule_id','Rule Lines', states={'activate': [('readonly', True)]}),
44 'create_date': fields.datetime('Create Date', readonly=1),
45 'state': fields.selection([('draft','Draft'),('activate','Activated'),('deactivate','Deactivated')],'State',readonly=1)
49 'state': lambda *a: 'draft',
52 def button_activate_rule(self, cr, uid, ids, context=None):
53 check = self.browse(cr, uid, ids[0]).rule_lines
55 raise osv.except_osv(_('Error !'), _('Rule Lines are empty ! Cannot activate the Rule.'))
56 cronobj = self.pool.get('ir.cron')
57 cronids = cronobj.search(cr,uid,[('model','=','base.action.rule'),('active','=',False)])
59 cronobj.write(cr, uid, cronids, {'active': True})
60 self.write(cr, uid, ids, {'state': 'activate'})
63 def button_deactivate_rule(self, cr, uid, ids, context=None):
64 checkids = self.pool.get('base.action.rule').search(cr, uid, [])
65 cronobj = self.pool.get('ir.cron')
66 cronids = cronobj.search(cr,uid,[('model','=','base.action.rule'),('active','=',True)])
67 self.write(cr, uid, ids, {'state': 'deactivate'})
68 if cronids and all(rule.state == 'deactivate' for rule in self.browse(cr, uid, checkids)):
69 cronobj.write(cr, uid, cronids, {'active': False})
72 def remind_partner(self, cr, uid, ids, context={}, attach=False):
73 return self.remind_user(cr, uid, ids, context, attach,
76 def remind_user(self, cr, uid, ids, context={}, attach=False, destination=True):
77 ruleline_obj = self.pool.get('base.action.rule.line')
78 for rule in self.browse(cr, uid, ids):
79 for action in rule.rule_lines:
80 if not action.act_remind_user:
81 raise osv.except_osv(_('Warning!'), ("Remind Responsible should be active."))
82 if action.trg_user_id and action.trg_user_id.address_id and not action.trg_user_id.address_id.email:
83 raise osv.except_osv(_('Error!'), ("User Email is not specified."))
84 if action.trg_user_id and action.trg_user_id.address_id and action.trg_user_id.address_id.email:
85 src = action.trg_user_id.address_id.email
86 dest = action.act_reply_to
87 body = action.act_mail_body
90 if action.trg_user_id.signature:
91 body += '\n\n%s' % (action.trg_user_id.signature or '')
97 attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', rule.name.model), ('res_id', '=', rule.name.id)])
98 attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname','datas'])
99 attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
102 flag = tools.email_send(
105 "Reminder: [%s] %s" % (str(rule.name.id), rule.name.model, ),
106 ruleline_obj.format_body(body),
107 reply_to=action.act_reply_to,
108 openobject_id=str(rule.name.id),
109 attach=attach_to_send
112 raise except_orm(_('Email!'),
113 _("Email Successfully Sent by %s") % action.trg_user_id.name)
115 raise except_orm(_('Email!'),
116 _("Email is not sent Successfully for %s") % action.trg_user_id.name)
119 def _check(self, cr, uid, ids=False, context={}):
121 Function called by the scheduler to process models
123 ruleobj = self.pool.get('base.action.rule')
124 ids = ruleobj.search(cr, uid, [('state','=','activate')])
125 rules = ruleobj.browse(cr, uid, ids, context)
126 return ruleobj._action(cr, uid, rules, False, context=context)
128 def _action(self, cr, uid, rules, state_to, scrit=None, context={}):
132 history_obj = self.pool.get('base.action.rule.history')
133 cr.execute("select nextcall from ir_cron where model='base.action.rule'")
134 action_next = cr.fetchone()[0]
136 cr.execute('select id, rule_id, res_id, date_action_last, date_action_next' \
137 ' from base_action_rule_history where rule_id in (%s)' %(','.join(map(lambda x: "'"+str(x.id)+"'",rules))))
138 history = cr.fetchall()
139 checkids = map(lambda x: x[1], history or [])
140 if not len(history) or len(history) < len(rules):
142 if rule.id not in checkids:
143 lastDate = mx.DateTime.strptime(rule.create_date[:19], '%Y-%m-%d %H:%M:%S')
144 history_obj.create(cr, uid, {'rule_id': rule.id, 'res_id': rule.name.id, 'date_action_last': lastDate, 'date_action_next': action_next})
146 obj = self.pool.get(rule.name.model)
147 rec_ids = obj.search(cr, uid, [])
148 for action in rule.rule_lines:
149 for data in obj.browse(cr, uid, rec_ids):
151 ok = ok and (not action.trg_state_from or action.trg_state_from==data.state)
152 ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
153 ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==data.user_id.id)
154 ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==data.partner_id.id)
156 not action.trg_partner_categ_id.id or
158 data.partner_id.id and
159 (action.trg_partner_categ_id.id in map(lambda x: x.id, data.partner_id.category_id or []))
162 ok = ok and (not action.trg_priority_from or action.trg_priority_from>=data.priority)
163 ok = ok and (not action.trg_priority_to or action.trg_priority_to<=data.priority)
165 reg_name = action.regex_name
168 ptrn = re.compile(str(reg_name))
169 _result = ptrn.search(str(data.name))
172 regex_n = not reg_name or result_name
179 if action.trg_date_type=='create':
180 base = mx.DateTime.strptime(data.create_date[:19], '%Y-%m-%d %H:%M:%S')
181 elif action.trg_date_type=='action_last':
186 base = mx.DateTime.strptime(data.create_date[:19], '%Y-%m-%d %H:%M:%S')
187 elif action.trg_date_type=='date' and data.date:
188 base = mx.DateTime.strptime(data.date, '%Y-%m-%d %H:%M:%S')
191 'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval),
192 'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval),
193 'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval),
194 'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval),
196 d = base + fnct[action.trg_date_range_type](action.trg_date_range)
197 dt = d.strftime('%Y-%m-%d %H:%M:%S')
199 ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
204 if not hist[4] or dt < hist[4]:
205 history_obj.write(cr, uid, [hist[0]], {'date_action_next': dt}, context)
208 ok = action.trg_date_type=='none'
211 if action.server_action_id:
212 context.update({'active_id': data.id,'active_ids': [data.id]})
213 self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
216 data.state = action.act_state
217 write['state'] = action.act_state
218 if action.act_user_id:
219 data.user_id = action.act_user_id
220 write['user_id'] = action.act_user_id.id
221 if action.act_priority:
222 data.priority = action.act_priority
223 write['priority'] = action.act_priority
224 if action.act_email_cc:
225 if '@' in (data.email_cc or ''):
226 emails = data.email_cc.split(",")
227 if action.act_email_cc not in emails:# and '<'+str(action.act_email_cc)+">" not in emails:
228 write['email_cc'] = data.email_cc+','+action.act_email_cc
230 write['email_cc'] = action.act_email_cc
231 obj.write(cr, uid, [data.id], write, context)
232 if action.act_remind_user:
233 self.remind_user(cr, uid, [rule.id], context, attach=action.act_remind_attach)
234 if action.act_remind_partner:
235 self.remind_partner(cr, uid, [rule.id], context, attach=action.act_remind_attach)
237 if action.act_mail_to_user:
238 if data.user_id and data.user_id.address_id:
239 emails.append(data.user_id.address_id.email)
240 if action.act_mail_to_partner:
241 emails.append(data.email_from)
242 if action.act_mail_to_watchers:
243 emails += (action.act_email_cc or '').split(',')
244 if action.act_mail_to_email:
245 emails += (action.act_mail_to_email or '').split(',')
246 emails = filter(None, emails)
247 if len(emails) and action.act_mail_body:
248 emails = list(set(emails))
249 obj.email_send(cr, uid, data, emails, action.act_mail_body)
253 history_obj.write(cr, uid, [hist[0]], {'date_action_last': base, 'date_action_next': action_next})
258 class base_action_rule_line(osv.osv):
259 _name = 'base.action.rule.line'
260 _description = 'Action Rule Lines'
262 'name': fields.char('Rule Name',size=64, required=True),
263 'rule_id': fields.many2one('base.action.rule','Rule'),
264 'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the case rule without removing it."),
265 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case rules."),
267 'trg_state_from': fields.selection([('',''),('escalate','Escalate')]+AVAILABLE_STATES, 'State', size=16),
268 'trg_state_to': fields.selection([('',''),('escalate','Escalate')]+AVAILABLE_STATES, 'Button Pressed', size=16),
270 'trg_date_type': fields.selection([
272 ('create','Creation Date'),
273 ('action_last','Last Action Date'),
275 ], 'Trigger Date', size=16),
276 'trg_date_range': fields.integer('Delay after trigger date',help="Delay After Trigger Date, specifies you can put a negative number " \
277 "if you need a delay before the trigger date, like sending a reminder 15 minutes before a meeting."),
278 'trg_date_range_type': fields.selection([('minutes', 'Minutes'),('hour','Hours'),('day','Days'),('month','Months')], 'Delay type'),
281 'trg_user_id': fields.many2one('res.users', 'Responsible'),
283 'trg_partner_id': fields.many2one('res.partner', 'Partner'),
284 'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
286 'trg_priority_from': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Minimum Priority'),
287 'trg_priority_to': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Maximum Priority'),
288 'act_method': fields.char('Call Object Method', size=64),
289 'act_state': fields.selection([('','')]+AVAILABLE_STATES, 'Set state to', size=16),
290 'act_user_id': fields.many2one('res.users', 'Set responsible to'),
291 'act_priority': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Set priority to'),
292 'act_email_cc': fields.char('Add watchers (Cc)', size=250, help="These people will receive a copy of the future communication between partner and users by email"),
294 'act_remind_partner': fields.boolean('Remind Partner', help="Check this if you want the rule to send a reminder by email to the partner."),
295 'act_remind_user': fields.boolean('Remind responsible', help="Check this if you want the rule to send a reminder by email to the user."),
296 'act_reply_to': fields.char('Reply-To', size=64),
297 'act_remind_attach': fields.boolean('Remind with attachment', help="Check this if you want that all documents attached to the case be attached to the reminder email sent."),
299 'act_mail_to_user': fields.boolean('Mail to responsible',help="Check this if you want the rule to send an email to the responsible person."),
300 'act_mail_to_partner': fields.boolean('Mail to partner',help="Check this if you want the rule to send an email to the partner."),
301 'act_mail_to_watchers': fields.boolean('Mail to watchers (CC)',help="Check this if you want the rule to mark CC(mail to any other person defined in actions)."),
302 'act_mail_to_email': fields.char('Mail to these emails', size=128,help="Email-id of the persons whom mail is to be sent"),
303 'act_mail_body': fields.text('Mail body',help="Content of mail"),
304 'regex_name': fields.char('Regular Expression on Model Name', size=128),
305 'server_action_id': fields.many2one('ir.actions.server','Server Action',help="Describes the action name." \
306 "eg:on which object which action to be taken on basis of which condition"),
310 'active': lambda *a: 1,
311 'trg_date_type': lambda *a: 'none',
312 'trg_date_range_type': lambda *a: 'day',
313 'act_mail_to_user': lambda *a: 0,
314 'act_remind_partner': lambda *a: 0,
315 'act_remind_user': lambda *a: 0,
316 'act_mail_to_partner': lambda *a: 0,
317 'act_mail_to_watchers': lambda *a: 0,
322 def format_body(self, body):
323 return body and tools.ustr(body.encode('ascii', 'replace')) or ''
325 def format_mail(self, case, body):
328 'case_subject': case.name,
329 'case_date': case.date,
330 'case_description': case.description,
332 'case_user': (case.user_id and case.user_id.name) or '/',
333 'case_user_email': (case.user_id and case.user_id.address_id and case.user_id.address_id.email) or '/',
334 'case_user_phone': (case.user_id and case.user_id.address_id and case.user_id.address_id.phone) or '/',
336 'email_from': case.email_from,
337 'partner': (case.partner_id and case.partner_id.name) or '/',
338 'partner_email': (case.partner_address_id and case.partner_address_id.email) or '/',
340 return self.format_body(body % data)
342 def _check_mail(self, cr, uid, ids, context=None):
343 emptycase = orm.browse_null()
344 for rule in self.browse(cr, uid, ids):
345 if rule.act_mail_body:
347 self.format_mail(emptycase, rule.act_mail_body)
348 except (ValueError, KeyError, TypeError):
353 (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
356 base_action_rule_line()
358 class base_action_rule_history(osv.osv):
359 _name = 'base.action.rule.history'
360 _description = 'Action Rule History'
362 'rule_id': fields.many2one('base.action.rule','Rule', required=True, readonly=1),
363 'name': fields.related('rule_id', 'name', type='many2one', relation='ir.model', string='Model', readonly=1),
364 'res_id': fields.integer('Resource ID', readonly=1),
365 'date_action_last': fields.datetime('Last Action', readonly=1),
366 'date_action_next': fields.datetime('Next Action', readonly=1),
369 base_action_rule_history()
371 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: