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 _
29 class crm_lead2opportunity_partner(osv.osv_memory):
30 _name = 'crm.lead2opportunity.partner'
31 _description = 'Lead To Opportunity Partner'
32 _inherit = 'crm.lead2partner'
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')]),
43 def default_get(self, cr, uid, fields, context=None):
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
49 lead_obj = self.pool.get('crm.lead')
52 res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
53 opportunities = res.get('opportunity_ids') or []
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)
61 if not partner_id and res.get('partner_id'):
62 partner_id = res.get('partner_id')
66 ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id), ('type', '=', 'opportunity'), '!', ('state', 'in', ['done', 'cancel'])])
68 opportunities.append(ids[0])
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())
80 opportunities.append(ids[0])
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})
87 res.update({'name' : ids and 'merge' or 'convert'})
88 if 'opportunity_ids' in fields:
89 res.update({'opportunity_ids': opportunities})
94 def view_init(self, cr, uid, fields, context=None):
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
105 lead_obj = self.pool.get('crm.lead')
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"))
112 def _convert(self, cr, uid, ids, lead, partner_id, stage_ids, context=None):
113 leads = self.pool.get('crm.lead')
116 address_id = self.pool.get('res.partner.address').search(cr, uid,
117 [('partner_id', '=', partner_id)],
118 order='create_date desc',
121 'planned_revenue': lead.planned_revenue,
122 'probability': lead.probability,
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'),
130 if partner_id and address_id:
131 vals['partner_address_id'] = address_id[0]
133 vals['partner_address_id'] = False
135 lead.write(vals, context=context)
136 leads.history(cr, uid, [lead], _('Converted to opportunity'), details='Converted to Opportunity', context=context)
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
142 leads.log(cr, uid, lead.id, _("Lead '%s' has been converted to an opportunity.") % lead.name)
144 def send_mail_to_salesman(self, lead):
145 email_to = lead.user_id and lead.user_id.user_email
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)
153 tools.email_send(email_from, email_to, subject, body)
157 def action_apply(self, cr, uid, ids, context=None):
159 This converts lead to opportunity and opens Opportunity view
160 @param ids: ids of the leads to convert to opportunities
162 @return : View dictionary opening the Opportunity form view
167 record_id = context and context.get('active_ids') or False
169 return {'type': 'ir.actions.act_window_close'}
171 leads = self.pool.get('crm.lead')
172 models_data = self.pool.get('ir.model.data')
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
190 for lead in leads.browse(cr, uid, record_id, context=context):
192 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('type','=','opportunity'),('sequence','>=',1), ('section_ids','=', lead.section_id.id)])
194 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('type','=','opportunity'),('sequence','>=',1)])
196 data = self.browse(cr, uid, ids[0], context=context)
199 if data.action == 'create':
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
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)
218 'name': _('Opportunity'),
220 'view_mode': 'form,tree',
221 'res_model': 'crm.lead',
222 'domain': [('type', '=', 'opportunity')],
223 'res_id': int(lead.id),
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
232 crm_lead2opportunity_partner()
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'
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'),
246 def mass_convert(self, cr, uid, ids, context=None):
247 lead_obj = self.pool.get('crm.lead')
251 active_ids = context.get('active_ids')
252 data = self.browse(cr, uid, ids, context=context)[0]
254 salesteam = data.section_id and data.section_id.id
256 salesmans = map(lambda x : x.id, data.user_ids)
261 for lead_id in active_ids:
264 value['section_id'] = salesteam
266 value['user_id'] = salesmans[index]
268 index = index < len(salesmans) and index or 0
270 lead_obj.write(cr, uid, [lead_id], value, context=context)
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)
277 self.action_apply(cr, uid, ids, context=context)
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
286 'name': _('Opportunity'),
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,
295 crm_lead2opportunity_mass_convert()
296 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: