PageRenderTime 365ms CodeModel.GetById 51ms RepoModel.GetById 17ms app.codeStats 0ms

/addons/crm/wizard/crm_lead_to_opportunity.py

https://gitlab.com/thanhchatvn/cloud-odoo
Python | 265 lines | 212 code | 25 blank | 28 comment | 65 complexity | c7719b1b4844463965506afc3833251e MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from openerp.osv import fields, osv
  4. from openerp.tools.translate import _
  5. import re
  6. from openerp.exceptions import UserError
  7. class crm_lead2opportunity_partner(osv.osv_memory):
  8. _name = 'crm.lead2opportunity.partner'
  9. _description = 'Lead To Opportunity Partner'
  10. _inherit = 'crm.partner.binding'
  11. _columns = {
  12. 'name': fields.selection([
  13. ('convert', 'Convert to opportunity'),
  14. ('merge', 'Merge with existing opportunities')
  15. ], 'Conversion Action', required=True),
  16. 'opportunity_ids': fields.many2many('crm.lead', string='Opportunities'),
  17. 'user_id': fields.many2one('res.users', 'Salesperson', select=True),
  18. 'team_id': fields.many2one('crm.team', 'Sales Team', oldname='section_id', select=True),
  19. }
  20. def onchange_action(self, cr, uid, ids, action, context=None):
  21. return {'value': {'partner_id': False if action != 'exist' else self._find_matching_partner(cr, uid, context=context)}}
  22. def _get_duplicated_leads(self, cr, uid, partner_id, email, include_lost=False, context=None):
  23. """
  24. Search for opportunities that have the same partner and that arent done or cancelled
  25. """
  26. return self.pool.get('crm.lead')._get_duplicated_leads_by_emails(cr, uid, partner_id, email, include_lost=include_lost, context=context)
  27. def default_get(self, cr, uid, fields, context=None):
  28. """
  29. Default get for name, opportunity_ids.
  30. If there is an exisitng partner link to the lead, find all existing
  31. opportunities links with this partner to merge all information together
  32. """
  33. lead_obj = self.pool.get('crm.lead')
  34. res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
  35. if context.get('active_id'):
  36. tomerge = [int(context['active_id'])]
  37. partner_id = res.get('partner_id')
  38. lead = lead_obj.browse(cr, uid, int(context['active_id']), context=context)
  39. email = lead.partner_id and lead.partner_id.email or lead.email_from
  40. tomerge.extend(self._get_duplicated_leads(cr, uid, partner_id, email, include_lost=True, context=context))
  41. tomerge = list(set(tomerge))
  42. if 'action' in fields and not res.get('action'):
  43. res.update({'action' : partner_id and 'exist' or 'create'})
  44. if 'partner_id' in fields:
  45. res.update({'partner_id' : partner_id})
  46. if 'name' in fields:
  47. res.update({'name' : len(tomerge) >= 2 and 'merge' or 'convert'})
  48. if 'opportunity_ids' in fields and len(tomerge) >= 2:
  49. res.update({'opportunity_ids': tomerge})
  50. if lead.user_id:
  51. res.update({'user_id': lead.user_id.id})
  52. if lead.team_id:
  53. res.update({'team_id': lead.team_id.id})
  54. if not partner_id and not lead.contact_name:
  55. res.update({'action': 'nothing'})
  56. return res
  57. def on_change_user(self, cr, uid, ids, user_id, team_id, context=None):
  58. """ When changing the user, also set a team_id or restrict team id
  59. to the ones user_id is member of. """
  60. if user_id:
  61. if team_id:
  62. user_in_team = self.pool.get('crm.team').search(cr, uid, [('id', '=', team_id), '|', ('user_id', '=', user_id), ('member_ids', '=', user_id)], context=context, count=True)
  63. else:
  64. user_in_team = False
  65. if not user_in_team:
  66. result = self.pool['crm.lead'].on_change_user(cr, uid, ids, user_id, context=context)
  67. team_id = result.get('value') and result['value'].get('team_id') and result['value']['team_id'] or False
  68. return {'value': {'team_id': team_id}}
  69. def view_init(self, cr, uid, fields, context=None):
  70. """
  71. Check some preconditions before the wizard executes.
  72. """
  73. if context is None:
  74. context = {}
  75. lead_obj = self.pool.get('crm.lead')
  76. for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
  77. if lead.probability == 100:
  78. raise UserError(_("Closed/Dead leads cannot be converted into opportunities."))
  79. return False
  80. def _convert_opportunity(self, cr, uid, ids, vals, context=None):
  81. if context is None:
  82. context = {}
  83. lead = self.pool.get('crm.lead')
  84. res = False
  85. lead_ids = vals.get('lead_ids', [])
  86. team_id = vals.get('team_id', False)
  87. partner_id = vals.get('partner_id')
  88. data = self.browse(cr, uid, ids, context=context)[0]
  89. leads = lead.browse(cr, uid, lead_ids, context=context)
  90. for lead_id in leads:
  91. partner_id = self._create_partner(cr, uid, lead_id.id, data.action, partner_id or lead_id.partner_id.id, context=context)
  92. res = lead.convert_opportunity(cr, uid, [lead_id.id], partner_id, [], False, context=context)
  93. user_ids = vals.get('user_ids', False)
  94. if context.get('no_force_assignation'):
  95. leads_to_allocate = [lead_id.id for lead_id in leads if not lead_id.user_id]
  96. else:
  97. leads_to_allocate = lead_ids
  98. if user_ids:
  99. lead.allocate_salesman(cr, uid, leads_to_allocate, user_ids, team_id=team_id, context=context)
  100. return res
  101. def action_apply(self, cr, uid, ids, context=None):
  102. """
  103. Convert lead to opportunity or merge lead and opportunity and open
  104. the freshly created opportunity view.
  105. """
  106. if context is None:
  107. context = {}
  108. lead_obj = self.pool['crm.lead']
  109. partner_obj = self.pool['res.partner']
  110. w = self.browse(cr, uid, ids, context=context)[0]
  111. opp_ids = [o.id for o in w.opportunity_ids]
  112. vals = {
  113. 'team_id': w.team_id.id,
  114. }
  115. if w.partner_id:
  116. vals['partner_id'] = w.partner_id.id
  117. if w.name == 'merge':
  118. lead_id = lead_obj.merge_opportunity(cr, uid, opp_ids, context=context)
  119. lead_ids = [lead_id]
  120. lead = lead_obj.read(cr, uid, lead_id, ['type', 'user_id'], context=context)
  121. if lead['type'] == "lead":
  122. context = dict(context, active_ids=lead_ids)
  123. vals.update({'lead_ids': lead_ids, 'user_ids': [w.user_id.id]})
  124. self._convert_opportunity(cr, uid, ids, vals, context=context)
  125. elif not context.get('no_force_assignation') or not lead['user_id']:
  126. vals.update({'user_id': w.user_id.id})
  127. lead_obj.write(cr, uid, lead_id, vals, context=context)
  128. else:
  129. lead_ids = context.get('active_ids', [])
  130. vals.update({'lead_ids': lead_ids, 'user_ids': [w.user_id.id]})
  131. self._convert_opportunity(cr, uid, ids, vals, context=context)
  132. for lead in lead_obj.browse(cr, uid, lead_ids, context=context):
  133. if lead.partner_id and lead.partner_id.user_id != lead.user_id:
  134. partner_obj.write(cr, uid, [lead.partner_id.id], {'user_id': lead.user_id.id}, context=context)
  135. return self.pool.get('crm.lead').redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
  136. def _create_partner(self, cr, uid, lead_id, action, partner_id, context=None):
  137. """
  138. Create partner based on action.
  139. :return dict: dictionary organized as followed: {lead_id: partner_assigned_id}
  140. """
  141. #TODO this method in only called by crm_lead2opportunity_partner
  142. #wizard and would probably diserve to be refactored or at least
  143. #moved to a better place
  144. if context is None:
  145. context = {}
  146. lead = self.pool.get('crm.lead')
  147. if action == 'each_exist_or_create':
  148. ctx = dict(context)
  149. ctx['active_id'] = lead_id
  150. partner_id = self._find_matching_partner(cr, uid, context=ctx)
  151. action = 'create'
  152. res = lead.handle_partner_assignation(cr, uid, [lead_id], action, partner_id, context=context)
  153. return res.get(lead_id)
  154. class crm_lead2opportunity_mass_convert(osv.osv_memory):
  155. _name = 'crm.lead2opportunity.partner.mass'
  156. _description = 'Mass Lead To Opportunity Partner'
  157. _inherit = 'crm.lead2opportunity.partner'
  158. _columns = {
  159. 'user_ids': fields.many2many('res.users', string='Salesmen'),
  160. 'team_id': fields.many2one('crm.team', 'Sales Team', select=True, oldname='section_id'),
  161. 'deduplicate': fields.boolean('Apply deduplication', help='Merge with existing leads/opportunities of each partner'),
  162. 'action': fields.selection([
  163. ('each_exist_or_create', 'Use existing partner or create'),
  164. ('nothing', 'Do not link to a customer')
  165. ], 'Related Customer', required=True),
  166. 'force_assignation': fields.boolean('Force assignation', help='If unchecked, this will leave the salesman of duplicated opportunities'),
  167. }
  168. _defaults = {
  169. 'deduplicate': True,
  170. }
  171. def default_get(self, cr, uid, fields, context=None):
  172. res = super(crm_lead2opportunity_mass_convert, self).default_get(cr, uid, fields, context)
  173. if 'partner_id' in fields:
  174. # avoid forcing the partner of the first lead as default
  175. res['partner_id'] = False
  176. if 'action' in fields:
  177. res['action'] = 'each_exist_or_create'
  178. if 'name' in fields:
  179. res['name'] = 'convert'
  180. if 'opportunity_ids' in fields:
  181. res['opportunity_ids'] = False
  182. return res
  183. def on_change_action(self, cr, uid, ids, action, context=None):
  184. vals = {}
  185. if action != 'exist':
  186. vals = {'value': {'partner_id': False}}
  187. return vals
  188. def on_change_deduplicate(self, cr, uid, ids, deduplicate, context=None):
  189. if context is None:
  190. context = {}
  191. active_leads = self.pool['crm.lead'].browse(cr, uid, context['active_ids'], context=context)
  192. partner_ids = [(lead.partner_id.id, lead.partner_id and lead.partner_id.email or lead.email_from) for lead in active_leads]
  193. partners_duplicated_leads = {}
  194. for partner_id, email in partner_ids:
  195. duplicated_leads = self._get_duplicated_leads(cr, uid, partner_id, email)
  196. if len(duplicated_leads) > 1:
  197. partners_duplicated_leads.setdefault((partner_id, email), []).extend(duplicated_leads)
  198. leads_with_duplicates = []
  199. for lead in active_leads:
  200. lead_tuple = (lead.partner_id.id, lead.partner_id.email if lead.partner_id else lead.email_from)
  201. if len(partners_duplicated_leads.get(lead_tuple, [])) > 1:
  202. leads_with_duplicates.append(lead.id)
  203. return {'value': {'opportunity_ids': leads_with_duplicates}}
  204. def _convert_opportunity(self, cr, uid, ids, vals, context=None):
  205. """
  206. When "massively" (more than one at a time) converting leads to
  207. opportunities, check the salesteam_id and salesmen_ids and update
  208. the values before calling super.
  209. """
  210. if context is None:
  211. context = {}
  212. data = self.browse(cr, uid, ids, context=context)[0]
  213. salesteam_id = data.team_id and data.team_id.id or False
  214. salesmen_ids = []
  215. if data.user_ids:
  216. salesmen_ids = [x.id for x in data.user_ids]
  217. vals.update({'user_ids': salesmen_ids, 'team_id': salesteam_id})
  218. return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
  219. def mass_convert(self, cr, uid, ids, context=None):
  220. data = self.browse(cr, uid, ids, context=context)[0]
  221. ctx = dict(context)
  222. if data.name == 'convert' and data.deduplicate:
  223. merged_lead_ids = []
  224. remaining_lead_ids = []
  225. lead_selected = context.get('active_ids', [])
  226. for lead_id in lead_selected:
  227. if lead_id not in merged_lead_ids:
  228. lead = self.pool['crm.lead'].browse(cr, uid, lead_id, context=context)
  229. duplicated_lead_ids = self._get_duplicated_leads(cr, uid, lead.partner_id.id, lead.partner_id and lead.partner_id.email or lead.email_from)
  230. if len(duplicated_lead_ids) > 1:
  231. lead_id = self.pool.get('crm.lead').merge_opportunity(cr, uid, duplicated_lead_ids, False, False, context=context)
  232. merged_lead_ids.extend(duplicated_lead_ids)
  233. remaining_lead_ids.append(lead_id)
  234. active_ids = set(context.get('active_ids', []))
  235. active_ids = active_ids.difference(merged_lead_ids)
  236. active_ids = active_ids.union(remaining_lead_ids)
  237. ctx['active_ids'] = list(active_ids)
  238. ctx['no_force_assignation'] = context.get('no_force_assignation', not data.force_assignation)
  239. return self.action_apply(cr, uid, ids, context=ctx)