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