1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from osv import osv, fields
23 from tools.translate import _
27 class crm_lead2opportunity_partner(osv.osv_memory):
28 _name = 'crm.lead2opportunity.partner'
29 _description = 'Lead To Opportunity Partner'
30 _inherit = 'crm.partner.binding'
33 'name': fields.selection([
34 ('convert', 'Convert to opportunity'),
35 ('merge', 'Merge with existing opportunities')
36 ], 'Conversion Action', required=True),
37 'opportunity_ids': fields.many2many('crm.lead', string='Opportunities', domain=[('type', '=', 'opportunity')]),
40 def default_get(self, cr, uid, fields, context=None):
42 Default get for name, opportunity_ids.
43 If there is an exisitng partner link to the lead, find all existing
44 opportunities links with this partner to merge all information together
46 lead_obj = self.pool.get('crm.lead')
48 res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
49 opportunities = res.get('opportunity_ids') or []
52 for lead in lead_obj.browse(cr, uid, opportunities, context=context):
53 partner_id = lead.partner_id and lead.partner_id.id or False
55 #TOFIX: use mail.mail_message.to_mail
56 email = re.findall(r'([^ ,<@]+@[^> ,]+)', lead.email_from or '')
57 email = map(lambda x: "'" + x + "'", email)
59 if not partner_id and res.get('partner_id'):
60 partner_id = res.get('partner_id')
64 # Search for opportunities that have the same partner and that arent done or cancelled
65 ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id), ('type', '=', 'opportunity'), '!', ('state', 'in', ['done', 'cancel'])])
67 opportunities.append(ids[0])
70 # Find email of existing opportunity matching the email_from of the lead
71 cr.execute("""select id from crm_lead where type='opportunity' and
72 substring(email_from from '([^ ,<@]+@[^> ,]+)') in (%s)""" % (','.join(email)))
73 ids = map(lambda x:x[0], cr.fetchall())
75 opportunities.append(ids[0])
77 if 'action' in fields:
78 res.update({'action' : partner_id and 'exist' or 'create'})
79 if 'partner_id' in fields:
80 res.update({'partner_id' : partner_id})
82 res.update({'name' : ids and 'merge' or 'convert'})
83 if 'opportunity_ids' in fields:
84 res.update({'opportunity_ids': opportunities})
88 def view_init(self, cr, uid, fields, context=None):
90 Check some preconditions before the wizard executes.
94 lead_obj = self.pool.get('crm.lead')
95 for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
96 if lead.state in ['done', 'cancel']:
97 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled leads cannot be converted into opportunities."))
100 def _convert_opportunity(self, cr, uid, ids, vals, context=None):
103 lead = self.pool.get('crm.lead')
105 partner_ids_map = self._create_partner(cr, uid, ids, context=context)
106 lead_ids = vals.get('lead_ids', [])
107 team_id = vals.get('section_id', False)
108 for lead_id in lead_ids:
109 partner_id = partner_ids_map.get(lead_id, False)
110 # FIXME: cannot pass user_ids as the salesman allocation only works in batch
111 res = lead.convert_opportunity(cr, uid, [lead_id], partner_id, [], team_id, context=context)
112 # FIXME: must perform salesman allocation in batch separately here
113 user_ids = vals.get('user_ids', False)
115 lead.allocate_salesman(cr, uid, lead_ids, user_ids, team_id=team_id, context=context)
118 def _merge_opportunity(self, cr, uid, ids, opportunity_ids, action='merge', context=None):
122 # Expected: all newly-converted leads (active_ids) will be merged with the opportunity(ies)
123 # that have been selected in the 'opportunity_ids' m2m, with all these records
124 # merged into the first opportunity (and the rest deleted)
125 opportunity_ids = [o.id for o in opportunity_ids]
126 lead_ids = context.get('active_ids', [])
127 if action == 'merge' and lead_ids and opportunity_ids:
128 # Add the leads in the to-merge list, next to other opps
129 # (the fact that they're passed in context['lead_ids'] means that
130 # they cannot be selected to contain the result of the merge.
131 opportunity_ids.extend(lead_ids)
132 context.update({'lead_ids': lead_ids, "convert" : True})
133 res = self.pool.get('crm.lead').merge_opportunity(cr, uid, opportunity_ids, context=context)
136 def action_apply(self, cr, uid, ids, context=None):
138 Convert lead to opportunity or merge lead and opportunity and open
139 the freshly created opportunity view.
143 lead = self.pool.get('crm.lead')
144 lead_ids = context.get('active_ids', [])
145 data = self.browse(cr, uid, ids, context=context)[0]
146 self._convert_opportunity(cr, uid, ids, {'lead_ids': lead_ids}, context=context)
147 self._merge_opportunity(cr, uid, ids, data.opportunity_ids, data.name, context=context)
148 return lead.redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
151 class crm_lead2opportunity_mass_convert(osv.osv_memory):
152 _name = 'crm.lead2opportunity.partner.mass'
153 _description = 'Mass Lead To Opportunity Partner'
154 _inherit = 'crm.lead2opportunity.partner'
157 'user_ids': fields.many2many('res.users', string='Salesmen'),
158 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
161 def default_get(self, cr, uid, fields, context=None):
162 res = super(crm_lead2opportunity_mass_convert, self).default_get(cr, uid, fields, context)
163 if 'partner_id' in fields:
164 # avoid forcing the partner of the first lead as default
165 res['partner_id'] = False
166 if 'action' in fields:
167 res['action'] = 'create'
169 res['name'] = 'convert'
170 if 'opportunity_ids' in fields:
171 res['opportunity_ids'] = False
174 def _convert_opportunity(self, cr, uid, ids, vals, context=None):
176 When "massively" (more than one at a time) converting leads to
177 opportunities, check the salesteam_id and salesmen_ids and update
178 the values before calling super.
182 data = self.browse(cr, uid, ids, context=context)[0]
183 salesteam_id = data.section_id and data.section_id.id or False
186 salesmen_ids = [x.id for x in data.user_ids]
187 vals.update({'user_ids': salesmen_ids, 'section_id': salesteam_id})
188 return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
190 def mass_convert(self, cr, uid, ids, context=None):
191 return self.action_apply(cr, uid, ids, context=context)
193 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: