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