[IMP] crm*: update crm modules to new mail module (wip)
[odoo/odoo.git] / addons / crm / wizard / crm_merge_opportunities.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 from osv import osv, fields
22 from tools.translate import _
23
24 class crm_merge_opportunity(osv.osv_memory):
25     """Merge two Opportunities"""
26
27     _name = 'crm.merge.opportunity'
28     _description = 'Merge two Opportunities'
29
30     def _get_first_not_null_id(self, attr, ops, oldest):
31         if hasattr(oldest, attr) and getattr(oldest, attr):
32             return getattr(oldest, attr).id
33         
34         for op in ops:
35             if hasattr(op, attr) and getattr(op, attr):
36                 return getattr(op, attr).id
37         return False
38
39     def _get_first_not_null(self, attr, ops, oldest):
40         if hasattr(oldest, attr) and getattr(oldest, attr):
41             return getattr(oldest, attr)
42         
43         for op in ops:
44             if hasattr(op, attr) and getattr(op, attr):
45                 return getattr(op, attr)
46         return False
47
48     def _concat_all(self, attr, ops):
49         return ', '.join([getattr(op, attr) for op in ops if hasattr(op, attr) and getattr(op, attr)])
50
51
52     def get_attachments(self, cr, uid, id, context=None):
53         attach_obj = self.pool.get('ir.attachment')
54         result = []
55         attach_ids = attach_obj.search(cr, uid, [('res_model' , '=', 'crm.lead'), ('res_id', '=', id)])
56         return attach_ids
57
58     def set_attachements_res_id(self, cr, uid, op_id, attach_ids, context=None):
59         attach_obj = self.pool.get('ir.attachment')
60         attach_obj.write(cr, uid, attach_ids, {'res_id' : op_id})
61
62
63     def find_oldest(self, cr, uid, op_ids, context=None):
64         if not context:
65             context = {}
66         ids = [op_id.id for op_id in op_ids]
67         if context.get('convert'):
68             ids = list(set(ids) - set(context.get('lead_ids', False)) )
69         lead_obj = self.pool.get('crm.lead')
70         op_id = lead_obj.search(cr, uid, [('id', 'in', ids)], order='create_date' , context=context)
71         opps = lead_obj.browse(cr, uid, [op_id[0]], context=context)
72         return opps[0]
73
74     def merge(self, cr, uid, op_ids, context=None):
75         """
76             @param opp_ids : list of opportunities ids to merge
77         """
78         opp_obj = self.pool.get('crm.lead')
79         message_obj = self.pool.get('mail.message')
80
81         lead_ids = context and context.get('lead_ids', []) or []
82
83         if len(op_ids) <= 1:
84             raise osv.except_osv(_('Warning !'),_('Please select more than one opportunities.'))
85
86         opportunities = opp_obj.browse(cr, uid, lead_ids, context=context)
87         opportunities_list = list(set(op_ids) - set(opportunities))
88         oldest_opp = self.find_oldest(cr, uid, op_ids, context=context)
89         if opportunities :
90             first_opportunity = opportunities[0]
91             tail_opportunities = opportunities_list
92         else:
93             first_opportunity = opportunities_list[0]
94             tail_opportunities = opportunities_list[1:]
95             
96
97         data = {
98                 'partner_id': self._get_first_not_null_id('partner_id', op_ids, oldest_opp),  # !!
99                 'title': self._get_first_not_null_id('title', op_ids, oldest_opp),
100                 'name' : self._get_first_not_null('name', op_ids, oldest_opp),  #not lost
101                 'categ_id' : self._get_first_not_null_id('categ_id', op_ids, oldest_opp), # !!
102                 'channel_id' : self._get_first_not_null_id('channel_id', op_ids, oldest_opp), # !!
103                 'city' : self._get_first_not_null('city', op_ids, oldest_opp),  # !!
104                 'company_id' : self._get_first_not_null_id('company_id', op_ids, oldest_opp), #!!
105                 'contact_name' : self._get_first_not_null('contact_name', op_ids, oldest_opp), #not lost
106                 'country_id' : self._get_first_not_null_id('country_id', op_ids, oldest_opp), #!!
107                 'partner_address_id' : self._get_first_not_null_id('partner_address_id', op_ids, oldest_opp), #!!
108                 'partner_assigned_id' : hasattr(opp_obj,'partner_assigned_id') and self._get_first_not_null_id('partner_assigned_id', op_ids, oldest_opp), #!!
109                 'type_id' : self._get_first_not_null_id('type_id', op_ids, oldest_opp), #!!
110                 'user_id' : self._get_first_not_null_id('user_id', op_ids, oldest_opp), #!!
111                 'section_id' : self._get_first_not_null_id('section_id', op_ids, oldest_opp), #!!
112                 'state_id' : self._get_first_not_null_id('state_id', op_ids, oldest_opp),
113                 'description' : self._concat_all('description', op_ids),  #not lost
114                 'email' : self._get_first_not_null('email', op_ids, oldest_opp), # !!
115                 'fax' : self._get_first_not_null('fax', op_ids, oldest_opp),
116                 'mobile' : self._get_first_not_null('mobile', op_ids, oldest_opp),
117                 'partner_latitude' : hasattr(opp_obj,'partner_latitude') and self._get_first_not_null('partner_latitude', op_ids, oldest_opp),
118                 'partner_longitude' : hasattr(opp_obj,'partner_longitude') and self._get_first_not_null('partner_longitude', op_ids, oldest_opp),
119                 'partner_name' : self._get_first_not_null('partner_name', op_ids, oldest_opp),
120                 'phone' : self._get_first_not_null('phone', op_ids, oldest_opp),
121                 'probability' : self._get_first_not_null('probability', op_ids, oldest_opp),
122                 'planned_revenue' : self._get_first_not_null('planned_revenue', op_ids, oldest_opp),
123                 'street' : self._get_first_not_null('street', op_ids, oldest_opp),
124                 'street2' : self._get_first_not_null('street2', op_ids, oldest_opp),
125                 'zip' : self._get_first_not_null('zip', op_ids, oldest_opp),
126                 'state' : 'open',
127                 'create_date' : self._get_first_not_null('create_date', op_ids, oldest_opp),
128                 'date_action_last': self._get_first_not_null('date_action_last', op_ids, oldest_opp),
129                 'date_action_next': self._get_first_not_null('date_action_nexte', op_ids, oldest_opp),
130                 'email_from' : self._get_first_not_null('email_from', op_ids, oldest_opp),
131                 'email_cc' : self._get_first_not_null('email_cc', op_ids, oldest_opp),
132                 'partner_name' : self._get_first_not_null('partner_name', op_ids, oldest_opp),
133
134             }
135
136         #copy message into the first opportunity + merge attachement
137
138         for opp in tail_opportunities + [first_opportunity]:
139             attach_ids = self.get_attachments(cr, uid, opp, context=context)
140             self.set_attachements_res_id(cr, uid, first_opportunity.id, attach_ids)
141             for mail_msg in opp.message_ids:
142                 message_obj.write(cr, uid, mail_msg.id, {'res_id': first_opportunity.id, 'name' : _("From %s : %s") % (opp.name, mail_msg.subject) }, context=context)
143
144         #Notification about loss of information
145         details = []
146         subject = ['Merged opportunities :']
147         for opp in op_ids:
148             subject.append(opp.name)
149             details.append(_('Merged Opportunity: %s\n  Partner: %s\n  Stage: %s\n  Section: %s\n   Salesman: %s\n   Category: %s\n   Channel: %s\n   Company: %s\n   Contact name: %s\n   Email: %s\n   Phone number: %s\n   Fax: %s\n   Mobile: %s\n   State: %s\n   Description: %s\n   Probability: %s\n   Planned revennue: %s\n   Country: %s\n   City: %s\n   Street: %s\n   Street 2: %s\n   Zip 2: %s')  % ( opp.name, opp.partner_id.name or '',
150                         opp.stage_id.name or '',
151                         opp.section_id.name or '',
152                         opp.user_id.name or '',
153                         opp.categ_id.name or '',
154                         opp.channel_id.name or '',
155                         opp.company_id.name or '',
156                         opp.contact_name or '',
157                         opp.email_from or '',
158                         opp.phone or '',
159                         opp.fax or '',
160                         opp.mobile or '',
161                         opp.state_id.name or '',
162                         opp.description or '',
163                         opp.probability or '',
164                         opp.planned_revenue or '',
165                         opp.country_id.name or '',
166                         opp.city or '',
167                         opp.street or '',
168                         opp.street2 or '',
169                         opp.zip or '',
170                         ))
171         subject = subject[0] + ", ".join(subject[1:])
172         details = "\n\n".join(details)
173
174         opp_obj.history(cr, uid, [first_opportunity], subject, body_text=details)
175         #data.update({'message_ids' : [(6, 0 ,self._concat_o2m('message_ids', op_ids))]})
176         opp_obj.write(cr, uid, [first_opportunity.id], data)
177         unlink_ids = map(lambda x: x.id, tail_opportunities)
178         opp_obj.unlink(cr, uid, unlink_ids, context=context)
179
180         models_data = self.pool.get('ir.model.data')
181
182         # Get Opportunity views
183         result = models_data._get_id(
184             cr, uid, 'crm', 'view_crm_case_opportunities_filter')
185         opportunity_view_form = models_data._get_id(
186             cr, uid, 'crm', 'crm_case_form_view_oppor')
187         opportunity_view_tree = models_data._get_id(
188             cr, uid, 'crm', 'crm_case_tree_view_oppor')
189         if opportunity_view_form:
190             opportunity_view_form = models_data.browse(
191                 cr, uid, opportunity_view_form, context=context).res_id
192         if opportunity_view_tree:
193             opportunity_view_tree = models_data.browse(
194                 cr, uid, opportunity_view_tree, context=context).res_id
195
196         return {
197                 'name': _('Opportunity'),
198                 'view_type': 'form',
199                 'view_mode': 'tree, form',
200                 'res_model': 'crm.lead',
201                 'domain': [('type', '=', 'opportunity')],
202                 'res_id': int(first_opportunity.id),
203                 'view_id': False,
204                 'views': [(opportunity_view_form, 'form'),
205                           (opportunity_view_tree, 'tree'),
206                           (False, 'calendar'), (False, 'graph')],
207                 'type': 'ir.actions.act_window',
208         }
209
210
211     def action_merge(self, cr, uid, ids, context=None):
212         obj_opportunity = self.browse(cr, uid, ids[0], context=context)
213         op_ids = obj_opportunity.opportunity_ids
214         self.write(cr, uid, ids, {'opportunity_ids' : [(6,0, [op_ids[0].id])]}, context=context)
215         context['lead_ids'] = [op_ids[0].id]
216         return self.merge(cr, uid, op_ids, context)
217
218     _columns = {
219         'opportunity_ids' : fields.many2many('crm.lead',  'merge_opportunity_rel', 'merge_id', 'opportunity_id', 'Opportunities', domain=[('type', '=', 'opportunity')]),
220     }
221
222     def default_get(self, cr, uid, fields, context=None):
223         """
224         This function gets default values
225         @param self: The object pointer
226         @param cr: the current row, from the database cursor,
227         @param uid: the current user’s ID for security checks,
228         @param fields: List of fields for default value
229         @param context: A standard dictionary for contextual values
230
231         @return : default values of fields.
232         """
233         record_ids = context and context.get('active_ids', False) or False
234         res = super(crm_merge_opportunity, self).default_get(cr, uid, fields, context=context)
235
236         if record_ids:
237             opp_ids = []
238             opps = self.pool.get('crm.lead').browse(cr, uid, record_ids, context=context)
239             for opp in opps:
240                 if opp.state not in ('done', 'cancel'):
241                     opp_ids.append(opp.id)
242             if 'opportunity_ids' in fields:
243                 res.update({'opportunity_ids': opp_ids})
244
245         return res
246
247 crm_merge_opportunity()
248
249 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: