[MERGE] Merge with lp:openobject-addons
[odoo/odoo.git] / addons / crm / wizard / crm_lead_to_partner.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 re
25
26 class crm_lead2partner(osv.osv_memory):
27     """ Converts lead to partner """
28
29     _name = 'crm.lead2partner'
30     _description = 'Lead to Partner'
31
32     _columns = {
33         'action': fields.selection([('exist', 'Link to an existing partner'), \
34                                     ('create', 'Create a new partner')], \
35                                     'Action', required=True),
36         'partner_id': fields.many2one('res.partner', 'Partner'),
37     }
38
39     def view_init(self, cr, uid, fields, context=None):
40         """
41         This function checks for precondition before wizard executes
42         @param self: The object pointer
43         @param cr: the current row, from the database cursor,
44         @param uid: the current user’s ID for security checks,
45         @param fields: List of fields for default value
46         @param context: A standard dictionary for contextual values
47
48         """
49
50         lead_obj = self.pool.get('crm.lead')
51         rec_ids = context and context.get('active_ids', [])
52         for lead in lead_obj.browse(cr, uid, rec_ids, context=context):
53             if lead.partner_id:
54                 raise osv.except_osv(_('Warning !'),
55                         _('A partner is already defined on this lead.'))
56
57     def default_get(self, cr, uid, fields, context=None):
58         """
59         This function gets default values
60         @param self: The object pointer
61         @param cr: the current row, from the database cursor,
62         @param uid: the current user’s ID for security checks,
63         @param fields: List of fields for default value
64         @param context: A standard dictionary for contextual values
65
66         @return : default values of fields.
67         """
68
69         lead_obj = self.pool.get('crm.lead')
70         partner_obj = self.pool.get('res.partner')
71         partner_id = False
72
73         data = list(context and context.get('active_ids', []) or [])
74         res = super(crm_lead2partner, self).default_get(cr, uid, fields, context=context)
75         for lead in lead_obj.browse(cr, uid, data, context=context):
76             partner_ids = []
77             # Find partner address matches the email_from of the lead
78             email = re.findall(r'([^ ,<@]+@[^> ,]+)', lead.email_from or '')
79             email = map(lambda x: "'" + x + "'", email)
80             if email:
81                 cr.execute("""select id from res_partner_address
82                                 where
83                                 substring(email from '([^ ,<@]+@[^> ,]+)') in (%s)""" % (','.join(email)))
84                 address_ids = map(lambda x: x[0], cr.fetchall())
85                 if address_ids:
86                     partner_ids = partner_obj.search(cr, uid, [('address', 'in', address_ids)], context=context)
87                     
88             # Find partner name that matches the name of the lead
89             if not partner_ids and lead.partner_name:
90                 partner_ids = partner_obj.search(cr, uid, [('name', '=', lead.partner_name)], context=context)
91                 
92             partner_id = partner_ids and partner_ids[0] or False
93             
94             
95
96             if 'partner_id' in fields:
97                 res.update({'partner_id': partner_id})
98             if 'action' in fields:
99                 res.update({'action': partner_id and 'exist' or 'create'})
100             if 'opportunity_ids' in fields:
101                 res.update({'opportunity_ids': data})
102
103         return res
104
105     def open_create_partner(self, cr, uid, ids, context=None):
106         """
107         This function Opens form of create partner.
108         @param self: The object pointer
109         @param cr: the current row, from the database cursor,
110         @param uid: the current user’s ID for security checks,
111         @param ids: List of Lead to Partner's IDs
112         @param context: A standard dictionary for contextual values
113
114         @return : Dictionary value for next form.
115         """
116         if context is None:
117             context = {}
118
119         view_obj = self.pool.get('ir.ui.view')
120         view_id = view_obj.search(cr, uid, [('model', '=', 'crm.lead2partner'), \
121                                      ('name', '=', 'crm.lead2partner.view')])
122         return {
123             'view_mode': 'form',
124             'view_type': 'form',
125             'view_id': view_id or False,
126             'res_model': 'crm.lead2partner',
127             'context': context,
128             'type': 'ir.actions.act_window',
129             'target': 'new',
130             }
131
132
133     def _create_partner(self, cr, uid, ids, context=None):
134         """
135         This function Creates partner based on action.
136         @param self: The object pointer
137         @param cr: the current row, from the database cursor,
138         @param uid: the current user’s ID for security checks,
139         @param ids: List of Lead to Partner's IDs
140         @param context: A standard dictionary for contextual values
141
142         @return : Dictionary {}.
143         """
144         if context is None:
145             context = {}
146
147         lead_obj = self.pool.get('crm.lead')
148         partner_obj = self.pool.get('res.partner')
149         contact_obj = self.pool.get('res.partner.address')
150         partner_ids = []
151         partner_id = False
152         rec_ids = context and context.get('active_ids', [])
153
154         for data in self.browse(cr, uid, ids, context=context):
155             for lead in lead_obj.browse(cr, uid, rec_ids, context=context):
156                 if data.action == 'create':
157                     partner_id = partner_obj.create(cr, uid, {
158                         'name': lead.partner_name or lead.contact_name or lead.name,
159                         'user_id': lead.user_id.id,
160                         'comment': lead.description,
161                     })
162                     contact_obj.create(cr, uid, {
163                         'partner_id': partner_id,
164                         'name': lead.contact_name,
165                         'phone': lead.phone,
166                         'mobile': lead.mobile,
167                         'email': lead.email_from,
168                         'fax': lead.fax,
169                         'title': lead.title and lead.title.id or False,
170                         'function': lead.function,
171                         'street': lead.street,
172                         'street2': lead.street2,
173                         'zip': lead.zip,
174                         'city': lead.city,
175                         'country_id': lead.country_id and lead.country_id.id or False,
176                         'state_id': lead.state_id and lead.state_id.id or False,
177                     })
178
179                 else:
180                     if data.partner_id:
181                         partner_id = data.partner_id.id
182                 self.assign_partner(cr, uid, lead.id, partner_id)
183                 partner_ids.append(partner_id)
184         return partner_ids
185
186
187     def assign_partner(self, cr, uid, lead_id, partner_id):
188         self.pool.get("crm.lead").write(cr, uid, [lead_id], {'partner_id' : partner_id})
189
190
191     def make_partner(self, cr, uid, ids, context=None):
192         """
193         This function Makes partner based on action.
194         @param self: The object pointer
195         @param cr: the current row, from the database cursor,
196         @param uid: the current user’s ID for security checks,
197         @param ids: List of Lead to Partner's IDs
198         @param context: A standard dictionary for contextual values
199
200         @return : Dictionary value for created Partner form.
201         """
202         if context is None:
203             context = {}
204
205         partner_ids = self._create_partner(cr, uid, ids, context=context)
206         return {'type': 'ir.actions.act_window_close'}
207
208 crm_lead2partner()
209
210 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: