[MERGE] Sync with trunk
[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 openerp.osv import fields, osv
23 from openerp.tools.translate import _
24 import re
25
26 class crm_lead2opportunity_partner(osv.osv_memory):
27     _name = 'crm.lead2opportunity.partner'
28     _description = 'Lead To Opportunity Partner'
29     _inherit = 'crm.partner.binding'
30
31     _columns = {
32         'name': fields.selection([
33                 ('convert', 'Convert to opportunity'),
34                 ('merge', 'Merge with existing opportunities')
35             ], 'Conversion Action', required=True),
36         'opportunity_ids': fields.many2many('crm.lead', string='Opportunities'),
37         'user_id': fields.many2one('res.users', 'Salesperson', select=True),
38         'section_id': fields.many2one('crm.case.section', 'Sales Team', select=True),
39     }
40
41     def default_get(self, cr, uid, fields, context=None):
42         """
43         Default get for name, opportunity_ids.
44         If there is an exisitng partner link to the lead, find all existing
45         opportunities links with this partner to merge all information together
46         """
47         lead_obj = self.pool.get('crm.lead')
48
49         res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
50         if context.get('active_id'):
51             tomerge = set([int(context['active_id'])])
52
53             email = False
54             partner_id = res.get('partner_id')
55             lead = lead_obj.browse(cr, uid, int(context['active_id']), context=context)
56
57             #TOFIX: use mail.mail_message.to_mail
58             email = re.findall(r'([^ ,<@]+@[^> ,]+)', lead.email_from or '')
59
60             if partner_id:
61                 # Search for opportunities that have the same partner and that arent done or cancelled
62                 ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id),  ('probability', '<', '100')])
63                 for id in ids:
64                     tomerge.add(id)
65             if email:
66                 ids = lead_obj.search(cr, uid, [('email_from', 'ilike', email[0]),  ('probability', '<', '100')])
67                 for id in ids:
68                     tomerge.add(id)
69
70             if 'action' in fields:
71                 res.update({'action' : partner_id and 'exist' or 'create'})
72             if 'partner_id' in fields:
73                 res.update({'partner_id' : partner_id})
74             if 'name' in fields:
75                 res.update({'name' : len(tomerge) >= 2 and 'merge' or 'convert'})
76             if 'opportunity_ids' in fields and len(tomerge) >= 2:
77                 res.update({'opportunity_ids': list(tomerge)})
78             if lead.user_id:
79                 res.update({'user_id': lead.user_id.id})
80             if lead.section_id:
81                 res.update({'section_id': lead.section_id.id})
82         return res
83
84     def on_change_user(self, cr, uid, ids, user_id, section_id, context=None):
85         """ When changing the user, also set a section_id or restrict section id
86             to the ones user_id is member of. """
87         if user_id:
88             if section_id:
89                 user_in_section = self.pool.get('crm.case.section').search(cr, uid, [('id', '=', section_id), '|', ('user_id', '=', user_id), ('member_ids', '=', user_id)], context=context, count=True)
90             else:
91                 user_in_section = False
92             if not user_in_section:
93                 section_id = False
94                 section_ids = self.pool.get('crm.case.section').search(cr, uid, ['|', ('user_id', '=', user_id), ('member_ids', '=', user_id)], context=context)
95                 if section_ids:
96                     section_id = section_ids[0]
97         return {'value': {'section_id': section_id}}
98
99     def view_init(self, cr, uid, fields, context=None):
100         """
101         Check some preconditions before the wizard executes.
102         """
103         if context is None:
104             context = {}
105         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.probability == 100:
108                 raise osv.except_osv(_("Warning!"), _("Closed/Dead leads cannot be converted into opportunities."))
109         return False
110
111     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
112         if context is None:
113             context = {}
114         lead = self.pool.get('crm.lead')
115         res = False
116         partner_ids_map = self._create_partner(cr, uid, ids, context=context)
117         lead_ids = vals.get('lead_ids', [])
118         team_id = vals.get('section_id', False)
119         for lead_id in lead_ids:
120             partner_id = partner_ids_map.get(lead_id, False)
121             # FIXME: cannot pass user_ids as the salesman allocation only works in batch
122             res = lead.convert_opportunity(cr, uid, [lead_id], partner_id, [], team_id, context=context)
123         # FIXME: must perform salesman allocation in batch separately here
124         user_ids = vals.get('user_ids', False)
125         if user_ids:
126             lead.allocate_salesman(cr, uid, lead_ids, user_ids, team_id=team_id, context=context)
127         return res
128
129     def action_apply(self, cr, uid, ids, context=None):
130         """
131         Convert lead to opportunity or merge lead and opportunity and open
132         the freshly created opportunity view.
133         """
134         if context is None:
135             context = {}
136
137         w = self.browse(cr, uid, ids, context=context)[0]
138         opp_ids = [o.id for o in w.opportunity_ids]
139         if w.name == 'merge':
140             lead_id = self.pool.get('crm.lead').merge_opportunity(cr, uid, opp_ids, w.user_id.id, w.section_id.id, context=context)
141             lead_ids = [lead_id]
142             lead = self.pool.get('crm.lead').read(cr, uid, lead_id, ['type'], context=context)
143             if lead['type'] == "lead":
144                 context.update({'active_ids': lead_ids})
145                 self._convert_opportunity(cr, uid, ids, {'lead_ids': lead_ids, 'user_ids': [w.user_id.id], 'section_id': w.section_id.id}, context=context)
146         else:
147             lead_ids = context.get('active_ids', [])
148             self._convert_opportunity(cr, uid, ids, {'lead_ids': lead_ids, 'user_ids': [w.user_id.id], 'section_id': w.section_id.id}, context=context)
149
150         return self.pool.get('crm.lead').redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
151
152     def _create_partner(self, cr, uid, ids, context=None):
153         """
154         Create partner based on action.
155         :return dict: dictionary organized as followed: {lead_id: partner_assigned_id}
156         """
157         #TODO this method in only called by crm_lead2opportunity_partner
158         #wizard and would probably diserve to be refactored or at least
159         #moved to a better place
160         if context is None:
161             context = {}
162         lead = self.pool.get('crm.lead')
163         lead_ids = context.get('active_ids', [])
164         data = self.browse(cr, uid, ids, context=context)[0]
165         partner_id = data.partner_id and data.partner_id.id or False
166         return lead.handle_partner_assignation(cr, uid, lead_ids, data.action, partner_id, context=context)
167
168 class crm_lead2opportunity_mass_convert(osv.osv_memory):
169     _name = 'crm.lead2opportunity.partner.mass'
170     _description = 'Mass Lead To Opportunity Partner'
171     _inherit = 'crm.lead2opportunity.partner'
172
173     _columns = {
174         'user_ids':  fields.many2many('res.users', string='Salesmen'),
175         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
176     }
177
178     def default_get(self, cr, uid, fields, context=None):
179         res = super(crm_lead2opportunity_mass_convert, self).default_get(cr, uid, fields, context)
180         if 'partner_id' in fields:
181             # avoid forcing the partner of the first lead as default
182             res['partner_id'] = False
183         if 'action' in fields:
184             res['action'] = 'create'
185         if 'name' in fields:
186             res['name'] = 'convert'
187         if 'opportunity_ids' in fields:
188             res['opportunity_ids'] = False
189         return res
190
191     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
192         """
193         When "massively" (more than one at a time) converting leads to
194         opportunities, check the salesteam_id and salesmen_ids and update
195         the values before calling super.
196         """
197         if context is None:
198             context = {}
199         data = self.browse(cr, uid, ids, context=context)[0]
200         salesteam_id = data.section_id and data.section_id.id or False
201         salesmen_ids = []
202         if data.user_ids:
203             salesmen_ids = [x.id for x in data.user_ids]
204         vals.update({'user_ids': salesmen_ids, 'section_id': salesteam_id})
205         return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
206
207     def mass_convert(self, cr, uid, ids, context=None):
208         return self.action_apply(cr, uid, ids, context=context)
209
210 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: