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