test_reconciliation_matching_rules.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. # -*- coding: utf-8 -*-
  2. from freezegun import freeze_time
  3. from contextlib import contextmanager
  4. from odoo.addons.account.tests.common import AccountTestInvoicingCommon
  5. from odoo.tests.common import Form
  6. from odoo.tests import tagged
  7. from odoo import Command
  8. @tagged('post_install', '-at_install')
  9. class TestReconciliationMatchingRules(AccountTestInvoicingCommon):
  10. @classmethod
  11. def setUpClass(cls, chart_template_ref=None):
  12. super().setUpClass(chart_template_ref=chart_template_ref)
  13. #################
  14. # Company setup #
  15. #################
  16. cls.currency_data_2 = cls.setup_multi_currency_data({
  17. 'name': 'Dark Chocolate Coin',
  18. 'symbol': '🍫',
  19. 'currency_unit_label': 'Dark Choco',
  20. 'currency_subunit_label': 'Dark Cacao Powder',
  21. }, rate2016=10.0, rate2017=20.0)
  22. cls.company = cls.company_data['company']
  23. cls.account_pay = cls.company_data['default_account_payable']
  24. cls.current_assets_account = cls.env['account.account'].search([
  25. ('account_type', '=', 'asset_current'),
  26. ('company_id', '=', cls.company.id)], limit=1)
  27. cls.bank_journal = cls.env['account.journal'].search([('type', '=', 'bank'), ('company_id', '=', cls.company.id)], limit=1)
  28. cls.cash_journal = cls.env['account.journal'].search([('type', '=', 'cash'), ('company_id', '=', cls.company.id)], limit=1)
  29. cls.tax21 = cls.env['account.tax'].create({
  30. 'name': '21%',
  31. 'type_tax_use': 'purchase',
  32. 'amount': 21,
  33. })
  34. cls.tax12 = cls.env['account.tax'].create({
  35. 'name': '12%',
  36. 'type_tax_use': 'purchase',
  37. 'amount': 12,
  38. })
  39. cls.partner_1 = cls.env['res.partner'].create({'name': 'partner_1', 'company_id': cls.company.id})
  40. cls.partner_2 = cls.env['res.partner'].create({'name': 'partner_2', 'company_id': cls.company.id})
  41. cls.partner_3 = cls.env['res.partner'].create({'name': 'partner_3', 'company_id': cls.company.id})
  42. ###############
  43. # Rules setup #
  44. ###############
  45. cls.rule_1 = cls.env['account.reconcile.model'].create({
  46. 'name': 'Invoices Matching Rule',
  47. 'sequence': '1',
  48. 'rule_type': 'invoice_matching',
  49. 'auto_reconcile': False,
  50. 'match_nature': 'both',
  51. 'match_same_currency': True,
  52. 'allow_payment_tolerance': True,
  53. 'payment_tolerance_type': 'percentage',
  54. 'payment_tolerance_param': 0.0,
  55. 'match_partner': True,
  56. 'match_partner_ids': [(6, 0, (cls.partner_1 + cls.partner_2 + cls.partner_3).ids)],
  57. 'company_id': cls.company.id,
  58. 'line_ids': [(0, 0, {'account_id': cls.current_assets_account.id})],
  59. })
  60. cls.rule_2 = cls.env['account.reconcile.model'].create({
  61. 'name': 'write-off model',
  62. 'rule_type': 'writeoff_suggestion',
  63. 'match_partner': True,
  64. 'match_partner_ids': [],
  65. 'line_ids': [(0, 0, {'account_id': cls.current_assets_account.id})],
  66. })
  67. ##################
  68. # Invoices setup #
  69. ##################
  70. cls.invoice_line_1 = cls._create_invoice_line(100, cls.partner_1, 'out_invoice')
  71. cls.invoice_line_2 = cls._create_invoice_line(200, cls.partner_1, 'out_invoice')
  72. cls.invoice_line_3 = cls._create_invoice_line(300, cls.partner_1, 'in_refund', name="RBILL/2019/09/0013")
  73. cls.invoice_line_4 = cls._create_invoice_line(1000, cls.partner_2, 'in_invoice')
  74. cls.invoice_line_5 = cls._create_invoice_line(600, cls.partner_3, 'out_invoice')
  75. cls.invoice_line_6 = cls._create_invoice_line(600, cls.partner_3, 'out_invoice', ref="RF12 3456")
  76. cls.invoice_line_7 = cls._create_invoice_line(200, cls.partner_3, 'out_invoice', pay_reference="RF12 3456")
  77. ####################
  78. # Statements setup #
  79. ####################
  80. # TODO : account_number, partner_name, transaction_type, narration
  81. invoice_number = cls.invoice_line_1.move_id.name
  82. cls.bank_line_1, cls.bank_line_2,\
  83. cls.bank_line_3, cls.bank_line_4,\
  84. cls.bank_line_5, cls.cash_line_1 = cls.env['account.bank.statement.line'].create([
  85. {
  86. 'journal_id': cls.bank_journal.id,
  87. 'date': '2020-01-01',
  88. 'payment_ref': 'invoice %s-%s' % tuple(invoice_number.split('/')[1:]),
  89. 'partner_id': cls.partner_1.id,
  90. 'amount': 100,
  91. 'sequence': 1,
  92. },
  93. {
  94. 'journal_id': cls.bank_journal.id,
  95. 'date': '2020-01-01',
  96. 'payment_ref': 'xxxxx',
  97. 'partner_id': cls.partner_1.id,
  98. 'amount': 600,
  99. 'sequence': 2,
  100. },
  101. {
  102. 'journal_id': cls.bank_journal.id,
  103. 'date': '2020-01-01',
  104. 'payment_ref': 'nawak',
  105. 'narration': 'Communication: RF12 3456',
  106. 'partner_id': cls.partner_3.id,
  107. 'amount': 600,
  108. 'sequence': 1,
  109. },
  110. {
  111. 'journal_id': cls.bank_journal.id,
  112. 'date': '2020-01-01',
  113. 'payment_ref': 'RF12 3456',
  114. 'partner_id': cls.partner_3.id,
  115. 'amount': 600,
  116. 'sequence': 2,
  117. },
  118. {
  119. 'journal_id': cls.bank_journal.id,
  120. 'date': '2020-01-01',
  121. 'payment_ref': 'baaaaah',
  122. 'ref': 'RF12 3456',
  123. 'partner_id': cls.partner_3.id,
  124. 'amount': 600,
  125. 'sequence': 2,
  126. },
  127. {
  128. 'journal_id': cls.cash_journal.id,
  129. 'date': '2020-01-01',
  130. 'payment_ref': 'yyyyy',
  131. 'partner_id': cls.partner_2.id,
  132. 'amount': -1000,
  133. 'sequence': 1,
  134. },
  135. ])
  136. @classmethod
  137. def _create_invoice_line(cls, amount, partner, move_type, currency=None, pay_reference=None, ref=None, name=None, inv_date='2019-09-01'):
  138. ''' Create an invoice on the fly.'''
  139. invoice_form = Form(cls.env['account.move'].with_context(default_move_type=move_type, default_invoice_date=inv_date, default_date=inv_date))
  140. invoice_form.partner_id = partner
  141. if currency:
  142. invoice_form.currency_id = currency
  143. if pay_reference:
  144. invoice_form.payment_reference = pay_reference
  145. if ref:
  146. invoice_form.ref = ref
  147. if name:
  148. invoice_form.name = name
  149. with invoice_form.invoice_line_ids.new() as invoice_line_form:
  150. invoice_line_form.name = 'xxxx'
  151. invoice_line_form.quantity = 1
  152. invoice_line_form.price_unit = amount
  153. invoice_line_form.tax_ids.clear()
  154. invoice = invoice_form.save()
  155. invoice.action_post()
  156. lines = invoice.line_ids
  157. return lines.filtered(lambda l: l.account_id.account_type in ('asset_receivable', 'liability_payable'))
  158. @classmethod
  159. def _create_st_line(cls, amount=1000.0, date='2019-01-01', payment_ref='turlututu', **kwargs):
  160. st_line = cls.env['account.bank.statement.line'].create({
  161. 'journal_id': kwargs.get('journal_id', cls.bank_journal.id),
  162. 'amount': amount,
  163. 'date': date,
  164. 'payment_ref': payment_ref,
  165. 'partner_id': cls.partner_a.id,
  166. **kwargs,
  167. })
  168. return st_line
  169. @classmethod
  170. def _create_reconcile_model(cls, **kwargs):
  171. return cls.env['account.reconcile.model'].create({
  172. 'name': "test",
  173. 'rule_type': 'invoice_matching',
  174. 'allow_payment_tolerance': True,
  175. 'payment_tolerance_type': 'percentage',
  176. 'payment_tolerance_param': 0.0,
  177. **kwargs,
  178. 'line_ids': [
  179. Command.create({
  180. 'account_id': cls.company_data['default_account_revenue'].id,
  181. 'amount_type': 'percentage',
  182. 'label': f"test {i}",
  183. **line_vals,
  184. })
  185. for i, line_vals in enumerate(kwargs.get('line_ids', []))
  186. ],
  187. 'partner_mapping_line_ids': [
  188. Command.create(line_vals)
  189. for i, line_vals in enumerate(kwargs.get('partner_mapping_line_ids', []))
  190. ],
  191. })
  192. @freeze_time('2020-01-01')
  193. def _check_statement_matching(self, rules, expected_values_list):
  194. for statement_line, expected_values in expected_values_list.items():
  195. res = rules._apply_rules(statement_line, statement_line._retrieve_partner())
  196. self.assertDictEqual(res, expected_values)
  197. def test_matching_fields(self):
  198. # Check without restriction.
  199. self._check_statement_matching(self.rule_1, {
  200. self.bank_line_1: {'amls': self.invoice_line_1, 'model': self.rule_1},
  201. self.bank_line_2: {'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3, 'model': self.rule_1},
  202. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  203. })
  204. def test_matching_fields_match_journal_ids(self):
  205. self.rule_1.match_journal_ids |= self.cash_line_1.journal_id
  206. self._check_statement_matching(self.rule_1, {
  207. self.bank_line_1: {},
  208. self.bank_line_2: {},
  209. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  210. })
  211. def test_matching_fields_match_nature(self):
  212. self.rule_1.match_nature = 'amount_received'
  213. self._check_statement_matching(self.rule_1, {
  214. self.bank_line_1: {'amls': self.invoice_line_1, 'model': self.rule_1},
  215. self.bank_line_2: {
  216. 'amls': self.invoice_line_2 + self.invoice_line_3 + self.invoice_line_1,
  217. 'model': self.rule_1,
  218. },
  219. self.cash_line_1: {},
  220. })
  221. self.rule_1.match_nature = 'amount_paid'
  222. self._check_statement_matching(self.rule_1, {
  223. self.bank_line_1: {},
  224. self.bank_line_2: {},
  225. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  226. })
  227. def test_matching_fields_match_amount(self):
  228. self.rule_1.match_amount = 'lower'
  229. self.rule_1.match_amount_max = 150
  230. self._check_statement_matching(self.rule_1, {
  231. self.bank_line_1: {'amls': self.invoice_line_1, 'model': self.rule_1},
  232. self.bank_line_2: {},
  233. self.cash_line_1: {},
  234. })
  235. self.rule_1.match_amount = 'greater'
  236. self.rule_1.match_amount_min = 200
  237. self._check_statement_matching(self.rule_1, {
  238. self.bank_line_1: {},
  239. self.bank_line_2: {'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3, 'model': self.rule_1},
  240. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  241. })
  242. self.rule_1.match_amount = 'between'
  243. self.rule_1.match_amount_min = 200
  244. self.rule_1.match_amount_max = 800
  245. self._check_statement_matching(self.rule_1, {
  246. self.bank_line_1: {},
  247. self.bank_line_2: {'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3, 'model': self.rule_1},
  248. self.cash_line_1: {},
  249. })
  250. def test_matching_fields_match_label(self):
  251. self.rule_1.match_label = 'contains'
  252. self.rule_1.match_label_param = 'yyyyy'
  253. self._check_statement_matching(self.rule_1, {
  254. self.bank_line_1: {},
  255. self.bank_line_2: {},
  256. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  257. })
  258. self.rule_1.match_label = 'not_contains'
  259. self.rule_1.match_label_param = 'xxxxx'
  260. self._check_statement_matching(self.rule_1, {
  261. self.bank_line_1: {'amls': self.invoice_line_1, 'model': self.rule_1},
  262. self.bank_line_2: {},
  263. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  264. })
  265. self.rule_1.match_label = 'match_regex'
  266. self.rule_1.match_label_param = 'xxxxx|yyyyy'
  267. self._check_statement_matching(self.rule_1, {
  268. self.bank_line_1: {},
  269. self.bank_line_2: {'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3, 'model': self.rule_1},
  270. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  271. })
  272. @freeze_time('2019-01-01')
  273. def test_zero_payment_tolerance(self):
  274. rule = self._create_reconcile_model(line_ids=[{}])
  275. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  276. invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, inv_date='2019-01-01')
  277. # Exact matching.
  278. st_line = self._create_st_line(amount=bsl_sign * 1000.0)
  279. self._check_statement_matching(
  280. rule,
  281. {st_line: {'amls': invl, 'model': rule}},
  282. )
  283. # No matching because there is no tolerance.
  284. st_line = self._create_st_line(amount=bsl_sign * 990.0)
  285. self._check_statement_matching(
  286. rule,
  287. {st_line: {}},
  288. )
  289. # The payment amount is higher than the invoice one.
  290. st_line = self._create_st_line(amount=bsl_sign * 1010.0)
  291. self._check_statement_matching(
  292. rule,
  293. {st_line: {'amls': invl, 'model': rule}},
  294. )
  295. @freeze_time('2019-01-01')
  296. def test_zero_payment_tolerance_auto_reconcile(self):
  297. rule = self._create_reconcile_model(
  298. auto_reconcile=True,
  299. line_ids=[{}],
  300. )
  301. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  302. invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, pay_reference='123456', inv_date='2019-01-01')
  303. # No matching because there is no tolerance.
  304. st_line = self._create_st_line(amount=bsl_sign * 990.0)
  305. self._check_statement_matching(
  306. rule,
  307. {st_line: {}},
  308. )
  309. # The payment amount is higher than the invoice one.
  310. st_line = self._create_st_line(amount=bsl_sign * 1010.0, payment_ref='123456')
  311. self._check_statement_matching(
  312. rule,
  313. {st_line: {'amls': invl, 'model': rule, 'auto_reconcile': True}},
  314. )
  315. @freeze_time('2019-01-01')
  316. def test_not_enough_payment_tolerance(self):
  317. rule = self._create_reconcile_model(
  318. payment_tolerance_param=0.5,
  319. line_ids=[{}],
  320. )
  321. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  322. with self.subTest(inv_type=inv_type, bsl_sign=bsl_sign):
  323. invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, inv_date='2019-01-01')
  324. # No matching because there is no enough tolerance.
  325. st_line = self._create_st_line(amount=bsl_sign * 990.0)
  326. self._check_statement_matching(
  327. rule,
  328. {st_line: {}},
  329. )
  330. # The payment amount is higher than the invoice one.
  331. # However, since the invoice amount is lower than the payment amount,
  332. # the tolerance is not checked and the invoice line is matched.
  333. st_line = self._create_st_line(amount=bsl_sign * 1010.0)
  334. self._check_statement_matching(
  335. rule,
  336. {st_line: {'amls': invl, 'model': rule}},
  337. )
  338. @freeze_time('2019-01-01')
  339. def test_enough_payment_tolerance(self):
  340. rule = self._create_reconcile_model(
  341. payment_tolerance_param=1.0,
  342. line_ids=[{}],
  343. )
  344. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  345. invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, inv_date='2019-01-01')
  346. # Enough tolerance to match the invoice line.
  347. st_line = self._create_st_line(amount=bsl_sign * 990.0)
  348. self._check_statement_matching(
  349. rule,
  350. {st_line: {'amls': invl, 'model': rule, 'status': 'write_off'}},
  351. )
  352. # The payment amount is higher than the invoice one.
  353. # However, since the invoice amount is lower than the payment amount,
  354. # the tolerance is not checked and the invoice line is matched.
  355. st_line = self._create_st_line(amount=bsl_sign * 1010.0)
  356. self._check_statement_matching(
  357. rule,
  358. {st_line: {'amls': invl, 'model': rule}},
  359. )
  360. @freeze_time('2019-01-01')
  361. def test_enough_payment_tolerance_auto_reconcile_not_full(self):
  362. rule = self._create_reconcile_model(
  363. payment_tolerance_param=1.0,
  364. auto_reconcile=True,
  365. line_ids=[{'amount_type': 'percentage_st_line', 'amount_string': '200.0'}],
  366. )
  367. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  368. invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, pay_reference='123456', inv_date='2019-01-01')
  369. # Enough tolerance to match the invoice line.
  370. st_line = self._create_st_line(amount=bsl_sign * 990.0, payment_ref='123456')
  371. self._check_statement_matching(
  372. rule,
  373. {st_line: {'amls': invl, 'model': rule, 'status': 'write_off', 'auto_reconcile': True}},
  374. )
  375. @freeze_time('2019-01-01')
  376. def test_allow_payment_tolerance_lower_amount(self):
  377. rule = self._create_reconcile_model(line_ids=[{'amount_type': 'percentage_st_line'}])
  378. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  379. invl = self._create_invoice_line(990.0, self.partner_a, inv_type, inv_date='2019-01-01')
  380. st_line = self._create_st_line(amount=bsl_sign * 1000)
  381. # Partial reconciliation.
  382. self._check_statement_matching(
  383. rule,
  384. {st_line: {'amls': invl, 'model': rule}},
  385. )
  386. @freeze_time('2019-01-01')
  387. def test_enough_payment_tolerance_auto_reconcile(self):
  388. rule = self._create_reconcile_model(
  389. payment_tolerance_param=1.0,
  390. auto_reconcile=True,
  391. line_ids=[{}],
  392. )
  393. for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)):
  394. invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, pay_reference='123456', inv_date='2019-01-01')
  395. # Enough tolerance to match the invoice line.
  396. st_line = self._create_st_line(amount=bsl_sign * 990.0, payment_ref='123456')
  397. self._check_statement_matching(
  398. rule,
  399. {st_line: {
  400. 'amls': invl,
  401. 'model': rule,
  402. 'status': 'write_off',
  403. 'auto_reconcile': True,
  404. }},
  405. )
  406. @freeze_time('2019-01-01')
  407. def test_percentage_st_line_auto_reconcile(self):
  408. rule = self._create_reconcile_model(
  409. payment_tolerance_param=1.0,
  410. rule_type='writeoff_suggestion',
  411. auto_reconcile=True,
  412. line_ids=[
  413. {'amount_type': 'percentage_st_line', 'amount_string': '100.0', 'label': 'A'},
  414. {'amount_type': 'percentage_st_line', 'amount_string': '-100.0', 'label': 'B'},
  415. {'amount_type': 'percentage_st_line', 'amount_string': '100.0', 'label': 'C'},
  416. ],
  417. )
  418. for bsl_sign in (1, -1):
  419. st_line = self._create_st_line(amount=bsl_sign * 1000.0)
  420. self._check_statement_matching(
  421. rule,
  422. {st_line: {
  423. 'model': rule,
  424. 'status': 'write_off',
  425. 'auto_reconcile': True,
  426. }},
  427. )
  428. def test_matching_fields_match_partner_category_ids(self):
  429. test_category = self.env['res.partner.category'].create({'name': 'Consulting Services'})
  430. test_category2 = self.env['res.partner.category'].create({'name': 'Consulting Services2'})
  431. self.partner_2.category_id = test_category + test_category2
  432. self.rule_1.match_partner_category_ids |= test_category
  433. self._check_statement_matching(self.rule_1, {
  434. self.bank_line_1: {},
  435. self.bank_line_2: {},
  436. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  437. })
  438. self.rule_1.match_partner_category_ids = False
  439. def test_mixin_rules(self):
  440. ''' Test usage of rules together.'''
  441. # rule_1 is used before rule_2.
  442. self.rule_1.sequence = 1
  443. self.rule_2.sequence = 2
  444. self._check_statement_matching(self.rule_1 + self.rule_2, {
  445. self.bank_line_1: {
  446. 'amls': self.invoice_line_1,
  447. 'model': self.rule_1,
  448. },
  449. self.bank_line_2: {
  450. 'amls': self.invoice_line_2 + self.invoice_line_3 + self.invoice_line_1,
  451. 'model': self.rule_1,
  452. },
  453. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  454. })
  455. # rule_2 is used before rule_1.
  456. self.rule_1.sequence = 2
  457. self.rule_2.sequence = 1
  458. self._check_statement_matching(self.rule_1 + self.rule_2, {
  459. self.bank_line_1: {'model': self.rule_2, 'auto_reconcile': False, 'status': 'write_off'},
  460. self.bank_line_2: {'model': self.rule_2, 'auto_reconcile': False, 'status': 'write_off'},
  461. self.cash_line_1: {'model': self.rule_2, 'auto_reconcile': False, 'status': 'write_off'},
  462. })
  463. # rule_2 is used before rule_1 but only on partner_1.
  464. self.rule_2.match_partner_ids |= self.partner_1
  465. self._check_statement_matching(self.rule_1 + self.rule_2, {
  466. self.bank_line_1: {'model': self.rule_2, 'auto_reconcile': False, 'status': 'write_off'},
  467. self.bank_line_2: {'model': self.rule_2, 'auto_reconcile': False, 'status': 'write_off'},
  468. self.cash_line_1: {'amls': self.invoice_line_4, 'model': self.rule_1},
  469. })
  470. def test_auto_reconcile(self):
  471. ''' Test auto reconciliation.'''
  472. self.bank_line_1.amount += 5
  473. self.rule_1.sequence = 2
  474. self.rule_1.auto_reconcile = True
  475. self.rule_1.payment_tolerance_param = 10.0
  476. self.rule_2.sequence = 1
  477. self.rule_2.match_partner_ids |= self.partner_2
  478. self.rule_2.auto_reconcile = True
  479. self._check_statement_matching(self.rule_1 + self.rule_2, {
  480. self.bank_line_1: {
  481. 'amls': self.invoice_line_1,
  482. 'model': self.rule_1,
  483. 'auto_reconcile': True,
  484. },
  485. self.bank_line_2: {
  486. 'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3,
  487. 'model': self.rule_1,
  488. },
  489. self.cash_line_1: {
  490. 'model': self.rule_2,
  491. 'status': 'write_off',
  492. 'auto_reconcile': True,
  493. },
  494. })
  495. def test_larger_invoice_auto_reconcile(self):
  496. ''' Test auto reconciliation with an invoice with larger amount than the
  497. statement line's, for rules without write-offs.'''
  498. self.bank_line_1.amount = 40
  499. self.invoice_line_1.move_id.payment_reference = self.bank_line_1.payment_ref
  500. self.rule_1.sequence = 2
  501. self.rule_1.allow_payment_tolerance = False
  502. self.rule_1.auto_reconcile = True
  503. self.rule_1.line_ids = [(5, 0, 0)]
  504. self._check_statement_matching(self.rule_1, {
  505. self.bank_line_1: {
  506. 'amls': self.invoice_line_1,
  507. 'model': self.rule_1,
  508. 'auto_reconcile': True,
  509. },
  510. self.bank_line_2: {
  511. 'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3,
  512. 'model': self.rule_1,
  513. },
  514. })
  515. def test_auto_reconcile_with_tax(self):
  516. ''' Test auto reconciliation with a tax amount included in the bank statement line'''
  517. self.rule_1.write({
  518. 'auto_reconcile': True,
  519. 'rule_type': 'writeoff_suggestion',
  520. 'line_ids': [(1, self.rule_1.line_ids.id, {
  521. 'amount': 50,
  522. 'force_tax_included': True,
  523. 'tax_ids': [(6, 0, self.tax21.ids)],
  524. }), (0, 0, {
  525. 'amount': 100,
  526. 'force_tax_included': False,
  527. 'tax_ids': [(6, 0, self.tax12.ids)],
  528. 'account_id': self.current_assets_account.id,
  529. })]
  530. })
  531. self.bank_line_1.amount = -121
  532. self._check_statement_matching(self.rule_1, {
  533. self.bank_line_1: {'model': self.rule_1, 'status': 'write_off', 'auto_reconcile': True},
  534. self.bank_line_2: {'model': self.rule_1, 'status': 'write_off', 'auto_reconcile': True},
  535. })
  536. def test_auto_reconcile_with_tax_fpos(self):
  537. """ Test the fiscal positions are applied by reconcile models when using taxes.
  538. """
  539. self.rule_1.write({
  540. 'auto_reconcile': True,
  541. 'rule_type': 'writeoff_suggestion',
  542. 'line_ids': [(1, self.rule_1.line_ids.id, {
  543. 'amount': 100,
  544. 'force_tax_included': True,
  545. 'tax_ids': [(6, 0, self.tax21.ids)],
  546. })]
  547. })
  548. self.partner_1.country_id = self.env.ref('base.lu')
  549. belgium = self.env.ref('base.be')
  550. self.partner_2.country_id = belgium
  551. self.bank_line_2.partner_id = self.partner_2
  552. self.bank_line_1.amount = -121
  553. self.bank_line_2.amount = -112
  554. self.env['account.fiscal.position'].create({
  555. 'name': "Test",
  556. 'country_id': belgium.id,
  557. 'auto_apply': True,
  558. 'tax_ids': [
  559. Command.create({
  560. 'tax_src_id': self.tax21.id,
  561. 'tax_dest_id': self.tax12.id,
  562. }),
  563. ]
  564. })
  565. self._check_statement_matching(self.rule_1, {
  566. self.bank_line_1: {'model': self.rule_1, 'status': 'write_off', 'auto_reconcile': True},
  567. self.bank_line_2: {'model': self.rule_1, 'status': 'write_off', 'auto_reconcile': True},
  568. })
  569. def test_reverted_move_matching(self):
  570. partner = self.partner_1
  571. AccountMove = self.env['account.move']
  572. move = AccountMove.create({
  573. 'journal_id': self.bank_journal.id,
  574. 'line_ids': [
  575. (0, 0, {
  576. 'account_id': self.account_pay.id,
  577. 'partner_id': partner.id,
  578. 'name': 'One of these days',
  579. 'debit': 10,
  580. }),
  581. (0, 0, {
  582. 'account_id': self.bank_journal.company_id.account_journal_payment_credit_account_id.id,
  583. 'partner_id': partner.id,
  584. 'name': 'I\'m gonna cut you into little pieces',
  585. 'credit': 10,
  586. })
  587. ],
  588. })
  589. payment_bnk_line = move.line_ids.filtered(lambda l: l.account_id == self.bank_journal.company_id.account_journal_payment_credit_account_id)
  590. move.action_post()
  591. move_reversed = move._reverse_moves()
  592. self.assertTrue(move_reversed.exists())
  593. self.bank_line_1.write({
  594. 'payment_ref': '8',
  595. 'partner_id': partner.id,
  596. 'amount': -10,
  597. })
  598. self._check_statement_matching(self.rule_1, {
  599. self.bank_line_1: {'amls': payment_bnk_line, 'model': self.rule_1},
  600. self.bank_line_2: {
  601. 'amls': self.invoice_line_1 + self.invoice_line_2 + self.invoice_line_3,
  602. 'model': self.rule_1,
  603. },
  604. })
  605. def test_match_different_currencies(self):
  606. partner = self.env['res.partner'].create({'name': 'Bernard Gagnant'})
  607. self.rule_1.write({'match_partner_ids': [(6, 0, partner.ids)], 'match_same_currency': False})
  608. currency_inv = self.env.ref('base.EUR')
  609. currency_inv.active = True
  610. currency_statement = self.env.ref('base.JPY')
  611. currency_statement.active = True
  612. invoice_line = self._create_invoice_line(100, partner, 'out_invoice', currency=currency_inv)
  613. self.bank_line_1.write({'partner_id': partner.id, 'foreign_currency_id': currency_statement.id, 'amount_currency': 100, 'payment_ref': 'test'})
  614. self._check_statement_matching(self.rule_1, {
  615. self.bank_line_1: {'amls': invoice_line, 'model': self.rule_1},
  616. self.bank_line_2: {},
  617. })
  618. def test_invoice_matching_rule_no_partner(self):
  619. """ Tests that a statement line without any partner can be matched to the
  620. right invoice if they have the same payment reference.
  621. """
  622. self.invoice_line_1.move_id.write({'payment_reference': 'Tournicoti66'})
  623. self.rule_1.allow_payment_tolerance = False
  624. self.bank_line_1.write({
  625. 'payment_ref': 'Tournicoti66',
  626. 'partner_id': None,
  627. 'amount': 95,
  628. })
  629. self.rule_1.write({
  630. 'line_ids': [(5, 0, 0)],
  631. 'match_partner': False,
  632. 'match_label': 'contains',
  633. 'match_label_param': 'Tournicoti', # So that we only match what we want to test
  634. })
  635. # TODO: 'invoice_line_1' has no reason to match 'bank_line_1' here... to check
  636. # self._check_statement_matching(self.rule_1, {
  637. # self.bank_line_1: {'amls': self.invoice_line_1, 'model': self.rule_1},
  638. # self.bank_line_2: {'amls': []},
  639. # }, self.bank_st)
  640. def test_inv_matching_rule_auto_rec_no_partner_with_writeoff(self):
  641. self.invoice_line_1.move_id.ref = "doudlidou3555"
  642. self.bank_line_1.write({
  643. 'payment_ref': 'doudlidou3555',
  644. 'partner_id': None,
  645. 'amount': 95,
  646. })
  647. self.rule_1.write({
  648. 'match_partner': False,
  649. 'match_label': 'contains',
  650. 'match_label_param': 'doudlidou', # So that we only match what we want to test
  651. 'payment_tolerance_param': 10.0,
  652. 'auto_reconcile': True,
  653. })
  654. # Check bank reconciliation
  655. self._check_statement_matching(self.rule_1, {
  656. self.bank_line_1: {
  657. 'amls': self.invoice_line_1,
  658. 'model': self.rule_1,
  659. 'status': 'write_off',
  660. 'auto_reconcile': True,
  661. },
  662. self.bank_line_2: {},
  663. })
  664. def test_partner_mapping_rule(self):
  665. st_line = self._create_st_line(partner_id=None, payment_ref=None)
  666. rule = self._create_reconcile_model(
  667. partner_mapping_line_ids=[{
  668. 'partner_id': self.partner_1.id,
  669. 'payment_ref_regex': 'toto.*',
  670. }],
  671. )
  672. # No match because the reference is not matching the regex.
  673. self.assertEqual(st_line._retrieve_partner(), self.env['res.partner'])
  674. st_line.payment_ref = "toto42"
  675. # Matching using the regex on payment_ref.
  676. self.assertEqual(st_line._retrieve_partner(), self.partner_1)
  677. rule.partner_mapping_line_ids.narration_regex = ".*coincoin"
  678. # No match because the narration is not matching the regex.
  679. self.assertEqual(st_line._retrieve_partner(), self.env['res.partner'])
  680. st_line.narration = "42coincoin"
  681. # Matching is back thanks to "coincoin".
  682. self.assertEqual(st_line._retrieve_partner(), self.partner_1)
  683. # More complex matching to match something from bank sync data.
  684. # Note: the indentation is done with multiple \n to mimic the bank sync behavior. Keep them for this test!
  685. rule.partner_mapping_line_ids.narration_regex = ".*coincoin.*"
  686. st_line.narration = """
  687. {
  688. "informations": "coincoin turlututu tsoin tsoin",
  689. }
  690. """
  691. # Same check with json data into the narration field.
  692. self.assertEqual(st_line._retrieve_partner(), self.partner_1)
  693. def test_match_multi_currencies(self):
  694. ''' Ensure the matching of candidates is made using the right statement line currency.
  695. In this test, the value of the statement line is 100 USD = 300 GOL = 900 DAR and we want to match two journal
  696. items of:
  697. - 100 USD = 200 GOL (= 600 DAR from the statement line point of view)
  698. - 14 USD = 280 DAR
  699. Both journal items should be suggested to the user because they represents 98% of the statement line amount
  700. (DAR).
  701. '''
  702. partner = self.env['res.partner'].create({'name': 'Bernard Perdant'})
  703. journal = self.env['account.journal'].create({
  704. 'name': 'test_match_multi_currencies',
  705. 'code': 'xxxx',
  706. 'type': 'bank',
  707. 'currency_id': self.currency_data['currency'].id,
  708. })
  709. matching_rule = self.env['account.reconcile.model'].create({
  710. 'name': 'test_match_multi_currencies',
  711. 'rule_type': 'invoice_matching',
  712. 'match_partner': True,
  713. 'match_partner_ids': [(6, 0, partner.ids)],
  714. 'allow_payment_tolerance': True,
  715. 'payment_tolerance_type': 'percentage',
  716. 'payment_tolerance_param': 5.0,
  717. 'match_same_currency': False,
  718. 'company_id': self.company_data['company'].id,
  719. 'past_months_limit': False,
  720. })
  721. statement_line = self.env['account.bank.statement.line'].create({
  722. 'journal_id': journal.id,
  723. 'date': '2016-01-01',
  724. 'payment_ref': 'line',
  725. 'partner_id': partner.id,
  726. 'foreign_currency_id': self.currency_data_2['currency'].id,
  727. 'amount': 300.0, # Rate is 3 GOL = 1 USD in 2016.
  728. 'amount_currency': 900.0, # Rate is 10 DAR = 1 USD in 2016 but the rate used by the bank is 9:1.
  729. })
  730. move = self.env['account.move'].create({
  731. 'move_type': 'entry',
  732. 'date': '2017-01-01',
  733. 'journal_id': self.company_data['default_journal_misc'].id,
  734. 'line_ids': [
  735. # Rate is 2 GOL = 1 USD in 2017.
  736. # The statement line will consider this line equivalent to 600 DAR.
  737. (0, 0, {
  738. 'account_id': self.company_data['default_account_receivable'].id,
  739. 'partner_id': partner.id,
  740. 'currency_id': self.currency_data['currency'].id,
  741. 'debit': 100.0,
  742. 'credit': 0.0,
  743. 'amount_currency': 200.0,
  744. }),
  745. # Rate is 20 GOL = 1 USD in 2017.
  746. (0, 0, {
  747. 'account_id': self.company_data['default_account_receivable'].id,
  748. 'partner_id': partner.id,
  749. 'currency_id': self.currency_data_2['currency'].id,
  750. 'debit': 14.0,
  751. 'credit': 0.0,
  752. 'amount_currency': 280.0,
  753. }),
  754. # Line to balance the journal entry:
  755. (0, 0, {
  756. 'account_id': self.company_data['default_account_revenue'].id,
  757. 'debit': 0.0,
  758. 'credit': 114.0,
  759. }),
  760. ],
  761. })
  762. move.action_post()
  763. move_line_1 = move.line_ids.filtered(lambda line: line.debit == 100.0)
  764. move_line_2 = move.line_ids.filtered(lambda line: line.debit == 14.0)
  765. self._check_statement_matching(matching_rule, {
  766. statement_line: {'amls': move_line_1 + move_line_2, 'model': matching_rule}
  767. })
  768. @freeze_time('2020-01-01')
  769. def test_matching_with_write_off_foreign_currency(self):
  770. journal_foreign_curr = self.company_data['default_journal_bank'].copy()
  771. journal_foreign_curr.currency_id = self.currency_data['currency']
  772. reco_model = self._create_reconcile_model(
  773. auto_reconcile=True,
  774. rule_type='writeoff_suggestion',
  775. line_ids=[{
  776. 'amount_type': 'percentage',
  777. 'amount': 100.0,
  778. 'account_id': self.company_data['default_account_revenue'].id,
  779. }],
  780. )
  781. st_line = self._create_st_line(amount=100.0, payment_ref='123456', journal_id=journal_foreign_curr.id)
  782. self._check_statement_matching(reco_model, {
  783. st_line: {
  784. 'model': reco_model,
  785. 'status': 'write_off',
  786. 'auto_reconcile': True,
  787. },
  788. })
  789. def test_payment_similar_communications(self):
  790. def create_payment_line(amount, memo, partner):
  791. payment = self.env['account.payment'].create({
  792. 'amount': amount,
  793. 'payment_type': 'inbound',
  794. 'partner_type': 'customer',
  795. 'partner_id': partner.id,
  796. 'ref': memo,
  797. 'destination_account_id': self.company_data['default_account_receivable'].id,
  798. })
  799. payment.action_post()
  800. return payment.line_ids.filtered(lambda x: x.account_id.account_type not in {'asset_receivable', 'liability_payable'})
  801. payment_partner = self.env['res.partner'].create({
  802. 'name': "Bernard Gagnant",
  803. })
  804. self.rule_1.match_partner_ids = [(6, 0, payment_partner.ids)]
  805. pmt_line_1 = create_payment_line(500, 'a1b2c3', payment_partner)
  806. pmt_line_2 = create_payment_line(500, 'a1b2c3', payment_partner)
  807. create_payment_line(500, 'd1e2f3', payment_partner)
  808. self.bank_line_1.write({
  809. 'amount': 1000,
  810. 'payment_ref': 'a1b2c3',
  811. 'partner_id': payment_partner.id,
  812. })
  813. self.bank_line_2.unlink()
  814. self.rule_1.allow_payment_tolerance = False
  815. self._check_statement_matching(self.rule_1, {
  816. self.bank_line_1: {'amls': pmt_line_1 + pmt_line_2, 'model': self.rule_1, 'status': 'write_off'},
  817. })
  818. def test_no_amount_check_keep_first(self):
  819. """ In case the reconciliation model doesn't check the total amount of the candidates,
  820. we still don't want to suggest more than are necessary to match the statement.
  821. For example, if a statement line amounts to 250 and is to be matched with three invoices
  822. of 100, 200 and 300 (retrieved in this order), only 100 and 200 should be proposed.
  823. """
  824. self.rule_1.allow_payment_tolerance = False
  825. self.bank_line_2.amount = 250
  826. self.bank_line_1.partner_id = None
  827. self._check_statement_matching(self.rule_1, {
  828. self.bank_line_1: {},
  829. self.bank_line_2: {
  830. 'amls': self.invoice_line_1 + self.invoice_line_2,
  831. 'model': self.rule_1,
  832. 'status': 'write_off',
  833. },
  834. })
  835. def test_no_amount_check_exact_match(self):
  836. """ If a reconciliation model finds enough candidates for a full reconciliation,
  837. it should still check the following candidates, in case one of them exactly
  838. matches the amount of the statement line. If such a candidate exist, all the
  839. other ones are disregarded.
  840. """
  841. self.rule_1.allow_payment_tolerance = False
  842. self.bank_line_2.amount = 300
  843. self.bank_line_1.partner_id = None
  844. self._check_statement_matching(self.rule_1, {
  845. self.bank_line_1: {},
  846. self.bank_line_2: {
  847. 'amls': self.invoice_line_3,
  848. 'model': self.rule_1,
  849. 'status': 'write_off',
  850. },
  851. })
  852. @freeze_time('2019-01-01')
  853. def test_invoice_matching_using_match_text_location(self):
  854. @contextmanager
  855. def rollback():
  856. savepoint = self.cr.savepoint()
  857. yield
  858. savepoint.rollback()
  859. rule = self._create_reconcile_model(
  860. match_partner=False,
  861. allow_payment_tolerance=False,
  862. match_text_location_label=False,
  863. match_text_location_reference=False,
  864. match_text_location_note=False,
  865. )
  866. st_line = self._create_st_line(amount=1000, partner_id=False)
  867. invoice = self.env['account.move'].create({
  868. 'move_type': 'out_invoice',
  869. 'partner_id': self.partner_a.id,
  870. 'invoice_date': '2019-01-01',
  871. 'invoice_line_ids': [Command.create({
  872. 'product_id': self.product_a.id,
  873. 'price_unit': 100,
  874. })],
  875. })
  876. invoice.action_post()
  877. term_line = invoice.line_ids.filtered(lambda x: x.display_type == 'payment_term')
  878. # No match at all.
  879. self.assertDictEqual(
  880. rule._apply_rules(st_line, None),
  881. {},
  882. )
  883. with rollback():
  884. term_line.name = "1234"
  885. st_line.payment_ref = "1234"
  886. # Matching if no checkbox checked.
  887. self.assertDictEqual(
  888. rule._apply_rules(st_line, None),
  889. {'amls': term_line, 'model': rule},
  890. )
  891. # No matching if other checkbox is checked.
  892. rule.match_text_location_note = True
  893. self.assertDictEqual(
  894. rule._apply_rules(st_line, None),
  895. {},
  896. )
  897. with self.subTest(rule_field='match_text_location_label', st_line_field='payment_ref'):
  898. with rollback():
  899. term_line.name = ''
  900. st_line.payment_ref = '/?'
  901. # No exact matching when the term line name is an empty string
  902. self.assertDictEqual(
  903. rule._apply_rules(st_line, None),
  904. {},
  905. )
  906. for rule_field, st_line_field in (
  907. ('match_text_location_label', 'payment_ref'),
  908. ('match_text_location_reference', 'ref'),
  909. ('match_text_location_note', 'narration'),
  910. ):
  911. with self.subTest(rule_field=rule_field, st_line_field=st_line_field):
  912. with rollback():
  913. rule[rule_field] = True
  914. st_line[st_line_field] = "123456"
  915. term_line.name = "123456"
  916. # Matching if the corresponding flag is enabled.
  917. self.assertDictEqual(
  918. rule._apply_rules(st_line, None),
  919. {'amls': term_line, 'model': rule},
  920. )
  921. # It works also if the statement line contains the word.
  922. st_line[st_line_field] = "payment for 123456 urgent!"
  923. self.assertDictEqual(
  924. rule._apply_rules(st_line, None),
  925. {'amls': term_line, 'model': rule},
  926. )
  927. # Not if the invoice has nothing in common even if numerical.
  928. term_line.name = "78910"
  929. self.assertDictEqual(
  930. rule._apply_rules(st_line, None),
  931. {},
  932. )
  933. # Exact matching on a single word.
  934. st_line[st_line_field] = "TURLUTUTU21"
  935. term_line.name = "TURLUTUTU21"
  936. self.assertDictEqual(
  937. rule._apply_rules(st_line, None),
  938. {'amls': term_line, 'model': rule},
  939. )
  940. # No matching if not enough numerical values.
  941. st_line[st_line_field] = "12"
  942. term_line.name = "selling 3 apples, 2 tomatoes and 12kg of potatoes"
  943. self.assertDictEqual(
  944. rule._apply_rules(st_line, None),
  945. {},
  946. )
  947. invoice2 = self.env['account.move'].create({
  948. 'move_type': 'out_invoice',
  949. 'partner_id': self.partner_a.id,
  950. 'invoice_date': '2019-01-01',
  951. 'invoice_line_ids': [Command.create({
  952. 'product_id': self.product_a.id,
  953. 'price_unit': 100,
  954. })],
  955. })
  956. invoice2.action_post()
  957. term_lines = (invoice + invoice2).line_ids.filtered(lambda x: x.display_type == 'payment_term')
  958. # Matching multiple invoices.
  959. rule.match_text_location_label = True
  960. st_line.payment_ref = "paying invoices 1234 & 5678"
  961. term_lines[0].name = "INV/1234"
  962. term_lines[1].name = "INV/5678"
  963. self.assertDictEqual(
  964. rule._apply_rules(st_line, None),
  965. {'amls': term_lines, 'model': rule},
  966. )
  967. # Matching multiple invoices sharing the same reference.
  968. term_lines[1].name = "INV/1234"
  969. self.assertDictEqual(
  970. rule._apply_rules(st_line, None),
  971. {'amls': term_lines, 'model': rule},
  972. )