[IMP]: crm + base_action_rule: Added category in Rule action
[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 class base_action_rule(osv.osv):
32     _name = 'base.action.rule'
33     _description = 'Action Rules'  
34     
35     
36     _columns = {
37         'name': fields.many2one('ir.model', 'Model', required=True),
38         'max_level': fields.integer('Max Level', help='Specifies maximum level.'),        
39         'rule_lines': fields.one2many('base.action.rule.line','rule_id','Rule Lines'),
40         'create_date': fields.datetime('Create Date', readonly=1),
41         'active': fields.boolean('Active')
42     }
43     
44     _defaults = {
45         'active': lambda *a: True,
46         'max_level': lambda *a: 15,
47     }
48
49     def format_body(self, body):
50         return body and tools.ustr(body) or ''
51
52     def format_mail(self, obj, body):
53         data = {
54             'object_id': obj.id,
55             'object_subject': hasattr(obj, 'name') and obj.name or False,
56             'object_date': hasattr(obj, 'date') and obj.date or False,
57             'object_description': hasattr(obj, 'description') and obj.description or False,
58             'object_user': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.name) or '/',
59             'object_user_email': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.address_id and obj.user_id.address_id.email) or '/',
60             'object_user_phone': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.address_id and obj.user_id.address_id.phone) or '/',        
61             'partner': hasattr(obj, 'partner_id') and (obj.partner_id and obj.partner_id.name) or '/',
62             'partner_email': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and obj.partner_address_id.email) or '/',
63         }
64         return self.format_body(body % data)
65
66     def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from',False), context={}):
67         body = self.format_mail(obj, body)
68         if not emailfrom:
69             if hasattr(obj, 'user_id')  and obj.user_id and obj.user_id.address_id and obj.user_id.address_id.email:
70                 emailfrom = obj.user_id.address_id.email
71             
72         name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
73         emailfrom = tools.ustr(emailfrom)
74         reply_to = emailfrom        
75         if not emailfrom:
76             raise osv.except_osv(_('Error!'),
77                     _("No E-Mail ID Found for your Company address!"))
78         return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
79
80     
81     def do_check(self, cr, uid, action, obj, context={}):
82         ok = True          
83         if hasattr(obj, 'user_id'):          
84             ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
85         if hasattr(obj, 'partner_id'):
86             ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)                    
87             ok = ok and (
88                 not action.trg_partner_categ_id.id or
89                 (
90                     obj.partner_id.id and
91                     (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
92                 )
93             )
94         state_to = context.get('state_to', False)
95         if hasattr(obj, 'state'):
96             ok = ok and (not action.trg_state_from or action.trg_state_from==obj.state)
97         if state_to:
98             ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
99
100         if hasattr(obj, 'priority'):
101             ok = ok and (not action.trg_priority_from or action.trg_priority_from>=obj.priority)
102             ok = ok and (not action.trg_priority_to or action.trg_priority_to<=obj.priority)
103
104         reg_name = action.regex_name
105         result_name = True
106         if reg_name:
107             ptrn = re.compile(str(reg_name))
108             _result = ptrn.search(str(obj.name))
109             if not _result:
110                 result_name = False
111         regex_n = not reg_name or result_name
112         ok = ok and regex_n
113         return ok
114
115     def do_action(self, cr, uid, action, model_obj, obj, context={}):
116         if action.server_action_id:
117             context.update({'active_id':obj.id,'active_ids':[obj.id]})
118             self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
119         write = {}                        
120         if hasattr(obj, 'user_id') and action.act_user_id:
121             obj.user_id = action.act_user_id
122             write['user_id'] = action.act_user_id.id
123         if hasattr(obj, 'date_action_last'):                        
124             write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
125         if hasattr(obj, 'state') and action.act_state:
126             obj.state = action.act_state
127             write['state'] = action.act_state
128
129         if hasattr(obj, 'categ_id') and action.act_categ_id:
130             obj.categ_id = action.act_categ_id
131             write['categ_id'] = action.act_categ_id.id
132
133         if hasattr(obj, 'priority') and action.act_priority:
134             obj.priority = action.act_priority
135             write['priority'] = action.act_priority
136
137         model_obj.write(cr, uid, [obj.id], write, context)
138         
139         if hasattr(model_obj, 'remind_user') and action.act_remind_user:
140             model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
141         if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
142             model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
143         if action.act_method:
144             getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
145         emails = []
146         if hasattr(obj, 'user_id') and action.act_mail_to_user:
147             if obj.user_id and obj.user_id.address_id:
148                 emails.append(obj.user_id.address_id.email)
149         
150         if action.act_mail_to_watchers:
151             emails += (action.act_email_cc or '').split(',')
152         if action.act_mail_to_email:
153             emails += (action.act_mail_to_email or '').split(',')
154         emails = filter(None, emails)
155         if len(emails) and action.act_mail_body:
156             emails = list(set(emails))
157             self.email_send(cr, uid, obj, emails, action.act_mail_body)
158         return True
159
160     def _action(self, cr, uid, ids, objects, scrit=None, context={}):
161         if not scrit:
162             scrit = []
163         rule_line_obj = self.pool.get('base.action.rule.line')
164         for rule in self.browse(cr, uid, ids):    
165             level = rule.max_level            
166             if not level:
167                 break
168             newactions = []
169             scrit += [('rule_id','=',rule.id)]
170             line_ids = rule_line_obj.search(cr, uid, scrit)
171             actions = rule_line_obj.browse(cr, uid, line_ids, context=context)
172             model_obj = self.pool.get(rule.name.model)
173             for obj in objects:
174                 for action in actions:
175                     ok = self.do_check(cr, uid, action, obj, context=context)
176                     if not ok:
177                         continue
178
179                     base = False
180                     if hasattr(obj, 'create_date') and action.trg_date_type=='create':
181                         base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
182                     elif hasattr(obj, 'create_date') and action.trg_date_type=='action_last':
183                         if hasattr(obj, 'date_action_last') and obj.date_action_last:
184                             base = mx.DateTime.strptime(obj.date_action_last, '%Y-%m-%d %H:%M:%S')
185                         else:
186                             base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
187                     elif hasattr(obj, 'date_deadline') and action.trg_date_type=='deadline' and obj.date_deadline:
188                         base = mx.DateTime.strptime(obj.date_deadline, '%Y-%m-%d %H:%M:%S')
189                     elif hasattr(obj, 'date') and action.trg_date_type=='date' and obj.date:
190                         base = mx.DateTime.strptime(obj.date, '%Y-%m-%d %H:%M:%S')
191                     if base:
192                         fnct = {
193                             'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval),
194                             'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval),
195                             'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval),
196                             'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval),
197                         }
198                         d = base + fnct[action.trg_date_range_type](action.trg_date_range)
199                         dt = d.strftime('%Y-%m-%d %H:%M:%S')
200                         ok = False
201                         if hasattr(obj, 'date_action_last') and hasattr(obj, 'date_action_next'):
202                             ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
203                                     ((not obj.date_action_next) or \
204                                     (dt >= obj.date_action_next and \
205                                     obj.date_action_last < obj.date_action_next))
206                             if not ok:
207                                 if not obj.date_action_next or dt < obj.date_action_next:
208                                     obj.date_action_next = dt
209                                     model_obj.write(cr, uid, [obj.id], {'date_action_next': dt}, context)
210                     else:
211                         ok = action.trg_date_type=='none'
212
213                     if ok:
214                         self.do_action(cr, uid, action, model_obj, obj, context)
215                         break            
216             level -= 1
217         return True
218 base_action_rule()
219
220 class base_action_rule_line(osv.osv):
221     _name = 'base.action.rule.line'
222     _description = 'Action Rule Lines'
223
224     def _state_get(self, cr, uid, context={}):
225         return self.state_get(cr, uid, context=context)
226     def _priority_get(self, cr, uid, context={}):
227         return self.priority_get(cr, uid, context=context)
228
229     def state_get(self, cr, uid, context={}):
230         return [('','')]
231     def priority_get(self, cr, uid, context={}):
232         return [('','')]
233
234     _columns = {
235         'name': fields.char('Rule Name',size=64, required=True),
236         'rule_id': fields.many2one('base.action.rule','Rule'),
237         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the rule without removing it."),
238         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of rules."),
239
240         'trg_date_type':  fields.selection([
241             ('none','None'),
242             ('create','Creation Date'),
243             ('action_last','Last Action Date'),
244             ('date','Date'),
245             ], 'Trigger Date', size=16),
246         'trg_date_range': fields.integer('Delay after trigger date',help="Delay After Trigger Date, specifies you can put a negative number " \
247                                                              "if you need a delay before the trigger date, like sending a reminder 15 minutes before a meeting."),
248         'trg_date_range_type': fields.selection([('minutes', 'Minutes'),('hour','Hours'),('day','Days'),('month','Months')], 'Delay type'),
249
250         
251         'trg_user_id':  fields.many2one('res.users', 'Responsible'),
252
253         'trg_partner_id': fields.many2one('res.partner', 'Partner'),
254         'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
255         'trg_state_from': fields.selection(_state_get, 'State', size=16),
256         'trg_state_to': fields.selection(_state_get, 'Button Pressed', size=16),
257         'trg_priority_from': fields.selection(_priority_get, 'Minimum Priority'),
258         'trg_priority_to': fields.selection(_priority_get, 'Maximum Priority'),       
259         
260         'act_method': fields.char('Call Object Method', size=64),        
261         'act_user_id': fields.many2one('res.users', 'Set responsible to'),  
262         'act_state': fields.selection(_state_get, 'Set state to', size=16),
263         'act_priority': fields.selection(_priority_get, 'Set priority to'),      
264         '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"),
265
266         'act_remind_partner': fields.boolean('Remind Partner', help="Check this if you want the rule to send a reminder by email to the partner."),
267         'act_remind_user': fields.boolean('Remind responsible', help="Check this if you want the rule to send a reminder by email to the user."),
268         'act_reply_to': fields.char('Reply-To', size=64),
269         '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."),
270
271         '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."),        
272         '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)."),
273         'act_mail_to_email': fields.char('Mail to these emails', size=128,help="Email-id of the persons whom mail is to be sent"),
274         'act_mail_body': fields.text('Mail body',help="Content of mail"),
275         'regex_name': fields.char('Regular Expression on Model Name', size=128),
276         'server_action_id': fields.many2one('ir.actions.server','Server Action',help="Describes the action name." \
277                                                     "eg:on which object which action to be taken on basis of which condition"),
278     }
279     
280     _defaults = {
281         'active': lambda *a: 1,
282         'trg_date_type': lambda *a: 'none',
283         'trg_date_range_type': lambda *a: 'day',
284         'act_mail_to_user': lambda *a: 0,
285         'act_remind_partner': lambda *a: 0,
286         'act_remind_user': lambda *a: 0,        
287         'act_mail_to_watchers': lambda *a: 0,
288     }
289     
290     _order = 'sequence'   
291     
292     
293     def _check_mail(self, cr, uid, ids, context=None):
294         empty = orm.browse_null()
295         rule_obj = self.pool.get('base.action.rule')
296         for rule in self.browse(cr, uid, ids):
297             if rule.act_mail_body:
298                 try:
299                     rule_obj.format_mail(empty, rule.act_mail_body)
300                 except (ValueError, KeyError, TypeError):
301                     return False
302         return True
303     
304     _constraints = [
305         (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
306     ]
307     
308 base_action_rule_line()
309 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: