[MERGE] upstream
[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', string='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
58             #TOFIX: use mail.mail_message.to_mail
59             email = re.findall(r'([^ ,<@]+@[^> ,]+)', lead.email_from or '')
60             email = map(lambda x: "'" + x + "'", email)
61
62         if not partner_id and res.get('partner_id'):
63             partner_id = res.get('partner_id')
64
65         ids = []
66         if partner_id:
67             ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id), ('type', '=', 'opportunity'), '!', ('state', 'in', ['done', 'cancel'])])
68             if ids:
69                 opportunities.append(ids[0])
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         """
97         if context is None:
98             context = {}
99         lead_obj = self.pool.get('crm.lead')
100         for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
101             if lead.state in ['done', 'cancel']:
102                 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled Leads can not be converted into Opportunity"))
103         return False
104
105     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
106         if context is None:
107             context = {}
108         lead = self.pool.get('crm.lead')
109         partner_id = self._create_partner(cr, uid, ids, context=context)
110         lead_ids = vals.get('lead_ids', [])
111         user_ids = vals.get('user_ids', False)
112         team_id = vals.get('section_id', False)
113         return lead.convert_opportunity(cr, uid, lead_ids, partner_id, user_ids, team_id, context=context) 
114
115     def _merge_opportunity(self, cr, uid, ids, opportunity_ids, action='merge', context=None):
116         #TOFIX: is it usefully ?
117         if context is None:
118             context = {}
119         merge_opportunity = self.pool.get('crm.merge.opportunity')
120         res = False
121         #If we convert in mass, don't merge if there is no other opportunity but no warning
122         if action == 'merge' and (len(opportunity_ids) > 1 or not context.get('mass_convert') ):
123             self.write(cr, uid, ids, {'opportunity_ids' : [(6,0, [opportunity_ids[0].id])]}, context=context)
124             context.update({'lead_ids' : record_id, "convert" : True})
125             res = merge_opportunity.merge(cr, uid, data.opportunity_ids, context=context)
126         return res
127
128     def action_apply(self, cr, uid, ids, context=None):
129         """
130         This converts lead to opportunity and opens Opportunity view
131         """
132         if not context:
133             context = {}
134         
135         lead = self.pool.get('crm.lead')
136         lead_ids = context.get('active_ids', [])
137         data = self.browse(cr, uid, ids, context=context)[0]
138         self._convert_opportunity(cr, uid, ids, {'lead_ids': lead_ids}, context=context)
139         self._merge_opportunity(cr, uid, ids, data.opportunity_ids, data.action, context=context)
140         return lead.redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
141
142 crm_lead2opportunity_partner()
143
144 class crm_lead2opportunity_mass_convert(osv.osv_memory):
145     _name = 'crm.lead2opportunity.partner.mass'
146     _description = 'Mass Lead To Opportunity Partner'
147     _inherit = 'crm.lead2opportunity.partner'
148
149
150     _columns = {
151             'user_ids':  fields.many2many('res.users', string='Salesmans'),
152             'section_id': fields.many2one('crm.case.section', 'Sales Team'),
153
154     }
155     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
156         data = self.browse(cr, uid, ids, context=context)[0]
157         salesteam_id = data.section_id and data.section_id.id or False
158         salesman = []
159         if data.user_ids:
160             salesman = [x.id for x in data.user_ids]
161         vals.update({'user_ids': salesman, 'section_id': salesteam_id})
162         return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
163
164     def mass_convert(self, cr, uid, ids, context=None):
165         value = self.default_get(cr, uid, ['partner_id', 'opportunity_ids'], context=context)
166         value['opportunity_ids'] = [(6, 0, value['opportunity_ids'])]
167         self.write(cr, uid, ids, value, context=context)
168         return self.action_apply(cr, uid, ids, context=context)
169 crm_lead2opportunity_mass_convert()
170 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: