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')
51 res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
52 opportunities = res.get('opportunity_ids') or []
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)
60 if not partner_id and res.get('partner_id'):
61 partner_id = res.get('partner_id')
65 ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id), ('type', '=', 'opportunity'), '!', ('state', 'in', ['done', 'cancel'])])
67 opportunities.append(ids[0])
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())
79 opportunities.append(ids[0])
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})
86 res.update({'name' : ids and 'merge' or 'convert'})
87 if 'opportunity_ids' in fields:
88 res.update({'opportunity_ids': opportunities})
93 def view_init(self, cr, uid, fields, context=None):
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
104 lead_obj = self.pool.get('crm.lead')
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"))
111 def _convert(self, cr, uid, ids, lead, partner_id, stage_ids, context=None):
112 leads = self.pool.get('crm.lead')
115 address_id = self.pool.get('res.partner.address').search(cr, uid,
116 [('partner_id', '=', partner_id)],
117 order='create_date desc',
120 'planned_revenue': lead.planned_revenue,
121 'probability': lead.probability,
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'),
129 if partner_id and address_id:
130 vals['partner_address_id'] = address_id[0]
132 vals['partner_address_id'] = False
134 lead.write(vals, context=context)
135 text = _('Converted to opportunity')
136 leads.message_append(cr, uid, [lead], text, body_text=text, context=context)
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
142 leads.log(cr, uid, lead.id, _("Lead '%s' has been converted to an opportunity.") % lead.name)
144 def send_mail_to_salesman(self, cr, uid, lead):
145 email_to = lead.user_id and lead.user_id.user_email
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)
155 def action_apply(self, cr, uid, ids, context=None):
157 This converts lead to opportunity and opens Opportunity view
158 @param ids: ids of the leads to convert to opportunities
160 @return : View dictionary opening the Opportunity form view
165 record_id = context and context.get('active_ids') or False
167 return {'type': 'ir.actions.act_window_close'}
169 leads = self.pool.get('crm.lead')
170 models_data = self.pool.get('ir.model.data')
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
188 for lead in leads.browse(cr, uid, record_id, context=context):
190 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('sequence','>=',1), ('section_ids','=', lead.section_id.id)])
192 stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('sequence','>=',1)])
194 data = self.browse(cr, uid, ids[0], context=context)
197 if data.action == 'create':
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
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)
216 'name': _('Opportunity'),
218 'view_mode': 'form,tree',
219 'res_model': 'crm.lead',
220 'domain': [('type', '=', 'opportunity')],
221 'res_id': int(lead.id),
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
230 crm_lead2opportunity_partner()
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'
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'),
244 def mass_convert(self, cr, uid, ids, context=None):
245 lead_obj = self.pool.get('crm.lead')
249 active_ids = context.get('active_ids')
250 data = self.browse(cr, uid, ids, context=context)[0]
252 salesteam = data.section_id and data.section_id.id
254 salesmans = map(lambda x : x.id, data.user_ids)
259 for lead_id in active_ids:
262 value['section_id'] = salesteam
264 value['user_id'] = salesmans[index]
266 index = index < len(salesmans) and index or 0
268 lead_obj.write(cr, uid, [lead_id], value, context=context)
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)
275 self.action_apply(cr, uid, ids, context=context)
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
284 'name': _('Opportunity'),
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,
293 crm_lead2opportunity_mass_convert()
294 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: