[IMP] account: remove invoice addresss
[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                 
71                 
72         if not partner_id:
73             label = False
74             opp_ids = []
75             if email:
76                 # Find email of existing opportunity matches the email_from of the lead
77                 cr.execute("""select id from crm_lead where type='opportunity' and
78                                 substring(email_from from '([^ ,<@]+@[^> ,]+)') in (%s)""" % (','.join(email)))
79                 ids = map(lambda x:x[0], cr.fetchall())
80             if ids:
81                 opportunities.append(ids[0])
82
83         if 'action' in fields:
84             res.update({'action' : partner_id and 'exist' or 'create'})
85         if 'partner_id' in fields:
86             res.update({'partner_id' : partner_id})
87         if 'name' in fields:
88             res.update({'name' : ids and 'merge' or 'convert'})
89         if 'opportunity_ids' in fields:
90             res.update({'opportunity_ids': opportunities})
91
92
93         return res
94
95     def view_init(self, cr, uid, fields, context=None):
96         """
97         This function checks for precondition before wizard executes
98         """
99         if context is None:
100             context = {}
101         lead_obj = self.pool.get('crm.lead')
102         for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
103             if lead.state in ['done', 'cancel']:
104                 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled Leads can not be converted into Opportunity"))
105         return False
106
107     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
108         if context is None:
109             context = {}
110         lead = self.pool.get('crm.lead')
111         partner_id = self._create_partner(cr, uid, ids, context=context)
112         lead_ids = vals.get('lead_ids', [])
113         user_ids = vals.get('user_ids', False)
114         team_id = vals.get('section_id', False)
115         return lead.convert_opportunity(cr, uid, lead_ids, partner_id, user_ids, team_id, context=context) 
116
117     def _merge_opportunity(self, cr, uid, ids, opportunity_ids, action='merge', context=None):
118         #TOFIX: is it usefully ?
119         if context is None:
120             context = {}
121         merge_opportunity = self.pool.get('crm.merge.opportunity')
122         res = False
123         #If we convert in mass, don't merge if there is no other opportunity but no warning
124         if action == 'merge' and (len(opportunity_ids) > 1 or not context.get('mass_convert') ):
125             self.write(cr, uid, ids, {'opportunity_ids' : [(6,0, [opportunity_ids[0].id])]}, context=context)
126             context.update({'lead_ids' : record_id, "convert" : True})
127             res = merge_opportunity.merge(cr, uid, data.opportunity_ids, context=context)
128         return res
129
130     def action_apply(self, cr, uid, ids, context=None):
131         """
132         This converts lead to opportunity and opens Opportunity view
133         """
134         if not context:
135             context = {}
136         
137         lead = self.pool.get('crm.lead')
138         lead_ids = context.get('active_ids', [])
139         data = self.browse(cr, uid, ids, context=context)[0]
140         self._convert_opportunity(cr, uid, ids, {'lead_ids': lead_ids}, context=context)
141         self._merge_opportunity(cr, uid, ids, data.opportunity_ids, data.action, context=context)
142         return lead.redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
143
144 crm_lead2opportunity_partner()
145
146 class crm_lead2opportunity_mass_convert(osv.osv_memory):
147     _name = 'crm.lead2opportunity.partner.mass'
148     _description = 'Mass Lead To Opportunity Partner'
149     _inherit = 'crm.lead2opportunity.partner'
150
151
152     _columns = {
153             'user_ids':  fields.many2many('res.users', string='Salesmans'),
154             'section_id': fields.many2one('crm.case.section', 'Sales Team'),
155
156     }
157     def _convert_opportunity(self, cr, uid, ids, vals, context=None):
158         data = self.browse(cr, uid, ids, context=context)[0]
159         salesteam_id = data.section_id and data.section_id.id or False
160         salesman = []
161         if data.user_ids:
162             salesman = [x.id for x in data.user_ids]
163         vals.update({'user_ids': salesman, 'section_id': salesteam_id})
164         return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
165
166     def mass_convert(self, cr, uid, ids, context=None):
167         value = self.default_get(cr, uid, ['partner_id', 'opportunity_ids'], context=context)
168         value['opportunity_ids'] = [(6, 0, value['opportunity_ids'])]
169         self.write(cr, uid, ids, value, context=context)
170         return self.action_apply(cr, uid, ids, context=context)
171 crm_lead2opportunity_mass_convert()
172 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: