common.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from ast import literal_eval
  4. from contextlib import contextmanager
  5. from unittest.mock import patch
  6. from odoo.addons.crm.models.crm_lead import PARTNER_ADDRESS_FIELDS_TO_SYNC
  7. from odoo.addons.mail.tests.common import MailCase, mail_new_test_user
  8. from odoo.addons.phone_validation.tools import phone_validation
  9. from odoo.addons.sales_team.tests.common import TestSalesCommon
  10. from odoo.fields import Datetime
  11. from odoo import models, tools
  12. INCOMING_EMAIL = """Return-Path: {return_path}
  13. X-Original-To: {to}
  14. Delivered-To: {to}
  15. Received: by mail.my.com (Postfix, from userid xxx)
  16. id 822ECBFB67; Mon, 24 Oct 2011 07:36:51 +0200 (CEST)
  17. X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on mail.my.com
  18. X-Spam-Level:
  19. X-Spam-Status: No, score=-1.0 required=5.0 tests=ALL_TRUSTED autolearn=ham
  20. version=3.3.1
  21. Received: from [192.168.1.146]
  22. (Authenticated sender: {email_from})
  23. by mail.customer.com (Postfix) with ESMTPSA id 07A30BFAB4
  24. for <{to}>; Mon, 24 Oct 2011 07:36:50 +0200 (CEST)
  25. Message-ID: {msg_id}
  26. Date: Mon, 24 Oct 2011 11:06:29 +0530
  27. From: {email_from}
  28. User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.14) Gecko/20110223 Lightning/1.0b2 Thunderbird/3.1.8
  29. MIME-Version: 1.0
  30. To: {to}
  31. Subject: {subject}
  32. Content-Type: text/plain; charset=ISO-8859-1; format=flowed
  33. Content-Transfer-Encoding: 8bit
  34. This is an example email. All sensitive content has been stripped out.
  35. ALL GLORY TO THE HYPNOTOAD !
  36. Cheers,
  37. Somebody."""
  38. class TestCrmCommon(TestSalesCommon, MailCase):
  39. FIELDS_FIRST_SET = [
  40. 'name', 'partner_id', 'campaign_id', 'company_id', 'country_id',
  41. 'team_id', 'state_id', 'stage_id', 'medium_id', 'source_id', 'user_id',
  42. 'title', 'city', 'contact_name', 'mobile', 'partner_name',
  43. 'phone', 'probability', 'expected_revenue', 'street', 'street2', 'zip',
  44. 'create_date', 'date_action_last', 'email_from', 'email_cc', 'website'
  45. ]
  46. merge_fields = ['description', 'type', 'priority']
  47. @classmethod
  48. def setUpClass(cls):
  49. super(TestCrmCommon, cls).setUpClass()
  50. cls._init_mail_gateway()
  51. # Salesmen organization
  52. # ------------------------------------------------------------
  53. # Role: M (team member) R (team manager)
  54. # SALESMAN---------------sales_team_1
  55. # admin------------------M-----------
  56. # user_sales_manager-----R-----------
  57. # user_sales_leads-------M-----------
  58. # user_sales_salesman----/-----------
  59. # Sales teams organization
  60. # ------------------------------------------------------------
  61. # SALESTEAM-----------SEQU-----COMPANY
  62. # sales_team_1--------5--------False
  63. # data----------------9999-----??
  64. cls.sales_team_1.write({
  65. 'alias_name': 'sales.test',
  66. 'use_leads': True,
  67. 'use_opportunities': True,
  68. 'assignment_domain': False,
  69. })
  70. cls.sales_team_1_m1.write({
  71. 'assignment_max': 45,
  72. 'assignment_domain': False,
  73. })
  74. cls.sales_team_1_m2.write({
  75. 'assignment_max': 15,
  76. 'assignment_domain': False,
  77. })
  78. (cls.user_sales_manager + cls.user_sales_leads + cls.user_sales_salesman).write({
  79. 'groups_id': [(4, cls.env.ref('crm.group_use_lead').id)]
  80. })
  81. cls.env['crm.stage'].search([]).write({'sequence': 9999}) # ensure search will find test data first
  82. cls.stage_team1_1 = cls.env['crm.stage'].create({
  83. 'name': 'New',
  84. 'sequence': 1,
  85. 'team_id': cls.sales_team_1.id,
  86. })
  87. cls.stage_team1_2 = cls.env['crm.stage'].create({
  88. 'name': 'Proposition',
  89. 'sequence': 5,
  90. 'team_id': cls.sales_team_1.id,
  91. })
  92. cls.stage_team1_won = cls.env['crm.stage'].create({
  93. 'name': 'Won',
  94. 'sequence': 70,
  95. 'team_id': cls.sales_team_1.id,
  96. 'is_won': True,
  97. })
  98. cls.stage_gen_1 = cls.env['crm.stage'].create({
  99. 'name': 'Generic stage',
  100. 'sequence': 3,
  101. 'team_id': False,
  102. })
  103. cls.stage_gen_won = cls.env['crm.stage'].create({
  104. 'name': 'Generic Won',
  105. 'sequence': 30,
  106. 'team_id': False,
  107. 'is_won': True,
  108. })
  109. # countries and langs
  110. base_us = cls.env.ref('base.us')
  111. cls.env['res.lang']._activate_lang('fr_FR')
  112. cls.env['res.lang']._activate_lang('en_US')
  113. cls.lang_en = cls.env['res.lang']._lang_get('en_US')
  114. cls.lang_fr = cls.env['res.lang']._lang_get('fr_FR')
  115. # leads
  116. cls.lead_1 = cls.env['crm.lead'].create({
  117. 'name': 'Nibbler Spacecraft Request',
  118. 'type': 'lead',
  119. 'user_id': cls.user_sales_leads.id,
  120. 'team_id': cls.sales_team_1.id,
  121. 'partner_id': False,
  122. 'contact_name': 'Amy Wong',
  123. 'email_from': 'amy.wong@test.example.com',
  124. 'lang_id': cls.lang_fr.id,
  125. 'phone': '+1 202 555 9999',
  126. 'country_id': cls.env.ref('base.us').id,
  127. 'probability': 20,
  128. })
  129. # update lead_1: stage_id is not computed anymore by default for leads
  130. cls.lead_1.write({
  131. 'stage_id': cls.stage_team1_1.id,
  132. })
  133. # create an history for new team
  134. cls.lead_team_1_won = cls.env['crm.lead'].create({
  135. 'name': 'Already Won',
  136. 'type': 'lead',
  137. 'user_id': cls.user_sales_leads.id,
  138. 'team_id': cls.sales_team_1.id,
  139. })
  140. cls.lead_team_1_won.action_set_won()
  141. cls.lead_team_1_lost = cls.env['crm.lead'].create({
  142. 'name': 'Already Won',
  143. 'type': 'lead',
  144. 'user_id': cls.user_sales_leads.id,
  145. 'team_id': cls.sales_team_1.id,
  146. })
  147. cls.lead_team_1_lost.action_set_lost()
  148. (cls.lead_team_1_won + cls.lead_team_1_lost).flush_recordset()
  149. # email / phone data
  150. cls.test_email_data = [
  151. '"Planet Express" <planet.express@test.example.com>',
  152. '"Philip, J. Fry" <philip.j.fry@test.example.com>',
  153. '"Turanga Leela" <turanga.leela@test.example.com>',
  154. ]
  155. cls.test_email_data_normalized = [
  156. 'planet.express@test.example.com',
  157. 'philip.j.fry@test.example.com',
  158. 'turanga.leela@test.example.com',
  159. ]
  160. cls.test_phone_data = [
  161. '+1 202 555 0122', # formatted US number
  162. '202 555 0999', # local US number
  163. '202 555 0888', # local US number
  164. ]
  165. cls.test_phone_data_sanitized = [
  166. '+12025550122',
  167. '+12025550999',
  168. '+12025550888',
  169. ]
  170. # create some test contact and companies
  171. cls.contact_company_1 = cls.env['res.partner'].create({
  172. 'name': 'Planet Express',
  173. 'email': cls.test_email_data[0],
  174. 'is_company': True,
  175. 'street': '57th Street',
  176. 'city': 'New New York',
  177. 'country_id': cls.env.ref('base.us').id,
  178. 'zip': '12345',
  179. })
  180. cls.contact_1 = cls.env['res.partner'].create({
  181. 'name': 'Philip J Fry',
  182. 'email': cls.test_email_data[1],
  183. 'mobile': cls.test_phone_data[0],
  184. 'title': cls.env.ref('base.res_partner_title_mister').id,
  185. 'function': 'Delivery Boy',
  186. 'lang': cls.lang_en.code,
  187. 'phone': False,
  188. 'parent_id': cls.contact_company_1.id,
  189. 'is_company': False,
  190. 'street': 'Actually the sewers',
  191. 'city': 'New York',
  192. 'country_id': cls.env.ref('base.us').id,
  193. 'zip': '54321',
  194. })
  195. cls.contact_2 = cls.env['res.partner'].create({
  196. 'name': 'Turanga Leela',
  197. 'email': cls.test_email_data[2],
  198. 'lang': cls.lang_en.code,
  199. 'mobile': cls.test_phone_data[1],
  200. 'phone': cls.test_phone_data[2],
  201. 'parent_id': False,
  202. 'is_company': False,
  203. 'street': 'Cookieville Minimum-Security Orphanarium',
  204. 'city': 'New New York',
  205. 'country_id': cls.env.ref('base.us').id,
  206. 'zip': '97648',
  207. })
  208. cls.contact_company = cls.env['res.partner'].create({
  209. 'name': 'Mom',
  210. 'company_name': 'MomCorp',
  211. 'is_company': True,
  212. 'street': 'Mom Friendly Robot Street',
  213. 'city': 'New new York',
  214. 'country_id': base_us.id,
  215. 'lang': cls.lang_en.code,
  216. 'mobile': '+1 202 555 0888',
  217. 'zip': '87654',
  218. })
  219. # test activities
  220. cls.activity_type_1 = cls.env['mail.activity.type'].create({
  221. 'name': 'Lead Test Activity 1',
  222. 'summary': 'ACT 1 : Presentation, barbecue, ... ',
  223. 'res_model': 'crm.lead',
  224. 'category': 'meeting',
  225. 'delay_count': 5,
  226. })
  227. cls.env['ir.model.data'].create({
  228. 'name': cls.activity_type_1.name.lower().replace(' ', '_'),
  229. 'module': 'crm',
  230. 'model': cls.activity_type_1._name,
  231. 'res_id': cls.activity_type_1.id,
  232. })
  233. def setUp(self):
  234. super(TestCrmCommon, self).setUp()
  235. self.flush_tracking()
  236. @classmethod
  237. def _activate_multi_company(cls):
  238. cls.company_2 = cls.env['res.company'].create({
  239. 'country_id': cls.env.ref('base.au').id,
  240. 'currency_id': cls.env.ref('base.AUD').id,
  241. 'email': 'company.2@test.example.com',
  242. 'name': 'New Test Company',
  243. })
  244. cls.user_sales_manager_mc = mail_new_test_user(
  245. cls.env,
  246. company_id=cls.company_2.id,
  247. company_ids=[(4, cls.company_main.id), (4, cls.company_2.id)],
  248. email='user.sales.manager.mc@test.example.com',
  249. login='user_sales_manager_mc',
  250. groups='sales_team.group_sale_manager,base.group_partner_manager',
  251. name='Myrddin Sales Manager',
  252. notification_type='inbox',
  253. )
  254. cls.team_company2 = cls.env['crm.team'].create({
  255. 'company_id': cls.company_2.id,
  256. 'name': 'C2 Team',
  257. 'sequence': 10,
  258. 'user_id': False,
  259. })
  260. cls.team_company2_m1 = cls.env['crm.team.member'].create({
  261. 'crm_team_id': cls.team_company2.id,
  262. 'user_id': cls.user_sales_manager_mc.id,
  263. 'assignment_max': 30,
  264. 'assignment_domain': False,
  265. })
  266. cls.team_company1 = cls.env['crm.team'].create({
  267. 'company_id': cls.company_main.id,
  268. 'name': 'MainCompany Team',
  269. 'sequence': 50,
  270. 'user_id': cls.user_sales_manager.id,
  271. })
  272. cls.partner_c2 = cls.env['res.partner'].create({
  273. 'company_id': cls.company_2.id,
  274. 'email': '"Partner C2" <partner_c2@multicompany.example.com>',
  275. 'name': 'Customer for C2',
  276. 'phone': '+32455001122',
  277. })
  278. def _create_leads_batch(self, lead_type='lead', count=10, email_dup_count=0,
  279. partner_count=0, partner_ids=None, user_ids=None,
  280. country_ids=None, probabilities=None, suffix=''):
  281. """ Helper tool method creating a batch of leads, useful when dealing
  282. with batch processes. Please update me.
  283. :param string type: 'lead', 'opportunity', 'mixed' (lead then opp),
  284. None (depends on configuration);
  285. :param partner_count: if not partner_ids is given, generate partner count
  286. customers; other leads will have no customer;
  287. :param partner_ids: a set of partner ids to cycle when creating leads;
  288. :param user_ids: a set of user ids to cycle when creating leads;
  289. :return: create leads
  290. """
  291. types = ['lead', 'opportunity']
  292. leads_data = [{
  293. 'name': f'TestLead{suffix}_{x:04d}',
  294. 'type': lead_type if lead_type else types[x % 2],
  295. 'priority': '%s' % (x % 3),
  296. } for x in range(count)]
  297. # generate customer information
  298. partners = []
  299. if partner_count:
  300. partners = self.env['res.partner'].create([{
  301. 'name': 'AutoPartner_%04d' % (x),
  302. 'email': tools.formataddr((
  303. 'AutoPartner_%04d' % (x),
  304. 'partner_email_%04d@example.com' % (x),
  305. )),
  306. } for x in range(partner_count)])
  307. # customer information
  308. if partner_ids:
  309. for idx, lead_data in enumerate(leads_data):
  310. lead_data['partner_id'] = partner_ids[idx % len(partner_ids)]
  311. else:
  312. for idx, lead_data in enumerate(leads_data):
  313. if partner_count and idx < partner_count:
  314. lead_data['partner_id'] = partners[idx].id
  315. else:
  316. lead_data['email_from'] = tools.formataddr((
  317. 'TestCustomer_%02d' % (idx),
  318. 'customer_email_%04d@example.com' % (idx)
  319. ))
  320. # country + phone information
  321. if country_ids:
  322. cid_to_country = dict(
  323. (country.id, country)
  324. for country in self.env['res.country'].browse([cid for cid in country_ids if cid])
  325. )
  326. for idx, lead_data in enumerate(leads_data):
  327. country_id = country_ids[idx % len(country_ids)]
  328. country = cid_to_country.get(country_id, self.env['res.country'])
  329. lead_data['country_id'] = country.id
  330. if lead_data['country_id']:
  331. lead_data['phone'] = phone_validation.phone_format(
  332. '0456%04d99' % (idx),
  333. country.code, country.phone_code,
  334. force_format='E164')
  335. else:
  336. lead_data['phone'] = '+32456%04d99' % (idx)
  337. # salesteam information
  338. if user_ids:
  339. for idx, lead_data in enumerate(leads_data):
  340. lead_data['user_id'] = user_ids[idx % len(user_ids)]
  341. # probabilities
  342. if probabilities:
  343. for idx, lead_data in enumerate(leads_data):
  344. lead_data['probability'] = probabilities[idx % len(probabilities)]
  345. # duplicates (currently only with email)
  346. dups_data = []
  347. if email_dup_count and not partner_ids:
  348. for idx, lead_data in enumerate(leads_data):
  349. if not lead_data.get('partner_id') and lead_data['email_from']:
  350. dup_data = dict(lead_data)
  351. dup_data['name'] = 'Duplicated-%s' % dup_data['name']
  352. dups_data.append(dup_data)
  353. if len(dups_data) >= email_dup_count:
  354. break
  355. return self.env['crm.lead'].create(leads_data + dups_data)
  356. def _create_duplicates(self, lead, create_opp=True):
  357. """ Helper tool method creating, based on a given lead
  358. * a customer (res.partner) based on lead email (to test partner finding)
  359. -> FIXME: using same normalized email does not work currently, only exact email works
  360. * a lead with same email_from
  361. * a lead with same email_normalized (other email_from)
  362. * a lead with customer but another email
  363. * a lost opportunity with same email_from
  364. """
  365. customer = self.env['res.partner'].create({
  366. 'name': 'Lead1 Email Customer',
  367. 'email': lead.email_from,
  368. })
  369. lead_email_from = self.env['crm.lead'].create({
  370. 'name': 'Duplicate: same email_from',
  371. 'type': 'lead',
  372. 'team_id': lead.team_id.id,
  373. 'email_from': lead.email_from,
  374. 'probability': lead.probability,
  375. })
  376. lead_email_normalized = self.env['crm.lead'].create({
  377. 'name': 'Duplicate: email_normalize comparison',
  378. 'type': 'lead',
  379. 'team_id': lead.team_id.id,
  380. 'stage_id': lead.stage_id.id,
  381. 'email_from': 'CUSTOMER WITH NAME <%s>' % lead.email_normalized.upper(),
  382. 'probability': lead.probability,
  383. })
  384. lead_partner = self.env['crm.lead'].create({
  385. 'name': 'Duplicate: customer ID',
  386. 'type': 'lead',
  387. 'team_id': lead.team_id.id,
  388. 'partner_id': customer.id,
  389. 'probability': lead.probability,
  390. })
  391. if create_opp:
  392. opp_lost = self.env['crm.lead'].create({
  393. 'name': 'Duplicate: lost opportunity',
  394. 'type': 'opportunity',
  395. 'team_id': lead.team_id.id,
  396. 'stage_id': lead.stage_id.id,
  397. 'email_from': lead.email_from,
  398. 'probability': lead.probability,
  399. })
  400. opp_lost.action_set_lost()
  401. else:
  402. opp_lost = self.env['crm.lead']
  403. new_leads = lead_email_from + lead_email_normalized + lead_partner + opp_lost
  404. new_leads.flush_recordset() # compute notably probability
  405. return customer, new_leads
  406. @contextmanager
  407. def assertLeadMerged(self, opportunity, leads, **expected):
  408. """ Assert result of lead _merge_opportunity process. This is done using
  409. a context manager in order to save original opportunity (master lead)
  410. values. Indeed those will be modified during merge process. We have to
  411. ensure final values are correct taking into account all leads values
  412. before merging them.
  413. :param opportunity: final opportunity
  414. :param leads: merged leads (including opportunity)
  415. """
  416. self.assertIn(opportunity, leads)
  417. # save opportunity value before being modified by merge process
  418. fields_all = self.FIELDS_FIRST_SET + self.merge_fields
  419. original_opp_values = dict(
  420. (fname, opportunity[fname])
  421. for fname in fields_all
  422. if fname in opportunity
  423. )
  424. def _find_value(lead, fname):
  425. if lead == opportunity:
  426. return original_opp_values[fname]
  427. return lead[fname]
  428. def _first_set(fname):
  429. values = [_find_value(lead, fname) for lead in leads]
  430. return next((value for value in values if value), False)
  431. def _get_type():
  432. values = [_find_value(lead, 'type') for lead in leads]
  433. return 'opportunity' if 'opportunity' in values else 'lead'
  434. def _get_description():
  435. values = [_find_value(lead, 'description') for lead in leads]
  436. return '<br><br>'.join(value for value in values if value)
  437. def _get_priority():
  438. values = [_find_value(lead, 'priority') for lead in leads]
  439. return max(values)
  440. def _aggregate(fname):
  441. if isinstance(self.env['crm.lead'][fname], models.BaseModel):
  442. values = leads.mapped(fname)
  443. else:
  444. values = [_find_value(lead, fname) for lead in leads]
  445. return values
  446. try:
  447. # merge process will modify opportunity
  448. yield
  449. finally:
  450. # support specific values caller may want to check in addition to generic tests
  451. for fname, expected in expected.items():
  452. if expected is False:
  453. self.assertFalse(opportunity[fname], "%s must be False" % fname)
  454. else:
  455. self.assertEqual(opportunity[fname], expected, "%s must be equal to %s" % (fname, expected))
  456. # classic fields: first not void wins or specific computation
  457. for fname in fields_all:
  458. if fname not in opportunity: # not all fields available when doing -u
  459. continue
  460. opp_value = opportunity[fname]
  461. if fname == 'description':
  462. self.assertEqual(opp_value, _get_description())
  463. elif fname == 'type':
  464. self.assertEqual(opp_value, _get_type())
  465. elif fname == 'priority':
  466. self.assertEqual(opp_value, _get_priority())
  467. elif fname in ('order_ids', 'visitor_ids'):
  468. self.assertEqual(opp_value, _aggregate(fname))
  469. elif fname in PARTNER_ADDRESS_FIELDS_TO_SYNC:
  470. # Specific computation, has its own test
  471. continue
  472. else:
  473. self.assertEqual(
  474. opp_value if opp_value or not isinstance(opp_value, models.BaseModel) else False,
  475. _first_set(fname)
  476. )
  477. class TestLeadConvertCommon(TestCrmCommon):
  478. @classmethod
  479. def setUpClass(cls):
  480. super(TestLeadConvertCommon, cls).setUpClass()
  481. # Sales Team organization
  482. # Role: M (team member) R (team manager)
  483. # SALESMAN---------------sales_team_1-----sales_team_convert
  484. # admin------------------M----------------/ (sales_team_1_m2)
  485. # user_sales_manager-----R----------------R
  486. # user_sales_leads-------M----------------/ (sales_team_1_m1)
  487. # user_sales_salesman----/----------------M (sales_team_convert_m1)
  488. # Stages Team organization
  489. # Name-------------------ST-------------------Sequ
  490. # stage_team1_1----------sales_team_1---------1
  491. # stage_team1_2----------sales_team_1---------5
  492. # stage_team1_won--------sales_team_1---------70
  493. # stage_gen_1------------/--------------------3
  494. # stage_gen_won----------/--------------------30
  495. # stage_team_convert_1---sales_team_convert---1
  496. cls.sales_team_convert = cls.env['crm.team'].create({
  497. 'name': 'Convert Sales Team',
  498. 'sequence': 10,
  499. 'alias_name': False,
  500. 'use_leads': True,
  501. 'use_opportunities': True,
  502. 'company_id': False,
  503. 'user_id': cls.user_sales_manager.id,
  504. 'assignment_domain': [('priority', 'in', ['1', '2', '3'])],
  505. })
  506. cls.sales_team_convert_m1 = cls.env['crm.team.member'].create({
  507. 'user_id': cls.user_sales_salesman.id,
  508. 'crm_team_id': cls.sales_team_convert.id,
  509. 'assignment_max': 30,
  510. 'assignment_domain': False,
  511. })
  512. cls.stage_team_convert_1 = cls.env['crm.stage'].create({
  513. 'name': 'New',
  514. 'sequence': 1,
  515. 'team_id': cls.sales_team_convert.id,
  516. })
  517. cls.lead_1.write({'date_open': Datetime.from_string('2020-01-15 11:30:00')})
  518. cls.crm_lead_dt_patcher = patch('odoo.addons.crm.models.crm_lead.fields.Datetime', wraps=Datetime)
  519. cls.crm_lead_dt_mock = cls.startClassPatcher(cls.crm_lead_dt_patcher)
  520. @classmethod
  521. def _switch_to_multi_membership(cls):
  522. # Sales Team organization
  523. # Role: M (team member) R (team manager)
  524. # SALESMAN---------------sales_team_1-----sales_team_convert
  525. # admin------------------M----------------/ (sales_team_1_m2)
  526. # user_sales_manager-----R----------------R+M <-- NEW (sales_team_convert_m2)
  527. # user_sales_leads-------M----------------/ (sales_team_1_m1)
  528. # user_sales_salesman----M----------------M <-- NEW (sales_team_1_m3 / sales_team_convert_m1)
  529. # SALESMAN--------------sales_team----------assign_max
  530. # admin-----------------sales_team_1--------15 (tot: 0.5/day)
  531. # user_sales_manager----sales_team_convert--60 (tot: 2/day)
  532. # user_sales_leads------sales_team_1--------45 (tot: 1.5/day)
  533. # user_sales_salesman---sales_team_1--------15 (tot: 1.5/day)
  534. # user_sales_salesman---sales_team_convert--30
  535. cls.sales_team_1_m1.write({
  536. 'assignment_max': 45,
  537. 'assignment_domain': False,
  538. })
  539. cls.sales_team_1_m2.write({
  540. 'assignment_max': 15,
  541. 'assignment_domain': [('probability', '>=', 10)],
  542. })
  543. cls.env['ir.config_parameter'].set_param('sales_team.membership_multi', True)
  544. cls.sales_team_1_m3 = cls.env['crm.team.member'].create({
  545. 'user_id': cls.user_sales_salesman.id,
  546. 'crm_team_id': cls.sales_team_1.id,
  547. 'assignment_max': 15,
  548. 'assignment_domain': [('probability', '>=', 20)],
  549. })
  550. cls.sales_team_convert_m1.write({
  551. 'assignment_max': 30,
  552. 'assignment_domain': [('probability', '>=', 20)]
  553. })
  554. cls.sales_team_convert_m2 = cls.env['crm.team.member'].create({
  555. 'user_id': cls.user_sales_manager.id,
  556. 'crm_team_id': cls.sales_team_convert.id,
  557. 'assignment_max': 60,
  558. 'assignment_domain': False,
  559. })
  560. @classmethod
  561. def _switch_to_auto_assign(cls):
  562. cls.env['ir.config_parameter'].set_param('crm.lead.auto.assignment', True)
  563. cls.assign_cron = cls.env.ref('crm.ir_cron_crm_lead_assign')
  564. cls.assign_cron.update({
  565. 'active': True,
  566. 'interval_type': 'days',
  567. 'interval_number': 1,
  568. })
  569. def assertMemberAssign(self, member, count):
  570. """ Check assign result and that domains are effectively taken into account """
  571. self.assertEqual(member.lead_month_count, count)
  572. member_leads = self.env['crm.lead'].search(member._get_lead_month_domain())
  573. self.assertEqual(len(member_leads), count)
  574. if member.assignment_domain:
  575. self.assertEqual(
  576. member_leads.filtered_domain(literal_eval(member.assignment_domain)),
  577. member_leads
  578. )
  579. # TODO this condition is not fulfilled in case of merge, need to change merge/assignment process
  580. # if member.crm_team_id.assignment_domain:
  581. # self.assertEqual(
  582. # member_leads.filtered_domain(literal_eval(member.crm_team_id.assignment_domain)),
  583. # member_leads,
  584. # 'Assign domain not matching: %s' % member.crm_team_id.assignment_domain
  585. # )
  586. class TestLeadConvertMassCommon(TestLeadConvertCommon):
  587. @classmethod
  588. def setUpClass(cls):
  589. super(TestLeadConvertMassCommon, cls).setUpClass()
  590. # Sales Team organization
  591. # Role: M (team member) R (team manager)
  592. # SALESMAN-------------------sales_team_1-----sales_team_convert
  593. # admin----------------------M----------------/ (sales_team_1_m2)
  594. # user_sales_manager---------R----------------R (sales_team_1_m1)
  595. # user_sales_leads-----------M----------------/
  596. # user_sales_leads_convert---/----------------M <-- NEW (sales_team_convert_m2)
  597. # user_sales_salesman--------/----------------M (sales_team_convert_m1)
  598. cls.user_sales_leads_convert = mail_new_test_user(
  599. cls.env, login='user_sales_leads_convert',
  600. name='Lucien Sales Leads Convert', email='crm_leads_2@test.example.com',
  601. company_id=cls.env.ref("base.main_company").id,
  602. notification_type='inbox',
  603. groups='sales_team.group_sale_salesman_all_leads,base.group_partner_manager,crm.group_use_lead',
  604. )
  605. cls.sales_team_convert_m2 = cls.env['crm.team.member'].create({
  606. 'user_id': cls.user_sales_leads_convert.id,
  607. 'crm_team_id': cls.sales_team_convert.id,
  608. })
  609. cls.lead_w_partner = cls.env['crm.lead'].create({
  610. 'name': 'New1',
  611. 'type': 'lead',
  612. 'priority': '0',
  613. 'probability': 10,
  614. 'user_id': cls.user_sales_manager.id,
  615. 'stage_id': False,
  616. 'partner_id': cls.contact_1.id,
  617. })
  618. cls.lead_w_partner.write({'stage_id': False})
  619. cls.tags = cls.env['crm.tag'].create([{'name': 'Tag %i' % i} for i in range(4)])
  620. cls.lead_1.tag_ids = cls.tags[:3]
  621. cls.lead_w_partner_company = cls.env['crm.lead'].create({
  622. 'name': 'New1',
  623. 'type': 'lead',
  624. 'probability': 50,
  625. 'user_id': cls.user_sales_manager.id,
  626. 'stage_id': cls.stage_team1_1.id,
  627. 'partner_id': cls.contact_company_1.id,
  628. 'contact_name': 'Hermes Conrad',
  629. 'email_from': 'hermes.conrad@test.example.com',
  630. 'tag_ids': (cls.tags[:2] | cls.tags[3]),
  631. })
  632. cls.lead_w_contact = cls.env['crm.lead'].create({
  633. 'name': 'LeadContact',
  634. 'type': 'lead',
  635. 'probability': 25,
  636. 'contact_name': 'TestContact',
  637. 'user_id': cls.user_sales_salesman.id,
  638. 'stage_id': cls.stage_gen_1.id,
  639. })
  640. cls.lead_w_email = cls.env['crm.lead'].create({
  641. 'name': 'LeadEmailAsContact',
  642. 'type': 'lead',
  643. 'priority': '2',
  644. 'probability': 15,
  645. 'email_from': 'contact.email@test.example.com',
  646. 'user_id': cls.user_sales_salesman.id,
  647. 'stage_id': cls.stage_gen_1.id,
  648. })
  649. cls.lead_w_email_lost = cls.env['crm.lead'].create({
  650. 'name': 'Lost',
  651. 'type': 'lead',
  652. 'probability': 15,
  653. 'email_from': 'strange.from@test.example.com',
  654. 'user_id': cls.user_sales_leads.id,
  655. 'stage_id': cls.stage_team1_2.id,
  656. 'active': False,
  657. })
  658. cls.env.flush_all()