[IMP] base_action_rule,crm: Added button for activating/deactivating rules. Added...
[odoo/odoo.git] / addons / base_action_rule / base_action_rule.py
1 import time
2 import mx.DateTime
3 import re
4
5 import tools
6 from osv import fields, osv, orm
7 from osv.orm import except_orm
8 from tools.translate import _
9
10 AVAILABLE_STATES = [
11     ('draft','Draft'),
12     ('open','Open'),
13     ('cancel', 'Cancelled'),
14     ('done', 'Closed'),
15     ('pending','Pending')
16 ]
17
18 AVAILABLE_PRIORITIES = [
19     ('5','Lowest'),
20     ('4','Low'),
21     ('3','Normal'),
22     ('2','High'),
23     ('1','Highest')
24 ]
25
26 class base_action_rule(osv.osv):
27     _name = 'base.action.rule'
28     _description = 'Action Rules'
29     
30     def _get_max_level(self, cr, uid, ids, field_name, arg, context=None):
31         res = {}
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.'))
37         return res
38     
39     _columns = {
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)
46     }
47     
48     _defaults = {
49         'state': lambda *a: 'draft',
50     }
51     
52     def button_activate_rule(self, cr, uid, ids, context=None):
53         check = self.browse(cr, uid, ids[0]).rule_lines
54         if not check:
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)])
58         if cronids:
59             cronobj.write(cr, uid, cronids, {'active': True})
60         self.write(cr, uid, ids, {'state': 'activate'})
61         return True
62     
63     def button_deactivate_rule(self, cr, uid, ids, context=None):
64         cronobj = self.pool.get('ir.cron')
65         cronids = cronobj.search(cr,uid,[('model','=','base.action.rule'),('active','=',True)])
66         if cronids:
67             cronobj.write(cr, uid, cronids, {'active': False})
68         self.write(cr, uid, ids, {'state': 'deactivate'})
69         return True
70     
71     def remind_partner(self, cr, uid, ids, context={}, attach=False):
72         return self.remind_user(cr, uid, ids, context, attach,
73                 destination=False)
74
75     def remind_user(self, cr, uid, ids, context={}, attach=False, destination=True):
76         ruleline_obj = self.pool.get('base.action.rule.line')
77         for rule in self.browse(cr, uid, ids):
78             for action in rule.rule_lines:
79                 if not action.act_remind_user:
80                     raise osv.except_osv(_('Warning!'), ("Remind Responsible should be active."))
81                 if action.trg_user_id and action.trg_user_id.address_id and not action.trg_user_id.address_id.email:
82                     raise osv.except_osv(_('Error!'), ("User Email is not specified."))
83                 if action.trg_user_id and action.trg_user_id.address_id and action.trg_user_id.address_id.email:
84                     src = action.trg_user_id.address_id.email
85                     dest = action.act_reply_to
86                     body = action.act_mail_body
87                     if not destination:
88                         src, dest = dest, src
89                         if action.trg_user_id.signature:
90                             body += '\n\n%s' % (action.trg_user_id.signature or '')
91                     dest = [dest]
92     
93                     attach_to_send = None
94     
95                     if attach:
96                         attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', rule.name.model), ('res_id', '=', rule.name.id)])
97                         attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname','datas'])
98                         attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
99     
100                     # Send an email
101                     flag = tools.email_send(
102                         src,
103                         dest,
104                         "Reminder: [%s] %s" % (str(rule.name.id), rule.name.model, ),
105                         ruleline_obj.format_body(body),
106                         reply_to=action.act_reply_to,
107                         openobject_id=str(rule.name.id),
108                         attach=attach_to_send
109                     )
110                     if flag:
111                         raise except_orm(_('Email!'),
112                                 _("Email Successfully Sent by %s") % action.trg_user_id.name)
113                     else:
114                         raise except_orm(_('Email!'),
115                                 _("Email is not sent Successfully for %s") % action.trg_user_id.name)
116         return True
117     
118     def _check(self, cr, uid, ids=False, context={}):
119         '''
120         Function called by the scheduler to process models
121         '''
122         ruleobj = self.pool.get('base.action.rule')
123         ids = ruleobj.search(cr, uid, [])
124         rules = ruleobj.browse(cr, uid, ids, context) 
125         return ruleobj._action(cr, uid, rules, False, context=context)
126     
127     def _action(self, cr, uid, rules, state_to, scrit=None, context={}):
128         if not scrit:
129             scrit = []
130         history = []
131         history_obj = self.pool.get('base.action.rule.history')
132         cr.execute("select nextcall from ir_cron where model='base.action.rule'")
133         action_next = cr.fetchone()[0]
134         if rules:
135             cr.execute('select id, rule_id, res_id, date_action_last, date_action_next' \
136                        ' from base_action_rule_history where rule_id in (%s)' %(','.join(map(lambda x: "'"+str(x.id)+"'",rules))))
137             history = cr.fetchall()
138             checkids = map(lambda x: x[1], history or [])
139             if not len(history) or len(history) < len(rules):
140                 for rule in rules:
141                     if rule.id not in checkids:
142                         lastDate = mx.DateTime.strptime(rule.create_date[:19], '%Y-%m-%d %H:%M:%S')
143                         history_obj.create(cr, uid, {'rule_id': rule.id, 'res_id': rule.name.id, 'date_action_last': lastDate, 'date_action_next': action_next})
144         for rule in rules:
145             obj = self.pool.get(rule.name.model)
146             rec_ids = obj.search(cr, uid, [])
147             for action in rule.rule_lines:
148                 for data in obj.browse(cr, uid, rec_ids):
149                     ok = True
150                     ok = ok and (not action.trg_state_from or action.trg_state_from==data.state)
151                     ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
152                     ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==data.user_id.id)
153                     ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==data.partner_id.id)
154                     ok = ok and (
155                         not action.trg_partner_categ_id.id or
156                         (
157                             data.partner_id.id and
158                             (action.trg_partner_categ_id.id in map(lambda x: x.id, data.partner_id.category_id or []))
159                         )
160                     )
161                     ok = ok and (not action.trg_priority_from or action.trg_priority_from>=data.priority)
162                     ok = ok and (not action.trg_priority_to or action.trg_priority_to<=data.priority)
163
164                     reg_name = action.regex_name
165                     result_name = True
166                     if reg_name:
167                         ptrn = re.compile(str(reg_name))
168                         _result = ptrn.search(str(data.name))
169                         if not _result:
170                             result_name = False
171                     regex_n = not reg_name or result_name
172                     ok = ok and regex_n
173                     
174                     if not ok:
175                         continue
176                     
177                     base = False
178                     if action.trg_date_type=='create':
179                         base = mx.DateTime.strptime(data.create_date[:19], '%Y-%m-%d %H:%M:%S')
180                     elif action.trg_date_type=='action_last':
181                         for hist in history:
182                             if hist[3]:
183                                 base = hist[4]
184                             else:
185                                 base = mx.DateTime.strptime(data.create_date[:19], '%Y-%m-%d %H:%M:%S')
186                     elif action.trg_date_type=='date' and data.date:
187                         base = mx.DateTime.strptime(data.date, '%Y-%m-%d %H:%M:%S')
188                     if base:
189                         fnct = {
190                             'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval),
191                             'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval),
192                             'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval),
193                             'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval),
194                         }
195                         d = base + fnct[action.trg_date_range_type](action.trg_date_range)
196                         dt = d.strftime('%Y-%m-%d %H:%M:%S')
197                         for hist in history:
198                             ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
199                                     ((not hist[4]) or \
200                                     (dt >= hist[4] and \
201                                     hist[3] < hist[4]))
202                             if not ok:
203                                 if not hist[4] or dt < hist[4]:
204                                     history_obj.write(cr, uid, [hist[0]], {'date_action_next': dt}, context)
205
206                     else:
207                         ok = action.trg_date_type=='none'
208
209                     if ok:
210                         if action.server_action_id:
211                             context.update({'active_id': data.id,'active_ids': [data.id]})
212                             self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
213                         write = {}
214                         if action.act_state:
215                             data.state = action.act_state
216                             write['state'] = action.act_state
217                         if action.act_user_id:
218                             data.user_id = action.act_user_id
219                             write['user_id'] = action.act_user_id.id
220                         if action.act_priority:
221                             data.priority = action.act_priority
222                             write['priority'] = action.act_priority
223                         if action.act_email_cc:
224                             if '@' in (data.email_cc or ''):
225                                 emails = data.email_cc.split(",")
226                                 if  action.act_email_cc not in emails:# and '<'+str(action.act_email_cc)+">" not in emails:
227                                     write['email_cc'] = data.email_cc+','+action.act_email_cc
228                             else:
229                                 write['email_cc'] = action.act_email_cc
230                         obj.write(cr, uid, [data.id], write, context)
231                         if action.act_remind_user:
232                             self.remind_user(cr, uid, [rule.id], context, attach=action.act_remind_attach)
233                         if action.act_remind_partner:
234                             self.remind_partner(cr, uid, [rule.id], context, attach=action.act_remind_attach)
235                         emails = []
236                         if action.act_mail_to_user:
237                             if data.user_id and data.user_id.address_id:
238                                 emails.append(data.user_id.address_id.email)
239                         if action.act_mail_to_partner:
240                             emails.append(data.email_from)
241                         if action.act_mail_to_watchers:
242                             emails += (action.act_email_cc or '').split(',')
243                         if action.act_mail_to_email:
244                             emails += (action.act_mail_to_email or '').split(',')
245                         emails = filter(None, emails)
246                         if len(emails) and action.act_mail_body:
247                             emails = list(set(emails))
248                             obj.email_send(cr, uid, data, emails, action.act_mail_body)
249                 for hist in history:
250                     if hist[3]:
251                         base = hist[4]
252                     history_obj.write(cr, uid, [hist[0]], {'date_action_last': base, 'date_action_next': action_next})
253         return True
254
255 base_action_rule()
256
257 class base_action_rule_line(osv.osv):
258     _name = 'base.action.rule.line'
259     _description = 'Action Rule Lines'
260     _columns = {
261         'name': fields.char('Rule Name',size=64, required=True),
262         'rule_id': fields.many2one('base.action.rule','Rule'),
263         '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."),
264         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case rules."),
265
266         'trg_state_from': fields.selection([('',''),('escalate','Escalate')]+AVAILABLE_STATES, 'State', size=16),
267         'trg_state_to': fields.selection([('',''),('escalate','Escalate')]+AVAILABLE_STATES, 'Button Pressed', size=16),
268
269         'trg_date_type':  fields.selection([
270             ('none','None'),
271             ('create','Creation Date'),
272             ('action_last','Last Action Date'),
273             ('date','Date'),
274             ], 'Trigger Date', size=16),
275         'trg_date_range': fields.integer('Delay after trigger date',help="Delay After Trigger Date, specifies you can put a negative number " \
276                                                              "if you need a delay before the trigger date, like sending a reminder 15 minutes before a meeting."),
277         'trg_date_range_type': fields.selection([('minutes', 'Minutes'),('hour','Hours'),('day','Days'),('month','Months')], 'Delay type'),
278
279         
280         'trg_user_id':  fields.many2one('res.users', 'Responsible'),
281
282         'trg_partner_id': fields.many2one('res.partner', 'Partner'),
283         'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
284
285         'trg_priority_from': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Minimum Priority'),
286         'trg_priority_to': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Maximum Priority'),
287         'act_method': fields.char('Call Object Method', size=64),
288         'act_state': fields.selection([('','')]+AVAILABLE_STATES, 'Set state to', size=16),
289         'act_user_id': fields.many2one('res.users', 'Set responsible to'),
290         'act_priority': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Set priority to'),
291         '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"),
292
293         'act_remind_partner': fields.boolean('Remind Partner', help="Check this if you want the rule to send a reminder by email to the partner."),
294         'act_remind_user': fields.boolean('Remind responsible', help="Check this if you want the rule to send a reminder by email to the user."),
295         'act_reply_to': fields.char('Reply-To', size=64),
296         '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."),
297
298         '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."),
299         'act_mail_to_partner': fields.boolean('Mail to partner',help="Check this if you want the rule to send an email to the partner."),
300         '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)."),
301         'act_mail_to_email': fields.char('Mail to these emails', size=128,help="Email-id of the persons whom mail is to be sent"),
302         'act_mail_body': fields.text('Mail body',help="Content of mail"),
303         'regex_name': fields.char('Regular Expression on Model Name', size=128),
304         'server_action_id': fields.many2one('ir.actions.server','Server Action',help="Describes the action name." \
305                                                     "eg:on which object which action to be taken on basis of which condition"),
306     }
307     
308     _defaults = {
309         'active': lambda *a: 1,
310         'trg_date_type': lambda *a: 'none',
311         'trg_date_range_type': lambda *a: 'day',
312         'act_mail_to_user': lambda *a: 0,
313         'act_remind_partner': lambda *a: 0,
314         'act_remind_user': lambda *a: 0,
315         'act_mail_to_partner': lambda *a: 0,
316         'act_mail_to_watchers': lambda *a: 0,
317     }
318     
319     _order = 'sequence'
320     
321     def format_body(self, body):
322         return body and tools.ustr(body.encode('ascii', 'replace')) or ''
323
324     def format_mail(self, case, body):
325         data = {
326             'case_id': case.id,
327             'case_subject': case.name,
328             'case_date': case.date,
329             'case_description': case.description,
330
331             'case_user': (case.user_id and case.user_id.name) or '/',
332             'case_user_email': (case.user_id and case.user_id.address_id and case.user_id.address_id.email) or '/',
333             'case_user_phone': (case.user_id and case.user_id.address_id and case.user_id.address_id.phone) or '/',
334
335             'email_from': case.email_from,
336             'partner': (case.partner_id and case.partner_id.name) or '/',
337             'partner_email': (case.partner_address_id and case.partner_address_id.email) or '/',
338         }
339         return self.format_body(body % data)
340     
341     def _check_mail(self, cr, uid, ids, context=None):
342         emptycase = orm.browse_null()
343         for rule in self.browse(cr, uid, ids):
344             if rule.act_mail_body:
345                 try:
346                     self.format_mail(emptycase, rule.act_mail_body)
347                 except (ValueError, KeyError, TypeError):
348                     return False
349         return True
350     
351     _constraints = [
352         (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
353     ]
354     
355 base_action_rule_line()
356
357 class base_action_rule_history(osv.osv):
358     _name = 'base.action.rule.history'
359     _description = 'Action Rule History'
360     _columns = {
361         'rule_id': fields.many2one('base.action.rule','Rule', required=True, readonly=1),
362         'name': fields.related('rule_id', 'name', type='many2one', relation='ir.model', string='Model', readonly=1),
363         'res_id': fields.integer('Resource ID', readonly=1),
364         'date_action_last': fields.datetime('Last Action', readonly=1),
365         'date_action_next': fields.datetime('Next Action', readonly=1),  
366     }
367     
368 base_action_rule_history()
369
370 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: