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