[CLEAN] Set Withespaces to PEP8 format
[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 = case.email_last or case.description
59                 if not destination:
60                     src, dest = dest, src
61                     if case.user_id.signature:
62                         body += '\n\n%s' % (case.user_id.signature or '')
63                 dest = [dest]
64
65                 attach_to_send = None
66
67                 if attach:
68                     attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', 'crm.case'), ('res_id', '=', case.id)])
69                     attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas'])
70                     attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send)
71
72                 # Send an email
73                 flag = tools.email_send(
74                     src,
75                     dest,
76                     "Reminder: [%s] %s" % (str(case.id), case.name,),
77                     self.format_body(body),
78                     reply_to=case.section_id.reply_to,
79                     openobject_id=str(case.id),
80                     attach=attach_to_send
81                 )
82                 if flag:
83                     raise osv.except_osv(_('Email!'), ("Email Successfully Sent"))
84                 else:
85                     raise osv.except_osv(_('Email Fail!'), ("Email is not sent successfully"))
86         return True
87
88     def _check(self, cr, uid, ids=False, context={}):
89         '''
90         Function called by the scheduler to process cases for date actions
91         Only works on not done and cancelled cases
92         '''
93         cr.execute('select * from crm_case \
94                 where (date_action_last<%s or date_action_last is null) \
95                 and (date_action_next<=%s or date_action_next is null) \
96                 and state not in (\'cancel\',\'done\')',
97                 (time.strftime("%Y-%m-%d %H:%M:%S"),
98                     time.strftime('%Y-%m-%d %H:%M:%S')))
99         ids2 = map(lambda x: x[0], cr.fetchall() or [])
100         cases = self.browse(cr, uid, ids2, context)
101         return self._action(cr, uid, cases, False, context=context)
102
103     def _action(self, cr, uid, cases, state_to, scrit=None, context={}):
104         if not context:
105             context = {}
106         context['state_to'] = state_to
107         rule_obj = self.pool.get('base.action.rule')
108         model_obj = self.pool.get('ir.model')
109         model_ids = model_obj.search(cr, uid, [('model', '=', self._name)])
110         rule_ids = rule_obj.search(cr, uid, [('name', '=', model_ids[0])])
111         return rule_obj._action(cr, uid, rule_ids, cases, scrit=scrit, context=context)
112
113     def format_body(self, body):
114         return self.pool.get('base.action.rule').format_body(body)
115
116     def format_mail(self, obj, body):
117         return self.pool.get('base.action.rule').format_mail(obj, body)
118 case()
119
120 class base_action_rule(osv.osv):
121     _inherit = 'base.action.rule'
122     _description = 'Action Rules'
123
124     def do_check(self, cr, uid, action, obj, context={}):
125         ok = super(base_action_rule, self).do_check(cr, uid, action, obj, context=context)
126
127         if hasattr(obj, 'section_id'):
128             ok = ok and (not action.trg_section_id or action.trg_section_id.id == obj.section_id.id)
129         if hasattr(obj, 'categ_id'):
130             ok = ok and (not action.trg_categ_id or action.trg_categ_id.id == obj.categ_id.id)
131         if hasattr(obj, 'history_line'):
132             ok = ok and (not action.trg_max_history or action.trg_max_history <= (len(obj.history_line) + 1))
133             reg_history = action.regex_history
134             result_history = True
135             if reg_history:
136                 ptrn = re.compile(str(reg_history))
137                 if obj.history_line:
138                     _result = ptrn.search(str(obj.history_line[0].description))
139                     if not _result:
140                         result_history = False
141             regex_h = not reg_history or result_history
142             ok = ok and regex_h
143         return ok
144
145     def do_action(self, cr, uid, action, model_obj, obj, context={}):
146         res = super(base_action_rule, self).do_action(cr, uid, action, model_obj, obj, context=context)
147         write = {}
148
149         if action.act_section_id:
150             obj.section_id = action.act_section_id
151             write['section_id'] = action.act_section_id.id
152
153         if hasattr(obj, 'email_cc') and action.act_email_cc:
154             if '@' in (obj.email_cc or ''):
155                 emails = obj.email_cc.split(",")
156                 if  obj.act_email_cc not in emails:# and '<'+str(action.act_email_cc)+">" not in emails:
157                     write['email_cc'] = obj.email_cc + ',' + obj.act_email_cc
158             else:
159                 write['email_cc'] = obj.act_email_cc
160
161         model_obj.write(cr, uid, [obj.id], write, context)
162         emails = []
163         if hasattr(obj, 'email_from') and action.act_mail_to_partner:
164             emails.append(obj.email_from)
165         emails = filter(None, emails)
166         if len(emails) and action.act_mail_body:
167             emails = list(set(emails))
168             self.email_send(cr, uid, obj, emails, action.act_mail_body)
169         return True
170
171
172 base_action_rule()
173
174 class base_action_rule_line(osv.osv):
175     _inherit = 'base.action.rule.line'
176
177     def state_get(self, cr, uid, context={}):
178         res = super(base_action_rule_line, self).state_get(cr, uid, context=context)
179         return res + [('escalate', 'Escalate')] + crm.AVAILABLE_STATES
180
181     def priority_get(self, cr, uid, context={}):
182         res = super(base_action_rule_line, self).priority_get(cr, uid, context=context)
183         return res + crm.AVAILABLE_PRIORITIES
184
185     _columns = {
186         'trg_section_id': fields.many2one('crm.case.section', 'Section'),
187         'trg_max_history': fields.integer('Maximum Communication History'),
188         'trg_categ_id':  fields.many2one('crm.case.categ', 'Category'),
189         'regex_history' : fields.char('Regular Expression on Case History', size=128),
190         'act_section_id': fields.many2one('crm.case.section', 'Set section to'),
191         'act_mail_to_partner': fields.boolean('Mail to partner', help="Check this if you want the rule to send an email to the partner."),
192     }
193
194 base_action_rule_line()