[MERGE+IMP] crm: utf-8 problems in mailagte
[odoo/odoo.git] / addons / crm / crm_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 re
24 import os
25 import base64
26 import tools
27 import mx.DateTime
28
29 from tools.translate import _
30 from osv import fields 
31 from osv import osv 
32 from osv import orm
33 from osv.orm import except_orm
34
35 import crm
36
37 class case(osv.osv):
38     _inherit = 'crm.case'
39     _columns = {
40         'date_action_last': fields.datetime('Last Action', readonly=1),
41         'date_action_next': fields.datetime('Next Action', readonly=1),
42     }
43
44     def remind_partner(self, cr, uid, ids, context={}, attach=False):
45         return self.remind_user(cr, uid, ids, context, attach,
46                 destination=False)
47
48     def remind_user(self, cr, uid, ids, context={}, attach=False, 
49             destination=True):
50         for case in self.browse(cr, uid, ids):
51             if not case.section_id.reply_to:
52                 raise osv.except_osv(_('Error!'), ("Reply To is not specified in Section"))
53             if not case.email_from:
54                 raise osv.except_osv(_('Error!'), ("Partner Email is not specified in Case"))
55             if case.section_id.reply_to and case.email_from:
56                 src = case.email_from
57                 dest = case.section_id.reply_to
58                 body = ""
59                 body = case.email_last or case.description               
60                 if not destination:
61                     src, dest = dest, src
62                     if body and case.user_id.signature:
63                         body += '\n\n%s' % (case.user_id.signature)
64
65                 body = self.format_body(body)
66                 dest = [dest]
67
68                 attach_to_send = None
69
70                 if attach:
71                     attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', 'crm.case'), ('res_id', '=', case.id)])
72                     attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname','datas'])
73                     attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
74
75                 # Send an email
76                 flag = tools.email_send(
77                     src,
78                     dest,
79                     "Reminder: [%s] %s" % (str(case.id), case.name, ),
80                     body,
81                     reply_to=case.section_id.reply_to,
82                     openobject_id=str(case.id),
83                     attach=attach_to_send
84                 )
85                 self._history(cr, uid, [case], _('Send'), history=True, email=dest, details=body, email_from=src)
86                 #if flag:
87                 #    raise osv.except_osv(_('Email!'),("Email Successfully Sent"))
88                 #else:
89                 #    raise osv.except_osv(_('Email Fail!'),("Email is not sent successfully"))
90         return True    
91
92     def _check(self, cr, uid, ids=False, context={}):
93         '''
94         Function called by the scheduler to process cases for date actions
95         Only works on not done and cancelled cases
96         '''
97         cr.execute('select * from crm_case \
98                 where (date_action_last<%s or date_action_last is null) \
99                 and (date_action_next<=%s or date_action_next is null) \
100                 and state not in (\'cancel\',\'done\')',
101                 (time.strftime("%Y-%m-%d %H:%M:%S"),
102                     time.strftime('%Y-%m-%d %H:%M:%S')))
103         ids2 = map(lambda x: x[0], cr.fetchall() or [])        
104         cases = self.browse(cr, uid, ids2, context)
105         return self._action(cr, uid, cases, False, context=context)        
106
107     def _action(self, cr, uid, cases, state_to, scrit=None, context={}):     
108         if not context:
109             context = {}
110         context['state_to'] = state_to        
111         rule_obj = self.pool.get('base.action.rule')
112         model_obj = self.pool.get('ir.model')
113         model_ids = model_obj.search(cr, uid, [('model','=',self._name)])        
114         rule_ids = rule_obj.search(cr, uid, [('name','=',model_ids[0])])
115         return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
116
117     def format_body(self, body):        
118         return self.pool.get('base.action.rule').format_body(body)
119
120     def format_mail(self, obj, body):
121         return self.pool.get('base.action.rule').format_mail(obj, body)
122 case()
123
124 class base_action_rule(osv.osv):
125     _inherit = 'base.action.rule'
126     _description = 'Action Rules'
127
128     def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from',False), context={}):
129         body = self.format_mail(obj, body)
130         if not emailfrom:
131             if hasattr(obj, 'user_id')  and obj.user_id and obj.user_id.address_id and obj.user_id.address_id.email:
132                 emailfrom = obj.user_id.address_id.email
133             
134         name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
135         emailfrom = tools.ustr(emailfrom)
136         if hasattr(obj, 'section_id') and obj.section_id and obj.section_id.reply_to:
137             reply_to = obj.section_id.reply_to
138         else:
139             reply_to = emailfrom
140         if not emailfrom:
141             raise osv.except_osv(_('Error!'),
142                     _("No E-Mail ID Found for your Company address!"))
143         return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
144     
145     def do_check(self, cr, uid, action, obj, context={}):
146         ok = super(base_action_rule, self).do_check(cr, uid, action, obj, context=context)
147         
148         if hasattr(obj, 'section_id'):
149             ok = ok and (not action.trg_section_id or action.trg_section_id.id==obj.section_id.id)
150         if hasattr(obj, 'categ_id'):
151             ok = ok and (not action.trg_categ_id or action.trg_categ_id.id==obj.categ_id.id)
152         if hasattr(obj, 'history_line'):
153             ok = ok and (not action.trg_max_history or action.trg_max_history<=(len(obj.history_line)+1))
154             reg_history = action.regex_history
155             result_history = True
156             if reg_history:
157                 ptrn = re.compile(str(reg_history))
158                 if obj.history_line:
159                     _result = ptrn.search(str(obj.history_line[0].description))
160                     if not _result:
161                         result_history = False
162             regex_h = not reg_history or result_history
163             ok = ok and regex_h
164         return ok
165
166     def do_action(self, cr, uid, action, model_obj, obj, context={}):
167         res = super(base_action_rule, self).do_action(cr, uid, action, model_obj, obj, context=context)         
168         write = {}
169         
170         if hasattr(action, act_section_id) and action.act_section_id:
171             obj.section_id = action.act_section_id
172             write['section_id'] = action.act_section_id.id        
173         
174         if hasattr(obj, 'email_cc') and action.act_email_cc:
175             if '@' in (obj.email_cc or ''):
176                 emails = obj.email_cc.split(",")
177                 if  obj.act_email_cc not in emails:# and '<'+str(action.act_email_cc)+">" not in emails:
178                     write['email_cc'] = obj.email_cc+','+obj.act_email_cc
179             else:
180                 write['email_cc'] = obj.act_email_cc
181         
182         model_obj.write(cr, uid, [obj.id], write, context)
183         emails = []
184         if hasattr(obj, 'email_from') and action.act_mail_to_partner:
185             emails.append(obj.email_from)
186         emails = filter(None, emails)
187         if len(emails) and action.act_mail_body:
188             emails = list(set(emails))
189             self.email_send(cr, uid, obj, emails, action.act_mail_body)
190         return True
191    
192     
193 base_action_rule()
194
195 class base_action_rule_line(osv.osv):
196     _inherit = 'base.action.rule.line'
197
198     def state_get(self, cr, uid, context={}):
199         res = super(base_action_rule_line, self).state_get(cr, uid, context=context)   
200         return res + [('escalate','Escalate')] + crm.AVAILABLE_STATES
201
202     def priority_get(self, cr, uid, context={}):
203         res = super(base_action_rule_line, self).priority_get(cr, uid, context=context) 
204         return res + crm.AVAILABLE_PRIORITIES
205     
206     _columns = {        
207         'trg_section_id': fields.many2one('crm.case.section', 'Section'),
208         'trg_max_history': fields.integer('Maximum Communication History'),
209         'trg_categ_id':  fields.many2one('crm.case.categ', 'Category'),        
210         'regex_history' : fields.char('Regular Expression on Case History', size=128),
211         'act_section_id': fields.many2one('crm.case.section', 'Set section to'),        
212         'act_categ_id': fields.many2one('crm.case.categ', 'Set Category to'),
213         'act_mail_to_partner': fields.boolean('Mail to partner',help="Check this if you want the rule to send an email to the partner."),        
214     }
215
216 base_action_rule_line()