[FIX] do not send email if email_to is false, do not link with contact if no partner
[odoo/odoo.git] / addons / crm / wizard / crm_lead_to_opportunity.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 from osv import osv, fields
23 from tools.translate import _
24 import tools
25
26 import time
27
28 class crm_lead2opportunity_partner(osv.osv_memory):
29     _name = 'crm.lead2opportunity.partner'
30     _description = 'Lead To Opportunity Partner'
31     _inherit = 'crm.lead2partner'
32
33     _columns = {
34         'action': fields.selection([('exist', 'Link to an existing partner'), \
35                                     ('create', 'Create a new partner'), \
36                                     ('nothing', 'Do not link to a partner')], \
37                                     'Action', required=True),
38         'name': fields.selection([('convert', 'Convert to Opportunity'), ('merge', 'Merge with existing Opportunity')],'Select Action', required=True),
39         'opportunity_ids': fields.many2many('crm.lead',  'merge_opportunity_rel', 'merge_id', 'opportunity_id', 'Opportunities', domain=[('type', '=', 'opportunity')]),
40     }
41
42     def default_get(self, cr, uid, fields, context=None):
43         """
44             Default get for name, opportunity_ids
45             if there is an exisitng  partner link to the lead, find all existing opportunity link with this partnet to merge
46             all information together
47         """
48         lead_obj = self.pool.get('crm.lead')
49
50
51         res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
52         opportunities = res.get('opportunity_ids') or []
53
54         partner_id = False
55         for lead in lead_obj.browse(cr, uid, opportunities, context=context):
56             partner_id = lead.partner_id and lead.partner_id.id or False
57
58         if not partner_id and res.get('partner_id'):
59             partner_id = res.get('partner_id')
60
61         ids = []
62         if partner_id:
63             ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id), ('type', '=', 'opportunity'), '!', ('state', 'in', ['done', 'cancel'])])
64             if ids:
65                 opportunities.append(ids[0])
66
67         if 'action' in fields:
68             res.update({'action' : partner_id and 'exist' or 'create'})
69         if 'partner_id' in fields:
70             res.update({'partner_id' : partner_id})
71         if 'name' in fields:
72             res.update({'name' : ids and 'merge' or 'convert'})
73         if 'opportunity_ids' in fields:
74             res.update({'opportunity_ids': opportunities})
75
76
77         return res
78
79     def view_init(self, cr, uid, fields, context=None):
80         """
81         This function checks for precondition before wizard executes
82         @param self: The object pointer
83         @param cr: the current row, from the database cursor,
84         @param uid: the current user’s ID for security checks,
85         @param fields: List of fields for default value
86         @param context: A standard dictionary for contextual values
87
88         """
89         if context is None:
90             context = {}
91         lead_obj = self.pool.get('crm.lead')
92
93         for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
94             if lead.state in ['done', 'cancel']:
95                 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled \
96 Leads Could not convert into Opportunity"))
97         return False
98
99     def _convert(self, cr, uid, ids, lead, partner_id, stage_ids, context=None):
100         leads = self.pool.get('crm.lead')
101         address_id = False
102         if partner_id:
103             address_id = self.pool.get('res.partner.address').search(cr, uid,
104                                                                  [('partner_id', '=', partner_id)],
105                                                                  order='create_date desc',
106                                                                  limit=1)
107         vals = {
108             'planned_revenue': lead.planned_revenue,
109             'probability': lead.probability,
110             'name': lead.name,
111             'partner_id': partner_id,
112             'user_id': (lead.user_id and lead.user_id.id),
113             'type': 'opportunity',
114             'stage_id': stage_ids and stage_ids[0] or False,
115             'date_action': time.strftime('%Y-%m-%d %H:%M:%S'),
116         }
117         if partner_id and address_id:
118             vals['partner_address_id'] = address_id[0]
119         else:
120             vals['partner_address_id'] = False
121
122         lead.write(vals, context=context)
123         leads.history(cr, uid, [lead], _('Converted to opportunity'), details='Converted to Opportunity', context=context)
124         if lead.partner_id:
125             msg_ids = [ x.id for x in lead.message_ids]
126             self.pool.get('mailgate.message').write(cr, uid, msg_ids, {
127                         'partner_id': lead.partner_id.id
128                     }, context=context)
129             leads.log(cr, uid, lead.id, _("Lead '%s' has been converted to an opportunity.") % lead.name)
130
131     def send_mail_to_salesman(self, lead):
132         email_to = lead.user_id and lead.user_id.user_email
133         if not email_to:
134             return
135         email_from = lead.section_id and lead.section_id.user_id and lead.section_id.user_id.user_email or email_to
136         partner = lead.partner_id and lead.partner_id.name or lead.partner_name 
137         subject = "lead %s converted into opportunity" % lead.name
138         body = "Info \n Id : %s \n Subject: %s \n Partner: %s \n Description : %s " % (lead.id, lead.name, lead.partner_id.name, lead.description)  
139         try :
140             tools.email_send(email_from, email_to, subject, body)
141         except:
142             pass
143
144     def action_apply(self, cr, uid, ids, context=None):
145         """
146         This converts lead to opportunity and opens Opportunity view
147         @param ids: ids of the leads to convert to opportunities
148
149         @return : View dictionary opening the Opportunity form view
150         """
151         if not context:
152             context = {}
153
154         record_id = context and context.get('active_ids') or False
155         if not record_id:
156             return {'type': 'ir.actions.act_window_close'}
157
158         leads = self.pool.get('crm.lead')
159         models_data = self.pool.get('ir.model.data')
160
161         # Get Opportunity views
162         result = models_data._get_id(
163             cr, uid, 'crm', 'view_crm_case_opportunities_filter')
164         opportunity_view_search = models_data.browse(
165             cr, uid, result, context=context).res_id
166         opportunity_view_form = models_data._get_id(
167             cr, uid, 'crm', 'crm_case_form_view_oppor')
168         opportunity_view_tree = models_data._get_id(
169             cr, uid, 'crm', 'crm_case_tree_view_oppor')
170         if opportunity_view_form:
171             opportunity_view_form = models_data.browse(
172                 cr, uid, opportunity_view_form, context=context).res_id
173         if opportunity_view_tree:
174             opportunity_view_tree = models_data.browse(
175                 cr, uid, opportunity_view_tree, context=context).res_id
176
177         for lead in leads.browse(cr, uid, record_id, context=context):
178             if lead.section_id:
179                 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('type','=','opportunity'),('sequence','>=',1), ('section_ids','=', lead.section_id.id)])
180             else:
181                 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('type','=','opportunity'),('sequence','>=',1)])
182
183             data = self.browse(cr, uid, ids[0], context=context)
184
185
186             if data.action == 'create':
187                 partner_ids = []
188                 partner_ids = self._create_partner(cr, uid, ids, context=context)
189                 partner_id = partner_ids and partner_ids[0]
190             elif data.action == 'exist':
191                 partner_id = data.partner_id and data.partner_id.id
192             else:
193                 partner_id = False
194
195             self._convert(cr, uid, ids, lead, partner_id, stage_ids, context=context)
196             self.send_mail_to_salesman(lead)
197             #If we convert in mass, don't merge if there is no other opportunity but no warning
198             if data.name == 'merge' and (len(data.opportunity_ids) > 1 or not context.get('mass_convert') ):
199                 merge_obj = self.pool.get('crm.merge.opportunity')
200                 self.write(cr, uid, ids, {'opportunity_ids' : [(6,0, [data.opportunity_ids[0].id])]}, context=context)
201                 context.update({'lead_ids' : record_id})
202                 return merge_obj.merge(cr, uid, data.opportunity_ids, context=context)
203
204         return {
205             'name': _('Opportunity'),
206             'view_type': 'form',
207             'view_mode': 'form,tree',
208             'res_model': 'crm.lead',
209             'domain': [('type', '=', 'opportunity')],
210             'res_id': int(lead.id),
211             'view_id': False,
212             'views': [(opportunity_view_form, 'form'),
213                       (opportunity_view_tree, 'tree'),
214                       (False, 'calendar'), (False, 'graph')],
215             'type': 'ir.actions.act_window',
216             'search_view_id': opportunity_view_search
217         }
218
219 crm_lead2opportunity_partner()
220
221 class crm_lead2opportunity_mass_convert(osv.osv_memory):
222     _name = 'crm.lead2opportunity.partner.mass'
223     _description = 'Mass Lead To Opportunity Partner'
224     _inherit = 'crm.lead2opportunity.partner'
225
226
227     _columns = {
228             'user_ids':  fields.many2many('res.users', 'mass_convert_rel', 'user_id', 'wizard_id', 'Salesmans'),
229             'section_id': fields.many2one('crm.case.section', 'Sales Team'),
230
231     }
232
233     def mass_convert(self, cr, uid, ids, context=None):
234         lead_obj = self.pool.get('crm.lead')
235         if not context:
236             context = {}
237
238         active_ids = context.get('active_ids')
239         data = self.browse(cr, uid, ids, context=context)[0]
240
241         salesteam = data.section_id and data.section_id.id
242         if data.user_ids:
243             salesmans = map(lambda x : x.id, data.user_ids)
244             index = 0
245         else:
246             salesmans = False
247
248         for lead_id in active_ids:
249             value = {}
250             if salesteam:
251                 value['section_id'] = salesteam
252             if salesmans:
253                 value['user_id'] = salesmans[index]
254                 index += 1
255                 index = index < len(salesmans) and index or 0
256             if value:
257                 lead_obj.write(cr, uid, [lead_id], value, context=context)
258
259             context['active_ids'] = [lead_id]
260             value = self.default_get(cr, uid, ['partner_id', 'opportunity_ids'], context=context)
261             value['opportunity_ids'] = [(6, 0, value['opportunity_ids'])]
262             self.write(cr, uid, ids, value, context=context)
263
264             self.action_apply(cr, uid, ids, context=context)
265
266
267
268         models_data = self.pool.get('ir.model.data')
269         result = models_data._get_id(cr, uid, 'crm', 'view_crm_case_opportunities_filter')
270         opportunity_view_search = models_data.browse(cr, uid, result, context=context).res_id
271
272         return {
273             'name': _('Opportunity'),
274             'view_type': 'form',
275             'view_mode': 'tree,form',
276             'res_model': 'crm.lead',
277             'domain': [('type', '=', 'opportunity'), ('id', 'in', active_ids)],
278             'type': 'ir.actions.act_window',
279             'search_view_id': opportunity_view_search,
280         }
281
282 crm_lead2opportunity_mass_convert()
283 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: