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