[IMP]: crm: Improvement in lead to opportunity wizard for partner id
[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 mx.DateTime import now
23 from osv import osv, fields
24 from tools.translate import _
25
26
27 class crm_lead2opportunity(osv.osv_memory):
28     _name = 'crm.lead2opportunity'
29     _description = 'Lead To Opportunity'
30     
31     def action_cancel(self, cr, uid, ids, context=None):
32         """
33         Closes Lead To Opportunity form
34         @param self: The object pointer
35         @param cr: the current row, from the database cursor,
36         @param uid: the current user’s ID for security checks,
37         @param ids: List of Lead to Partner's IDs
38         @param context: A standard dictionary for contextual values
39
40         """
41         return {'type': 'ir.actions.act_window_close'}
42     
43     def action_apply(self, cr, uid, ids, context=None):
44         """
45         This converts lead to opportunity and opens Opportunity view
46         @param self: The object pointer
47         @param cr: the current row, from the database cursor,
48         @param uid: the current user’s ID for security checks,
49         @param ids: List of Lead to Opportunity IDs
50         @param context: A standard dictionary for contextual values
51
52         @return : Dictionary value for created Opportunity form
53         """
54         value = {}
55         record_id = context and context.get('active_id', False) or False
56         if record_id:
57             lead_obj = self.pool.get('crm.lead')
58             opp_obj = self. pool.get('crm.opportunity')
59             data_obj = self.pool.get('ir.model.data')
60             history_obj = self.pool.get('crm.case.history')
61             model_obj = self.pool.get('ir.model')
62
63             # Get Opportunity views
64             result = data_obj._get_id(cr, uid, 'crm', 'view_crm_case_opportunities_filter')
65             res = data_obj.read(cr, uid, result, ['res_id'])
66             id2 = data_obj._get_id(cr, uid, 'crm', 'crm_case_form_view_oppor')
67             id3 = data_obj._get_id(cr, uid, 'crm', 'crm_case_tree_view_oppor')
68             if id2:
69                 id2 = data_obj.browse(cr, uid, id2, context=context).res_id
70             if id3:
71                 id3 = data_obj.browse(cr, uid, id3, context=context).res_id
72
73             lead = lead_obj.browse(cr, uid, record_id, context=context)
74             model_ids = model_obj.search(cr, uid, [('model', '=', 'crm.opportunity')])
75
76
77             for this in self.browse(cr, uid, ids, context=context):
78                 new_opportunity_id = opp_obj.create(cr, uid, {
79                         'name': this.name, 
80                         'planned_revenue': this.planned_revenue, 
81                         'probability': this.probability, 
82                         'partner_id': lead.partner_id and lead.partner_id.id or False , 
83                         'section_id': lead.section_id and lead.section_id.id or False, 
84                         'description': lead.description or False, 
85                         'date_deadline': lead.date_deadline or False, 
86                         'partner_address_id': lead.partner_address_id and \
87                                         lead.partner_address_id.id or False , 
88                         'priority': lead.priority, 
89                         'phone': lead.phone, 
90                         'email_from': lead.email_from
91                     })
92
93                 new_opportunity = opp_obj.browse(cr, uid, new_opportunity_id)
94                 vals = {
95                         'partner_id': this.partner_id and this.partner_id.id or False, 
96                         }
97                 if not lead.opportunity_id:
98                         vals.update({'opportunity_id' : new_opportunity.id})
99
100                 lead_obj.write(cr, uid, [lead.id], vals)
101                 lead_obj.case_close(cr, uid, [lead.id])
102                 
103                 # Copy lead history to opportunity
104                 for his_id in lead.history_line:
105                     history_ids = history_obj.copy(cr, uid, his_id.id, \
106                                                 {'model_id': model_ids[0], \
107                                                 'res_id': new_opportunity_id})
108
109                 opp_obj.case_open(cr, uid, [new_opportunity_id])
110
111             value = {
112                     'name': _('Opportunity'), 
113                     'view_type': 'form', 
114                     'view_mode': 'form,tree', 
115                     'res_model': 'crm.opportunity', 
116                     'res_id': int(new_opportunity_id), 
117                     'view_id': False, 
118                     'views': [(id2, 'form'), (id3, 'tree'), (False, 'calendar'), (False, 'graph')], 
119                     'type': 'ir.actions.act_window', 
120                     'search_view_id': res['res_id']
121                     }
122         return value
123
124     _columns = {
125         'name' : fields.char('Opportunity Summary', size=64, required=True, select=1), 
126         'probability': fields.float('Success Probability'), 
127         'planned_revenue': fields.float('Expected Revenue'), 
128         'partner_id': fields.many2one('res.partner', 'Partner'), 
129     }
130     
131     def view_init(self, cr, uid, fields, context=None):
132         """
133         This function checks for precondition before wizard executes
134         @param self: The object pointer
135         @param cr: the current row, from the database cursor,
136         @param uid: the current user’s ID for security checks,
137         @param fields: List of fields for default value
138         @param context: A standard dictionary for contextual values
139
140         """
141         lead_obj = self.pool.get('crm.lead')
142
143         for lead in lead_obj.browse(cr, uid, context.get('active_ids', [])):
144             if lead.state in ['done', 'cancel']:
145                 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled \
146 Leads Could not convert into Opportunity"))
147             if lead.state != 'open':
148                 raise osv.except_osv(_('Warning !'), _('Lead should be in \
149 \'Open\' state before converting to Opportunity.'))
150         return False
151
152     def default_get(self, cr, uid, fields, context=None):
153         """
154         This function gets default values
155         @param self: The object pointer
156         @param cr: the current row, from the database cursor,
157         @param uid: the current user’s ID for security checks,
158         @param fields: List of fields for default value
159         @param context: A standard dictionary for contextual values
160
161         @return : default values of fields.
162         """
163         lead_obj = self.pool.get('crm.lead')
164         rec_ids = context and context.get('active_ids', [])
165         partner_id = context.get('partner_id', False)
166         data = context and context.get('active_ids', []) or []
167         res = super(crm_lead2opportunity, self).default_get(cr, uid, fields, context=context)
168         for lead in lead_obj.browse(cr, uid, data, context=context):
169             if 'name' in fields:
170                 res.update({'name': lead.partner_name})
171             if 'partner_id' in fields:
172                 res.update({'partner_id': partner_id and partner_id[0] or False})
173         return res
174
175 crm_lead2opportunity()
176
177
178 class crm_lead2opportunity_partner(osv.osv_memory):
179     _name = 'crm.lead2opportunity.partner'
180     _description = 'Lead To Opportunity Partner'
181     _inherit = 'crm.lead2partner'
182
183     _columns = {
184         'partner_id': fields.many2one('res.partner', 'Partner'), 
185         'action': fields.selection([('exist', 'Link to an existing partner'), ('create', 'Create a new partner')], 'Action'), 
186     }
187     
188     def default_get(self, cr, uid, fields, context=None):
189         """
190         This function gets default values
191         @param self: The object pointer
192         @param cr: the current row, from the database cursor,
193         @param uid: the current user’s ID for security checks,
194         @param fields: List of fields for default value
195         @param context: A standard dictionary for contextual values
196
197         @return : default values of fields.
198         """
199         lead_obj = self.pool.get('crm.lead')
200         partner_obj = self.pool.get('res.partner')
201         contact_obj = self.pool.get('res.partner.address')
202         rec_ids = context and context.get('active_ids', [])
203         partner_id = False
204
205         data = context and context.get('active_ids', []) or []
206         res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
207
208         for lead in lead_obj.browse(cr, uid, data, context=context):
209             partner_ids = partner_obj.search(cr, uid, [('name', '=', lead.partner_name or lead.name)])
210             if not partner_ids and lead.email_from:
211                 address_ids = contact_obj.search(cr, uid, [('email', '=', lead.email_from)])
212                 if address_ids:
213                     addresses = contact_obj.browse(cr, uid, address_ids)
214                     partner_ids = addresses and [addresses[0].partner_id.id] or False
215             partner_id = partner_ids and partner_ids[0] or False
216
217             if 'partner_id' in fields:
218                 res.update({'partner_id': partner_id})
219             if 'action' in fields:
220                 res.update({'action': partner_id and 'exist' or 'create'})
221         return res
222     
223     def make_partner(self, cr, uid, ids, context=None):
224         """
225         This function Makes partner based on action.
226         @param self: The object pointer
227         @param cr: the current row, from the database cursor,
228         @param uid: the current user’s ID for security checks,
229         @param ids: List of Lead to Partner's IDs
230         @param context: A standard dictionary for contextual values
231
232         @return : Dictionary value for created Partner form.
233         """
234         if not context:
235             context = {}
236         
237         partner_ids = self._create_partner(cr, uid, ids, context)
238         mod_obj = self.pool.get('ir.model.data')
239         result = mod_obj._get_id(cr, uid, 'base', 'view_res_partner_filter')
240         res = mod_obj.read(cr, uid, result, ['res_id'])
241         value = {}
242         data_obj = self.pool.get('ir.model.data')
243         data_id = data_obj._get_id(cr, uid, 'crm', 'view_crm_lead2opportunity_create')
244         view_id = False
245         if data_id:
246             view_id = data_obj.browse(cr, uid, data_id, context=context).res_id
247         
248         context.update({'partner_id': partner_ids})
249         value = {            
250             'name': _('Create Opportunity'), 
251             'view_type': 'form', 
252             'view_mode': 'form,tree', 
253             'res_model': 'crm.lead2opportunity', 
254             'view_id': False, 
255             'context': context, 
256             'views': [(view_id, 'form')], 
257             'type': 'ir.actions.act_window', 
258             'target': 'new', 
259         }
260         return value
261
262     def action_skip(self, cr, uid, ids, context=None):
263         """
264         This skips partner creation
265         @param self: The object pointer
266         @param cr: the current row, from the database cursor,
267         @param uid: the current user’s ID for security checks,
268         @param ids: List of Lead to Opportunity IDs
269         @param context: A standard dictionary for contextual values
270
271         @return : Dictionary value for Opportunity form
272         """
273         value = {}
274         data_obj = self.pool.get('ir.model.data')
275         data_id = data_obj._get_id(cr, uid, 'crm', 'view_crm_lead2opportunity_create')
276         view_id = False
277         if data_id:
278             view_id = data_obj.browse(cr, uid, data_id, context=context).res_id
279         
280         context.update({'partner_id': False})
281         value = {            
282             'name': _('Create Opportunity'), 
283             'view_type': 'form', 
284             'view_mode': 'form,tree', 
285             'res_model': 'crm.lead2opportunity', 
286             'view_id': False, 
287             'context': context, 
288             'views': [(view_id, 'form')], 
289             'type': 'ir.actions.act_window', 
290             'target': 'new', 
291         }
292         return value
293     
294
295     def view_init(self, cr, uid, fields, context=None):
296         """
297         This function checks for precondition before wizard executes
298         @param self: The object pointer
299         @param cr: the current row, from the database cursor,
300         @param uid: the current user’s ID for security checks,
301         @param fields: List of fields for default value
302         @param context: A standard dictionary for contextual values
303
304         """
305         lead_obj = self.pool.get('crm.lead')
306
307         for lead in lead_obj.browse(cr, uid, context.get('active_ids', [])):
308             if lead.state in ['done', 'cancel']:
309                 raise osv.except_osv(_("Warning !"), _("Closed/Cancelled \
310 Leads Could not convert into Opportunity"))
311             if lead.state != 'open':
312                 raise osv.except_osv(_('Warning !'), _('Lead should be in \
313 \'Open\' state before converting to Opportunity.'))
314         return False
315
316 crm_lead2opportunity_partner()
317
318
319 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: