[IMP] base_action_rule, crm: Improved scheduling methods.
[odoo/odoo.git] / addons / base_action_rule / base_action_rule.py
1 import time
2 import mx.DateTime
3
4 import tools
5 from osv import fields, osv, orm
6 from osv.orm import except_orm
7
8 AVAILABLE_STATES = [
9     ('draft','Draft'),
10     ('open','Open'),
11     ('cancel', 'Cancelled'),
12     ('done', 'Closed'),
13     ('pending','Pending')
14 ]
15
16 AVAILABLE_PRIORITIES = [
17     ('5','Lowest'),
18     ('4','Low'),
19     ('3','Normal'),
20     ('2','High'),
21     ('1','Highest')
22 ]
23
24 class base_action_rule(osv.osv):
25     _name = 'base.action.rule'
26     _description = 'Action Rules'
27     _columns = {
28         'name': fields.many2one('ir.model', 'Model', required=True),
29         'max_level': fields.integer('Max Level'),
30         'rule_lines': fields.one2many('base.action.rule.line','rule_id','Rule Lines'),
31         'create_date': fields.datetime('Create Date', readonly=1)
32     }
33     
34     def _check(self, cr, uid, ids=False, context={}):
35         '''
36         Function called by the scheduler to process models
37         '''
38         ruleobj = self.pool.get('base.action.rule')
39         ids = ruleobj.search(cr, uid, [])
40         rules = ruleobj.browse(cr, uid, ids, context) 
41         return ruleobj._action(cr, uid, rules, False, context=context)
42     
43     def _action(self, cr, uid, rules, state_to, scrit=None, context={}):
44         if not scrit:
45             scrit = []
46         history = []
47         history_obj = self.pool.get('base.action.rule.history')
48         cr.execute("select nextcall from ir_cron where model='base.action.rule'")
49         action_next = cr.fetchone()[0]
50         if rules:
51             cr.execute('select id, rule_id, res_id, date_action_last, date_action_next' \
52                        ' from base_action_rule_history where rule_id in (%s)' %(','.join(map(lambda x: "'"+str(x.id)+"'",rules))))
53             history = cr.fetchall()
54             checkids = map(lambda x: x[1], history or [])
55             if not len(history) or len(history) < len(rules):
56                 for rule in rules:
57                     if rule.id not in checkids:
58                         lastDate = mx.DateTime.strptime(rule.create_date[:19], '%Y-%m-%d %H:%M:%S')
59                         history_obj.create(cr, uid, {'rule_id': rule.id, 'res_id': rule.name.id, 'date_action_last': lastDate, 'date_action_next': action_next})
60         
61         for rule in rules:
62             obj = self.pool.get(rule.name.model)
63             rec_ids = obj.search(cr, uid, [])
64             for action in rule.rule_lines:
65                 for data in obj.browse(cr, uid, rec_ids):
66                     ok = True
67                     ok = ok and (not action.trg_state_from or action.trg_state_from==data.state)
68                     ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
69                     ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==data.user_id.id)
70                     ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==data.partner_id.id)
71                     ok = ok and (
72                         not action.trg_partner_categ_id.id or
73                         (
74                             data.partner_id.id and
75                             (action.trg_partner_categ_id.id in map(lambda x: x.id, data.partner_id.category_id or []))
76                         )
77                     )
78                     ok = ok and (not action.trg_priority_from or action.trg_priority_from>=data.priority)
79                     ok = ok and (not action.trg_priority_to or action.trg_priority_to<=data.priority)
80
81                     reg_name = action.regex_name
82                     result_name = True
83                     if reg_name:
84                         ptrn = re.compile(str(reg_name))
85                         _result = ptrn.search(str(data.name))
86                         if not _result:
87                             result_name = False
88                     regex_n = not reg_name or result_name
89                     ok = ok and regex_n
90                     
91                     if not ok:
92                         continue
93                     
94                     base = False
95                     if action.trg_date_type=='create':
96                         base = mx.DateTime.strptime(data.create_date[:19], '%Y-%m-%d %H:%M:%S')
97                     elif action.trg_date_type=='action_last':
98                         for hist in history:
99                             if hist[3]:
100                                 base = hist[4]
101                             else:
102                                 base = mx.DateTime.strptime(data.create_date[:19], '%Y-%m-%d %H:%M:%S')
103                     elif action.trg_date_type=='date' and data.date:
104                         base = mx.DateTime.strptime(data.date, '%Y-%m-%d %H:%M:%S')
105                     if base:
106                         fnct = {
107                             'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval),
108                             'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval),
109                             'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval),
110                             'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval),
111                         }
112                         d = base + fnct[action.trg_date_range_type](action.trg_date_range)
113                         dt = d.strftime('%Y-%m-%d %H:%M:%S')
114                         for hist in history:
115                             ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
116                                     ((not hist[4]) or \
117                                     (dt >= hist[4] and \
118                                     hist[3] < hist[4]))
119                             if not ok:
120                                 if not hist[4] or dt < hist[4]:
121                                     history_obj.write(cr, uid, [hist[0]], {'date_action_next': dt}, context)
122
123                     else:
124                         ok = action.trg_date_type=='none'
125
126                     if ok:
127                         if action.server_action_id:
128                             context.update({'active_id':case.id,'active_ids':[case.id]})
129                             self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
130                 for hist in history:
131                     if hist[3]:
132                         base = hist[4]
133                     history_obj.write(cr, uid, [hist[0]], {'date_action_last': base, 'date_action_next': action_next})
134         return True
135
136 base_action_rule()
137
138 class base_action_rule_line(osv.osv):
139     _name = 'base.action.rule.line'
140     _description = 'Action Rule Lines'
141     _columns = {
142         'name': fields.char('Rule Name',size=64, required=True),
143         'rule_id': fields.many2one('base.action.rule','Rule'),
144         '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."),
145         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of case rules."),
146
147         'trg_state_from': fields.selection([('',''),('escalate','Escalate')]+AVAILABLE_STATES, 'State', size=16),
148         'trg_state_to': fields.selection([('',''),('escalate','Escalate')]+AVAILABLE_STATES, 'Button Pressed', size=16),
149
150         'trg_date_type':  fields.selection([
151             ('none','None'),
152             ('create','Creation Date'),
153             ('action_last','Last Action Date'),
154             ('date','Date'),
155             ], 'Trigger Date', size=16),
156         'trg_date_range': fields.integer('Delay after trigger date',help="Delay After Trigger Date, specifies you can put a negative number " \
157                                                              "if you need a delay before the trigger date, like sending a reminder 15 minutes before a meeting."),
158         'trg_date_range_type': fields.selection([('minutes', 'Minutes'),('hour','Hours'),('day','Days'),('month','Months')], 'Delay type'),
159
160         
161         'trg_user_id':  fields.many2one('res.users', 'Responsible'),
162
163         'trg_partner_id': fields.many2one('res.partner', 'Partner'),
164         'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
165
166         'trg_priority_from': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Minimum Priority'),
167         'trg_priority_to': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Maximim Priority'),
168         
169
170         'act_method': fields.char('Call Object Method', size=64),
171         'act_state': fields.selection([('','')]+AVAILABLE_STATES, 'Set state to', size=16),
172         'act_user_id': fields.many2one('res.users', 'Set responsible to'),
173         'act_priority': fields.selection([('','')] + AVAILABLE_PRIORITIES, 'Set priority to'),
174         '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"),
175
176         'act_remind_partner': fields.boolean('Remind Partner', help="Check this if you want the rule to send a reminder by email to the partner."),
177         'act_remind_user': fields.boolean('Remind responsible', help="Check this if you want the rule to send a reminder by email to the user."),
178         '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."),
179
180         '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."),
181         'act_mail_to_partner': fields.boolean('Mail to partner',help="Check this if you want the rule to send an email to the partner."),
182         '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)."),
183         'act_mail_to_email': fields.char('Mail to these emails', size=128,help="Email-id of the persons whom mail is to be sent"),
184         'act_mail_body': fields.text('Mail body',help="Content of mail"),
185         'regex_name': fields.char('Regular Expression on Model Name', size=128),
186         'server_action_id': fields.many2one('ir.actions.server','Server Action',help="Describes the action name." \
187                                                     "eg:on which object which action to be taken on basis of which condition"),
188     }
189     
190     _defaults = {
191         'active': lambda *a: 1,
192         'trg_date_type': lambda *a: 'none',
193         'trg_date_range_type': lambda *a: 'day',
194         'act_mail_to_user': lambda *a: 0,
195         'act_remind_partner': lambda *a: 0,
196         'act_remind_user': lambda *a: 0,
197         'act_mail_to_partner': lambda *a: 0,
198         'act_mail_to_watchers': lambda *a: 0,
199     }
200     
201     _order = 'sequence'
202     
203     def format_body(self, body):
204         return body and tools.ustr(body.encode('ascii', 'replace')) or ''
205
206     def format_mail(self, case, body):
207         data = {
208             'case_id': case.id,
209             'case_subject': case.name,
210             'case_date': case.date,
211             'case_description': case.description,
212
213             'case_user': (case.user_id and case.user_id.name) or '/',
214             'case_user_email': (case.user_id and case.user_id.address_id and case.user_id.address_id.email) or '/',
215             'case_user_phone': (case.user_id and case.user_id.address_id and case.user_id.address_id.phone) or '/',
216
217             'email_from': case.email_from,
218             'partner': (case.partner_id and case.partner_id.name) or '/',
219             'partner_email': (case.partner_address_id and case.partner_address_id.email) or '/',
220         }
221         return self.format_body(body % data)
222     
223     def _check_mail(self, cr, uid, ids, context=None):
224         emptycase = orm.browse_null()
225         for rule in self.browse(cr, uid, ids):
226             if rule.act_mail_body:
227                 try:
228                     self.format_mail(emptycase, rule.act_mail_body)
229                 except (ValueError, KeyError, TypeError):
230                     return False
231         return True
232     
233     _constraints = [
234         (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
235     ]
236     
237 base_action_rule_line()
238
239 class base_action_rule_history(osv.osv):
240     _name = 'base.action.rule.history'
241     _description = 'Action Rule History'
242     _rec_name = 'rule_id'
243     _columns = {
244         'rule_id': fields.many2one('base.action.rule','Rule', required=True, readonly=1),
245         'res_id': fields.integer('Resource ID', readonly=1),
246         'date_action_last': fields.datetime('Last Action', readonly=1),
247         'date_action_next': fields.datetime('Next Action', readonly=1),  
248     }
249     
250 base_action_rule_history()
251
252 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: