[MERGE] mail/chatter complete review/refactoring
[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 class crm_lead2opportunity_partner(osv.osv_memory):
28     _name = 'crm.lead2opportunity.partner'
29     _description = 'Lead To Opportunity Partner'
30     _inherit = 'crm.lead2partner'
31
32     _columns = {
33         'action': fields.selection([('exist', 'Link to an existing partner'), \
34                                     ('create', 'Create a new partner'), \
35                                     ('nothing', 'Do not link to a partner')], \
36                                     'Related Partner', required=True),
37         'name': fields.selection([('convert', 'Convert to Opportunities'), ('merge', 'Merge with existing Opportunities')], 'Conversion Action', required=True),
38         'opportunity_ids': fields.many2many('crm.lead', string='Opportunities', domain=[('type', '=', 'opportunity')]),
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 opportunity link with this partnet to merge
45             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         opportunities = res.get('opportunity_ids') or []
51         partner_id = False
52         email = False
53         for lead in lead_obj.browse(cr, uid, opportunities, context=context):
54             partner_id = lead.partner_id and lead.partner_id.id or False
55
56             #TOFIX: use mail.mail_message.to_mail
57             email = re.findall(r'([^ ,<@]+@[^> ,]+)', lead.email_from or '')
58             email = map(lambda x: "'" + x + "'", email)
59
60         if not partner_id and res.get('partner_id'):
61             partner_id = res.get('partner_id')
62
63         ids = []
64         if partner_id:
65             ids = lead_obj.search(cr, uid, [('partner_id', '=', partner_id), ('type', '=', 'opportunity'), '!', ('state', 'in', ['done', 'cancel'])])
66             if ids:
67                 opportunities.append(ids[0])
68         if not partner_id:
69             if email:
70                 # Find email of existing opportunity matches the email_from of the lead
71                 cr.execute("""select id from crm_lead where type='opportunity' and
72                                 substring(email_from from '([^ ,<@]+@[^> ,]+)') in (%s)""" % (','.join(email)))
73                 ids = map(lambda x:x[0], cr.fetchall())
74             if ids:
75                 opportunities.append(ids[0])
76
77         if 'action' in fields:
78             res.update({'action' : partner_id and 'exist' or 'create'})
79         if 'partner_id' in fields:
80             res.update({'partner_id' : partner_id})
81         if 'name' in fields:
82             res.update({'name' : ids and 'merge' or 'convert'})
83         if 'opportunity_ids' in fields:
84             res.update({'opportunity_ids': opportunities})
85
86
87         return res
88
89     def view_init(self, cr, uid, fields, context=None):
90         """
91         This function checks for precondition before wizard executes
92         """
93         if context is None:
94             context = {}
95         lead_obj = self.pool.get('crm.lead')
96         for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
97             if lead.state in ['done', 'cancel']:
98                 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled leads cannot be converted into opportunities."))
99         return False
100
101     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
102         if context is None:
103             context = {}
104         lead = self.pool.get('crm.lead')
105         res = False
106         partner_ids_map = self._create_partner(cr, uid, ids, context=context)
107         lead_ids = vals.get('lead_ids', [])
108         team_id = vals.get('section_id', False)
109         for lead_id in lead_ids:
110             partner_id = partner_ids_map.get(lead_id, False)
111             # FIXME: cannot pass user_ids as the salesman allocation only works in batch
112             res = lead.convert_opportunity(cr, uid, [lead_id], partner_id, [], team_id, context=context)
113         # FIXME: must perform salesman allocation in batch separately here  
114         user_ids = vals.get('user_ids', False)
115         if user_ids:
116             lead.allocate_salesman(cr, uid, lead_ids, user_ids, team_id=team_id, context=context)
117         return res
118
119     def _merge_opportunity(self, cr, uid, ids, opportunity_ids, action='merge', context=None):
120         if context is None:
121             context = {}
122         res = False
123         # Expected: all newly-converted leads (active_ids) will be merged with the opportunity(ies)
124         # that have been selected in the 'opportunity_ids' m2m, with all these records
125         # merged into the first opportunity (and the rest deleted)
126         opportunity_ids = [o.id for o in opportunity_ids]
127         lead_ids = context.get('active_ids', [])
128         if action == 'merge' and lead_ids and opportunity_ids:
129             # Add the leads in the to-merge list, next to other opps
130             # (the fact that they're passed in context['lead_ids'] means that
131             # they cannot be selected to contain the result of the merge.
132             opportunity_ids.extend(lead_ids)
133             context.update({'lead_ids': lead_ids, "convert" : True})
134             res = self.pool.get('crm.lead').merge_opportunity(cr, uid, opportunity_ids, context=context)
135         return res
136
137     def action_apply(self, cr, uid, ids, context=None):
138         """
139         This converts lead to opportunity and opens Opportunity view
140         """
141         if not context:
142             context = {}
143         lead = self.pool.get('crm.lead')
144         lead_ids = context.get('active_ids', [])
145         data = self.browse(cr, uid, ids, context=context)[0]
146         self._convert_opportunity(cr, uid, ids, {'lead_ids': lead_ids}, context=context)
147         self._merge_opportunity(cr, uid, ids, data.opportunity_ids, data.name, context=context)
148         return lead.redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
149
150
151 class crm_lead2opportunity_mass_convert(osv.osv_memory):
152     _name = 'crm.lead2opportunity.partner.mass'
153     _description = 'Mass Lead To Opportunity Partner'
154     _inherit = 'crm.lead2opportunity.partner'
155
156     _columns = {
157             'user_ids':  fields.many2many('res.users', string='Salesmen'),
158             'section_id': fields.many2one('crm.case.section', 'Sales Team'),
159     }
160
161     def default_get(self, cr, uid, fields, context=None):
162         res = super(crm_lead2opportunity_mass_convert, self).default_get(cr, uid, fields, context)
163         if 'partner_id' in fields:
164             # avoid forcing the partner of the first lead as default
165             res['partner_id'] = False
166         if 'action' in fields:
167             res['action'] = 'create'
168         if 'name' in fields:
169             res['name'] = 'convert'
170         if 'opportunity_ids' in fields:
171             res['opportunity_ids'] = False
172         return res
173
174     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
175         data = self.browse(cr, uid, ids, context=context)[0]
176         salesteam_id = data.section_id and data.section_id.id or False
177         salesman = []
178         if data.user_ids:
179             salesman = [x.id for x in data.user_ids]
180         vals.update({'user_ids': salesman, 'section_id': salesteam_id})
181         return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
182
183     def mass_convert(self, cr, uid, ids, context=None):
184         return self.action_apply(cr, uid, ids, context=context)
185
186 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: