[IMP] crm_parner_assign, crm: Corrected history[whole, laetst, case info] for lead...
[odoo/odoo.git] / addons / crm_partner_assign / wizard / crm_forward_to_partner.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 import time
24 import re
25 from osv import osv, fields
26 from tools.translate import _
27 from mail.mail_message import to_email
28
29 class crm_lead_forward_to_partner(osv.osv_memory):
30     """Forwards lead history"""
31     _name = 'crm.lead.forward.to.partner'
32     _inherit = "mail.compose.message"
33
34     _columns = {
35         'send_to': fields.selection([('user', 'User'), ('partner', 'Partner'), \
36                          ('email', 'Email Address')], 'Send to', required=True),
37         'user_id': fields.many2one('res.users', "User"),
38         'attachment_ids': fields.many2many('ir.attachment','lead_forward_to_partner_attachment_rel', 'wizard_id', 'attachment_id', 'Attachments'),
39         'partner_id' : fields.many2one('res.partner', 'Partner'),
40         'address_id' : fields.many2one('res.partner.address', 'Address'),
41         'history': fields.selection([('info', 'Case Information'), ('latest', 'Latest email'), ('whole', 'Whole Story')], 'Send history', required=True),
42     }
43
44     _defaults = {
45         'send_to' : 'email',
46         'history': 'latest',
47         'email_from': lambda self, cr, uid, *a: self.pool.get('res.users')._get_email_from(cr, uid, uid)[uid],
48     }
49
50
51     
52     def on_change_email(self, cr, uid, ids, user):
53         if not user:
54             return {'value': {'email_to': False}}
55         email = self.pool.get('res.users')._get_email_from(cr, uid, [user])[user]
56         return {'value': {'email_to': email}}
57
58     def on_change_history(self, cr, uid, ids, history_type, context=None):
59         """Gives message body according to type of history selected
60             * info: Forward the case information
61             * whole: Send the whole history
62             * latest: Send the latest histoy
63         """
64         #TODO: ids and context are not comming
65         res = {}
66         res_id = context.get('active_id')
67         model = context.get('active_model')
68         lead = self.pool.get(model).browse(cr, uid, res_id, context)
69         body_text = self._get_message_body_text(cr, uid, lead, history_type, context=context)
70         if body_text:
71             res = {'value': {'body_text' : body_text}}
72         return res
73     
74     def on_change_partner(self, cr, uid, ids, partner_id):
75         """This function fills address information based on partner/user selected
76         """
77         if not partner_id:
78             return {'value' : {'email_to' : False, 'address_id': False}}
79
80         partner_obj = self.pool.get('res.partner')
81         addr = partner_obj.address_get(cr, uid, [partner_id], ['contact'])
82         data = {'address_id': addr['contact']}
83         data.update(self.on_change_address(cr, uid, ids, addr['contact'])['value'])
84
85         partner = partner_obj.browse(cr, uid, [partner_id])
86         user_id = partner and partner[0].user_id or False
87         email = user_id and user_id.user_email or ''
88         data.update({'email_cc' : email, 'user_id': user_id and user_id.id or False})
89         return {
90             'value' : data,
91             'domain' : {'address_id' : partner_id and "[('partner_id', '=', partner_id)]" or "[]"}
92         }
93
94     def on_change_address(self, cr, uid, ids, address_id):
95         email = ''
96         if address_id:
97             email = self.pool.get('res.partner.address').browse(cr, uid, address_id).email
98         return {'value': {'email_to' : email}}
99
100     def action_forward(self, cr, uid, ids, context=None):
101         """
102         Forward the lead to a partner
103         """
104         if context is None:
105             context = {}
106         res = {'type': 'ir.actions.act_window_close'}
107         model = context.get('active_model')
108         if model not in ('crm.lead'):
109             return res
110
111         this = self.browse(cr, uid, ids[0], context=context)
112         lead = self.pool.get(model)
113         lead_id = context and context.get('active_id', False) or False
114         lead_ids = lead_id and [lead_id] or []
115         mode = context.get('mail.compose.message.mode')
116         if mode == 'mass_mail':
117             lead_ids = context and context.get('active_ids', []) or []
118             value = self.default_get(cr, uid, ['body_text', 'email_to', 'email_cc', 'subject', 'history'], context=context)
119             self.write(cr, uid, ids, value, context=context)
120             context['mail.compose.message.mode'] = mode
121
122         self.send_mail(cr, uid, ids, context=context)
123         for case in lead.browse(cr, uid, lead_ids, context=context):
124             if (this.send_to == 'partner' and this.partner_id):
125                 lead.assign_partner(cr, uid, [case.id], this.partner_id.id, context=context)
126
127             if this.send_to == 'user':
128                 lead.allocate_salesman(cr, uid, [case.id], [this.user_id.id], context=context)
129
130             email_cc = to_email(case.email_cc)
131             email_cc = email_cc and email_cc[0] or ''
132             new_cc = []
133             if email_cc:
134                 new_cc.append(email_cc)
135             for to in this.email_to.split(','):
136                 email_to = to_email(to)
137                 email_to = email_to and email_to[0] or ''
138                 if email_to not in new_cc:
139                     new_cc.append(to)
140             update_vals = {'email_cc' : ', '.join(new_cc) }
141             lead.write(cr, uid, case.id, update_vals, context=context)
142         return res
143
144     def _get_info_body_text(self, cr, uid, lead, context=None):
145         field_names = []
146         proxy = self.pool.get(lead._name)
147         if lead.type == 'opportunity':
148             field_names += ['partner_id']
149         field_names += [
150            'partner_name' , 'title', 'function', 'street', 'street2',
151             'zip', 'city', 'country_id', 'state_id', 'email_from',
152             'phone', 'fax', 'mobile', 'categ_id', 'description',
153         ]
154         return proxy._mail_body_text(cr, uid, lead, field_names, context=context)
155
156     def _get_message_body_text(self, cr, uid, lead, mode='whole', context=None):
157         """This function gets whole communication history and returns as top posting style
158         """
159         mail_message = self.pool.get('mail.message')
160         message_ids = []
161         body = self._get_info_body_text(cr, uid, lead, context=context)
162         if mode in ('whole', 'latest'):
163             message_ids = lead.message_ids
164             message_ids = map(lambda x: x.id, filter(lambda x: x.email_from, message_ids))
165             if mode == 'latest' and len(message_ids):
166                 message_ids = [message_ids[0]]
167             for message in mail_message.browse(cr, uid, message_ids, context=context):
168                 header = '-------- Original Message --------'
169                 sender = 'From: %s' %(message.email_from or '')
170                 to = 'To: %s' % (message.email_to or '')
171                 sentdate = 'Date: %s' % (message.date or '')
172                 desc = '\n%s'%(message.body_text)
173                 original = [header, sender, to, sentdate, desc, '\n']
174                 original = '\n'.join(original)
175                 body += original
176         return body or ''
177
178     def get_value(self, cr, uid, model, res_id, context=None):
179         if context is None:
180             context = {}
181         res = super(crm_lead_forward_to_partner, self).get_value(cr, uid,  model, res_id, context=context)
182         if model not in ("crm.lead"):
183             return res
184         proxy = self.pool.get(model)
185         partner = self.pool.get('res.partner')
186         lead = proxy.browse(cr, uid, res_id, context=context)
187         mode = context.get('mail.compose.message.mode')
188         if mode == "forward":
189             body_type = context.get('mail.compose.message.body')
190             email_cc = res.get('email_cc', "")
191             email = res.get('email_to', "")
192             subject = '%s: %s - %s' % (_('Fwd'), 'Lead forward', lead.name)
193             body = self._get_message_body_text(cr, uid, lead, body_type, context=context)
194             partner_assigned_id = lead.partner_assigned_id and lead.partner_assigned_id.id or False
195             user_id = False
196             if not partner_assigned_id:
197                 partner_assigned_id = proxy.search_geo_partner(cr, uid, [lead.id], context=None).get(lead.id, False)
198             if partner_assigned_id:
199                 assigned_partner = partner.browse(cr, uid, partner_assigned_id, context=context)
200                 user_id = assigned_partner.user_id and assigned_partner.user_id.id or False
201                 email_cc = assigned_partner.user_id and assigned_partner.user_id.user_email or ''
202                 email = assigned_partner.email
203             
204             res.update({
205                 'subject' : subject,
206                 'body_text' : body,
207                 'email_cc' : email_cc,
208                 'email_to' : email,
209                 'partner_assigned_id': partner_assigned_id,
210                 'user_id': user_id,
211             })
212         return res
213         
214
215     def default_get(self, cr, uid, fields, context=None):
216         if context is None:
217             context = {}
218         context['mail.compose.message.mode'] = 'forward'
219         context['mail.compose.message.body'] = 'info'
220         return super(crm_lead_forward_to_partner, self).default_get(cr, uid, fields, context=context)
221 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: