[IMP] sale order line invisible type
[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         'history': fields.selection([('info', 'Case Information'), ('latest', 'Latest email'), ('whole', 'Whole Story')], 'Send history', required=True),
41     }
42
43     _defaults = {
44         'send_to' : 'email',
45         'history': 'latest',
46         'email_from': lambda s, cr, uid, c: s.pool.get('res.users').browse(cr, uid, uid, c).email,
47     }
48
49     def on_change_email(self, cr, uid, ids, user, context=None):
50         if not user:
51             return {'value': {'email_to': False}}
52         return {'value': {'email_to': self.pool.get('res.users').browse(cr, uid, uid, context=context).email}}
53
54     def on_change_history(self, cr, uid, ids, history_type, context=None):
55         """Gives message body according to type of history selected
56             * info: Forward the case information
57             * whole: Send the whole history
58             * latest: Send the latest histoy
59         """
60         #TODO: ids and context are not comming
61         res = {}
62         res_id = context.get('active_id')
63         model = context.get('active_model')
64         lead = self.pool.get(model).browse(cr, uid, res_id, context)
65         body_text = self._get_message_body_text(cr, uid, lead, history_type, context=context)
66         if body_text:
67             res = {'value': {'body_text' : body_text}}
68         return res
69     
70     def on_change_partner(self, cr, uid, ids, partner_id):
71         """This function fills address information based on partner/user selected
72         """
73         if not partner_id:
74             return {'value' : {'email_to' : False}}
75         partner_obj = self.pool.get('res.partner')
76         data = {}
77         partner = partner_obj.browse(cr, uid, [partner_id])
78         user_id = partner and partner[0].user_id or False
79         data.update({'email_from': partner and partner[0].email or "", 
80                      'email_cc' : user_id and user_id.user or '', 
81                      'user_id': user_id and user_id.id or False})
82         return {'value' : data}
83
84     def action_forward(self, cr, uid, ids, context=None):
85         """
86         Forward the lead to a partner
87         """
88         if context is None:
89             context = {}
90         res = {'type': 'ir.actions.act_window_close'}
91         model = context.get('active_model')
92         if model not in ('crm.lead'):
93             return res
94
95         this = self.browse(cr, uid, ids[0], context=context)
96         lead = self.pool.get(model)
97         lead_id = context and context.get('active_id', False) or False
98         lead_ids = lead_id and [lead_id] or []
99         mode = context.get('mail.compose.message.mode')
100         if mode == 'mass_mail':
101             lead_ids = context and context.get('active_ids', []) or []
102             value = self.default_get(cr, uid, ['body_text', 'email_to', 'email_cc', 'subject', 'history'], context=context)
103             self.write(cr, uid, ids, value, context=context)
104             context['mail.compose.message.mode'] = mode
105
106         self.send_mail(cr, uid, ids, context=context)
107         for case in lead.browse(cr, uid, lead_ids, context=context):
108             if (this.send_to == 'partner' and this.partner_id):
109                 lead.assign_partner(cr, uid, [case.id], this.partner_id.id, context=context)
110
111             if this.send_to == 'user':
112                 lead.allocate_salesman(cr, uid, [case.id], [this.user_id.id], context=context)
113
114             email_cc = to_email(case.email_cc)
115             email_cc = email_cc and email_cc[0] or ''
116             new_cc = []
117             if email_cc:
118                 new_cc.append(email_cc)
119             for to in this.email_to.split(','):
120                 email_to = to_email(to)
121                 email_to = email_to and email_to[0] or ''
122                 if email_to not in new_cc:
123                     new_cc.append(to)
124             update_vals = {'email_cc' : ', '.join(new_cc) }
125             lead.write(cr, uid, [case.id], update_vals, context=context)
126         return res
127
128     def _get_info_body_text(self, cr, uid, lead, context=None):
129         field_names = []
130         proxy = self.pool.get(lead._name)
131         if lead.type == 'opportunity':
132             field_names += ['partner_id']
133         field_names += [
134            'partner_name' , 'title', 'function', 'street', 'street2',
135             'zip', 'city', 'country_id', 'state_id', 'email_from',
136             'phone', 'fax', 'mobile', 'categ_id', 'description',
137         ]
138         return proxy._mail_body_text(cr, uid, lead, field_names, context=context)
139
140     def _get_message_body_text(self, cr, uid, lead, mode='whole', context=None):
141         """This function gets whole communication history and returns as top posting style
142         """
143         mail_message = self.pool.get('mail.message')
144         message_ids = []
145         body = self._get_info_body_text(cr, uid, lead, context=context)
146         if mode in ('whole', 'latest'):
147             message_ids = lead.message_ids
148             message_ids = map(lambda x: x.id, filter(lambda x: x.email_from, message_ids))
149             if mode == 'latest' and len(message_ids):
150                 message_ids = [message_ids[0]]
151             for message in mail_message.browse(cr, uid, message_ids, context=context):
152                 header = '-------- Original Message --------'
153                 sender = 'From: %s' %(message.email_from or '')
154                 to = 'To: %s' % (message.email_to or '')
155                 sentdate = 'Date: %s' % (message.date or '')
156                 desc = '\n%s'%(message.body_text)
157                 original = [header, sender, to, sentdate, desc, '\n']
158                 original = '\n'.join(original)
159                 body += original
160         return body or ''
161
162     def get_value(self, cr, uid, model, res_id, context=None):
163         if context is None:
164             context = {}
165         res = super(crm_lead_forward_to_partner, self).get_value(cr, uid,  model, res_id, context=context)
166         if model not in ("crm.lead"):
167             return res
168         proxy = self.pool.get(model)
169         partner = self.pool.get('res.partner')
170         lead = proxy.browse(cr, uid, res_id, context=context)
171         mode = context.get('mail.compose.message.mode')
172         if mode == "forward":
173             body_type = context.get('mail.compose.message.body')
174             email_cc = res.get('email_cc', "")
175             email = res.get('email_to', "")
176             subject = '%s: %s - %s' % (_('Fwd'), 'Lead forward', lead.name)
177             body = self._get_message_body_text(cr, uid, lead, body_type, context=context)
178             partner_assigned_id = lead.partner_assigned_id and lead.partner_assigned_id.id or False
179             user_id = False
180             if not partner_assigned_id:
181                 partner_assigned_id = proxy.search_geo_partner(cr, uid, [lead.id], context=None).get(lead.id, False)
182             if partner_assigned_id:
183                 assigned_partner = partner.browse(cr, uid, partner_assigned_id, context=context)
184                 user_id = assigned_partner.user_id and assigned_partner.user_id.id or False
185                 email_cc = assigned_partner.user_id and assigned_partner.user_id.email or ''
186                 email = assigned_partner.email
187             
188             res.update({
189                 'subject' : subject,
190                 'body_text' : body,
191                 'email_cc' : email_cc,
192                 'email_to' : email,
193                 'partner_assigned_id': partner_assigned_id,
194                 'user_id': user_id,
195             })
196         return res
197         
198
199     def default_get(self, cr, uid, fields, context=None):
200         if context is None:
201             context = {}
202         context['mail.compose.message.mode'] = 'forward'
203         context['mail.compose.message.body'] = 'info'
204         return super(crm_lead_forward_to_partner, self).default_get(cr, uid, fields, context=context)
205 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: