account_payment.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. # -*- coding: utf-8 -*-
  2. from odoo import models, fields, api, _, Command
  3. from odoo.exceptions import UserError, ValidationError
  4. from odoo.tools.misc import format_date, formatLang
  5. class AccountPayment(models.Model):
  6. _name = "account.payment"
  7. _inherits = {'account.move': 'move_id'}
  8. _inherit = ['mail.thread', 'mail.activity.mixin']
  9. _description = "Payments"
  10. _order = "date desc, name desc"
  11. _check_company_auto = True
  12. # == Business fields ==
  13. move_id = fields.Many2one(
  14. comodel_name='account.move',
  15. string='Journal Entry', required=True, readonly=True, ondelete='cascade',
  16. check_company=True)
  17. is_reconciled = fields.Boolean(string="Is Reconciled", store=True,
  18. compute='_compute_reconciliation_status')
  19. is_matched = fields.Boolean(string="Is Matched With a Bank Statement", store=True,
  20. compute='_compute_reconciliation_status')
  21. available_partner_bank_ids = fields.Many2many(
  22. comodel_name='res.partner.bank',
  23. compute='_compute_available_partner_bank_ids',
  24. )
  25. partner_bank_id = fields.Many2one('res.partner.bank', string="Recipient Bank Account",
  26. readonly=False, store=True, tracking=True,
  27. compute='_compute_partner_bank_id',
  28. domain="[('id', 'in', available_partner_bank_ids)]",
  29. check_company=True)
  30. is_internal_transfer = fields.Boolean(string="Internal Transfer",
  31. readonly=False, store=True,
  32. tracking=True,
  33. compute="_compute_is_internal_transfer")
  34. qr_code = fields.Char(string="QR Code URL",
  35. compute="_compute_qr_code")
  36. paired_internal_transfer_payment_id = fields.Many2one('account.payment',
  37. help="When an internal transfer is posted, a paired payment is created. "
  38. "They are cross referenced through this field", copy=False)
  39. # == Payment methods fields ==
  40. payment_method_line_id = fields.Many2one('account.payment.method.line', string='Payment Method',
  41. readonly=False, store=True, copy=False,
  42. compute='_compute_payment_method_line_id',
  43. domain="[('id', 'in', available_payment_method_line_ids)]",
  44. help="Manual: Pay or Get paid by any method outside of Odoo.\n"
  45. "Payment Providers: Each payment provider has its own Payment Method. Request a transaction on/to a card thanks to a payment token saved by the partner when buying or subscribing online.\n"
  46. "Check: Pay bills by check and print it from Odoo.\n"
  47. "Batch Deposit: Collect several customer checks at once generating and submitting a batch deposit to your bank. Module account_batch_payment is necessary.\n"
  48. "SEPA Credit Transfer: Pay in the SEPA zone by submitting a SEPA Credit Transfer file to your bank. Module account_sepa is necessary.\n"
  49. "SEPA Direct Debit: Get paid in the SEPA zone thanks to a mandate your partner will have granted to you. Module account_sepa is necessary.\n")
  50. available_payment_method_line_ids = fields.Many2many('account.payment.method.line',
  51. compute='_compute_payment_method_line_fields')
  52. payment_method_id = fields.Many2one(
  53. related='payment_method_line_id.payment_method_id',
  54. string="Method",
  55. tracking=True,
  56. store=True
  57. )
  58. available_journal_ids = fields.Many2many(
  59. comodel_name='account.journal',
  60. compute='_compute_available_journal_ids'
  61. )
  62. # == Synchronized fields with the account.move.lines ==
  63. amount = fields.Monetary(currency_field='currency_id')
  64. payment_type = fields.Selection([
  65. ('outbound', 'Send'),
  66. ('inbound', 'Receive'),
  67. ], string='Payment Type', default='inbound', required=True, tracking=True)
  68. partner_type = fields.Selection([
  69. ('customer', 'Customer'),
  70. ('supplier', 'Vendor'),
  71. ], default='customer', tracking=True, required=True)
  72. payment_reference = fields.Char(string="Payment Reference", copy=False, tracking=True,
  73. help="Reference of the document used to issue this payment. Eg. check number, file name, etc.")
  74. currency_id = fields.Many2one(
  75. comodel_name='res.currency',
  76. string='Currency',
  77. compute='_compute_currency_id', store=True, readonly=False, precompute=True,
  78. help="The payment's currency.")
  79. partner_id = fields.Many2one(
  80. comodel_name='res.partner',
  81. string="Customer/Vendor",
  82. store=True, readonly=False, ondelete='restrict',
  83. compute='_compute_partner_id',
  84. domain="['|', ('parent_id','=', False), ('is_company','=', True)]",
  85. tracking=True,
  86. check_company=True)
  87. outstanding_account_id = fields.Many2one(
  88. comodel_name='account.account',
  89. string="Outstanding Account",
  90. store=True,
  91. compute='_compute_outstanding_account_id',
  92. check_company=True)
  93. destination_account_id = fields.Many2one(
  94. comodel_name='account.account',
  95. string='Destination Account',
  96. store=True, readonly=False,
  97. compute='_compute_destination_account_id',
  98. domain="[('account_type', 'in', ('asset_receivable', 'liability_payable')), ('company_id', '=', company_id)]",
  99. check_company=True)
  100. destination_journal_id = fields.Many2one(
  101. comodel_name='account.journal',
  102. string='Destination Journal',
  103. domain="[('type', 'in', ('bank','cash')), ('company_id', '=', company_id), ('id', '!=', journal_id)]",
  104. check_company=True,
  105. )
  106. # == Stat buttons ==
  107. reconciled_invoice_ids = fields.Many2many('account.move', string="Reconciled Invoices",
  108. compute='_compute_stat_buttons_from_reconciliation',
  109. help="Invoices whose journal items have been reconciled with these payments.")
  110. reconciled_invoices_count = fields.Integer(string="# Reconciled Invoices",
  111. compute="_compute_stat_buttons_from_reconciliation")
  112. # used to determine label 'invoice' or 'credit note' in view
  113. reconciled_invoices_type = fields.Selection(
  114. [('credit_note', 'Credit Note'), ('invoice', 'Invoice')],
  115. compute='_compute_stat_buttons_from_reconciliation')
  116. reconciled_bill_ids = fields.Many2many('account.move', string="Reconciled Bills",
  117. compute='_compute_stat_buttons_from_reconciliation',
  118. help="Invoices whose journal items have been reconciled with these payments.")
  119. reconciled_bills_count = fields.Integer(string="# Reconciled Bills",
  120. compute="_compute_stat_buttons_from_reconciliation")
  121. reconciled_statement_line_ids = fields.Many2many(
  122. comodel_name='account.bank.statement.line',
  123. string="Reconciled Statement Lines",
  124. compute='_compute_stat_buttons_from_reconciliation',
  125. help="Statements lines matched to this payment",
  126. )
  127. reconciled_statement_lines_count = fields.Integer(
  128. string="# Reconciled Statement Lines",
  129. compute="_compute_stat_buttons_from_reconciliation",
  130. )
  131. # == Display purpose fields ==
  132. payment_method_code = fields.Char(
  133. related='payment_method_line_id.code')
  134. # used to know whether the field `partner_bank_id` needs to be displayed or not in the payments form views
  135. show_partner_bank_account = fields.Boolean(
  136. compute='_compute_show_require_partner_bank')
  137. # used to know whether the field `partner_bank_id` needs to be required or not in the payments form views
  138. require_partner_bank_account = fields.Boolean(
  139. compute='_compute_show_require_partner_bank')
  140. country_code = fields.Char(related='company_id.account_fiscal_country_id.code')
  141. amount_signed = fields.Monetary(
  142. currency_field='currency_id', compute='_compute_amount_signed', tracking=True,
  143. help='Negative value of amount field if payment_type is outbound')
  144. amount_company_currency_signed = fields.Monetary(
  145. currency_field='company_currency_id', compute='_compute_amount_company_currency_signed', store=True)
  146. _sql_constraints = [
  147. (
  148. 'check_amount_not_negative',
  149. 'CHECK(amount >= 0.0)',
  150. "The payment amount cannot be negative.",
  151. ),
  152. ]
  153. # -------------------------------------------------------------------------
  154. # HELPERS
  155. # -------------------------------------------------------------------------
  156. def _seek_for_lines(self):
  157. ''' Helper used to dispatch the journal items between:
  158. - The lines using the temporary liquidity account.
  159. - The lines using the counterpart account.
  160. - The lines being the write-off lines.
  161. :return: (liquidity_lines, counterpart_lines, writeoff_lines)
  162. '''
  163. self.ensure_one()
  164. liquidity_lines = self.env['account.move.line']
  165. counterpart_lines = self.env['account.move.line']
  166. writeoff_lines = self.env['account.move.line']
  167. for line in self.move_id.line_ids:
  168. if line.account_id in self._get_valid_liquidity_accounts():
  169. liquidity_lines += line
  170. elif line.account_id.account_type in ('asset_receivable', 'liability_payable') or line.account_id == self.company_id.transfer_account_id:
  171. counterpart_lines += line
  172. else:
  173. writeoff_lines += line
  174. return liquidity_lines, counterpart_lines, writeoff_lines
  175. def _get_valid_liquidity_accounts(self):
  176. return (
  177. self.journal_id.default_account_id,
  178. self.payment_method_line_id.payment_account_id,
  179. self.journal_id.company_id.account_journal_payment_debit_account_id,
  180. self.journal_id.company_id.account_journal_payment_credit_account_id,
  181. self.journal_id.inbound_payment_method_line_ids.payment_account_id,
  182. self.journal_id.outbound_payment_method_line_ids.payment_account_id,
  183. )
  184. def _get_aml_default_display_map(self):
  185. return {
  186. ('outbound', 'customer'): _("Customer Reimbursement"),
  187. ('inbound', 'customer'): _("Customer Payment"),
  188. ('outbound', 'supplier'): _("Vendor Payment"),
  189. ('inbound', 'supplier'): _("Vendor Reimbursement"),
  190. }
  191. def _get_aml_default_display_name_list(self):
  192. """ Hook allowing custom values when constructing the default label to set on the journal items.
  193. :return: A list of terms to concatenate all together. E.g.
  194. [
  195. ('label', "Vendor Reimbursement"),
  196. ('sep', ' '),
  197. ('amount', "$ 1,555.00"),
  198. ('sep', ' - '),
  199. ('date', "05/14/2020"),
  200. ]
  201. """
  202. self.ensure_one()
  203. display_map = self._get_aml_default_display_map()
  204. values = [
  205. ('label', _("Internal Transfer") if self.is_internal_transfer else display_map[(self.payment_type, self.partner_type)]),
  206. ('sep', ' '),
  207. ('amount', formatLang(self.env, self.amount, currency_obj=self.currency_id)),
  208. ]
  209. if self.partner_id:
  210. values += [
  211. ('sep', ' - '),
  212. ('partner', self.partner_id.display_name),
  213. ]
  214. values += [
  215. ('sep', ' - '),
  216. ('date', format_date(self.env, fields.Date.to_string(self.date))),
  217. ]
  218. return values
  219. def _get_liquidity_aml_display_name_list(self):
  220. """ Hook allowing custom values when constructing the label to set on the liquidity line.
  221. :return: A list of terms to concatenate all together. E.g.
  222. [('reference', "INV/2018/0001")]
  223. """
  224. self.ensure_one()
  225. if self.is_internal_transfer:
  226. if self.payment_type == 'inbound':
  227. return [('transfer_to', _('Transfer to %s', self.journal_id.name))]
  228. else: # payment.payment_type == 'outbound':
  229. return [('transfer_from', _('Transfer from %s', self.journal_id.name))]
  230. elif self.payment_reference:
  231. return [('reference', self.payment_reference)]
  232. else:
  233. return self._get_aml_default_display_name_list()
  234. def _get_counterpart_aml_display_name_list(self):
  235. """ Hook allowing custom values when constructing the label to set on the counterpart line.
  236. :return: A list of terms to concatenate all together. E.g.
  237. [('reference', "INV/2018/0001")]
  238. """
  239. self.ensure_one()
  240. if self.payment_reference:
  241. return [('reference', self.payment_reference)]
  242. else:
  243. return self._get_aml_default_display_name_list()
  244. def _prepare_move_line_default_vals(self, write_off_line_vals=None):
  245. ''' Prepare the dictionary to create the default account.move.lines for the current payment.
  246. :param write_off_line_vals: Optional list of dictionaries to create a write-off account.move.line easily containing:
  247. * amount: The amount to be added to the counterpart amount.
  248. * name: The label to set on the line.
  249. * account_id: The account on which create the write-off.
  250. :return: A list of python dictionary to be passed to the account.move.line's 'create' method.
  251. '''
  252. self.ensure_one()
  253. write_off_line_vals = write_off_line_vals or {}
  254. if not self.outstanding_account_id:
  255. raise UserError(_(
  256. "You can't create a new payment without an outstanding payments/receipts account set either on the company or the %s payment method in the %s journal.",
  257. self.payment_method_line_id.name, self.journal_id.display_name))
  258. # Compute amounts.
  259. write_off_line_vals_list = write_off_line_vals or []
  260. write_off_amount_currency = sum(x['amount_currency'] for x in write_off_line_vals_list)
  261. write_off_balance = sum(x['balance'] for x in write_off_line_vals_list)
  262. if self.payment_type == 'inbound':
  263. # Receive money.
  264. liquidity_amount_currency = self.amount
  265. elif self.payment_type == 'outbound':
  266. # Send money.
  267. liquidity_amount_currency = -self.amount
  268. else:
  269. liquidity_amount_currency = 0.0
  270. liquidity_balance = self.currency_id._convert(
  271. liquidity_amount_currency,
  272. self.company_id.currency_id,
  273. self.company_id,
  274. self.date,
  275. )
  276. counterpart_amount_currency = -liquidity_amount_currency - write_off_amount_currency
  277. counterpart_balance = -liquidity_balance - write_off_balance
  278. currency_id = self.currency_id.id
  279. # Compute a default label to set on the journal items.
  280. liquidity_line_name = ''.join(x[1] for x in self._get_liquidity_aml_display_name_list())
  281. counterpart_line_name = ''.join(x[1] for x in self._get_counterpart_aml_display_name_list())
  282. line_vals_list = [
  283. # Liquidity line.
  284. {
  285. 'name': liquidity_line_name,
  286. 'date_maturity': self.date,
  287. 'amount_currency': liquidity_amount_currency,
  288. 'currency_id': currency_id,
  289. 'debit': liquidity_balance if liquidity_balance > 0.0 else 0.0,
  290. 'credit': -liquidity_balance if liquidity_balance < 0.0 else 0.0,
  291. 'partner_id': self.partner_id.id,
  292. 'account_id': self.outstanding_account_id.id,
  293. },
  294. # Receivable / Payable.
  295. {
  296. 'name': counterpart_line_name,
  297. 'date_maturity': self.date,
  298. 'amount_currency': counterpart_amount_currency,
  299. 'currency_id': currency_id,
  300. 'debit': counterpart_balance if counterpart_balance > 0.0 else 0.0,
  301. 'credit': -counterpart_balance if counterpart_balance < 0.0 else 0.0,
  302. 'partner_id': self.partner_id.id,
  303. 'account_id': self.destination_account_id.id,
  304. },
  305. ]
  306. return line_vals_list + write_off_line_vals_list
  307. # -------------------------------------------------------------------------
  308. # COMPUTE METHODS
  309. # -------------------------------------------------------------------------
  310. @api.depends('move_id.line_ids.amount_residual', 'move_id.line_ids.amount_residual_currency', 'move_id.line_ids.account_id')
  311. def _compute_reconciliation_status(self):
  312. ''' Compute the field indicating if the payments are already reconciled with something.
  313. This field is used for display purpose (e.g. display the 'reconcile' button redirecting to the reconciliation
  314. widget).
  315. '''
  316. for pay in self:
  317. liquidity_lines, counterpart_lines, writeoff_lines = pay._seek_for_lines()
  318. if not pay.currency_id or not pay.id:
  319. pay.is_reconciled = False
  320. pay.is_matched = False
  321. elif pay.currency_id.is_zero(pay.amount):
  322. pay.is_reconciled = True
  323. pay.is_matched = True
  324. else:
  325. residual_field = 'amount_residual' if pay.currency_id == pay.company_id.currency_id else 'amount_residual_currency'
  326. if pay.journal_id.default_account_id and pay.journal_id.default_account_id in liquidity_lines.account_id:
  327. # Allow user managing payments without any statement lines by using the bank account directly.
  328. # In that case, the user manages transactions only using the register payment wizard.
  329. pay.is_matched = True
  330. else:
  331. pay.is_matched = pay.currency_id.is_zero(sum(liquidity_lines.mapped(residual_field)))
  332. reconcile_lines = (counterpart_lines + writeoff_lines).filtered(lambda line: line.account_id.reconcile)
  333. pay.is_reconciled = pay.currency_id.is_zero(sum(reconcile_lines.mapped(residual_field)))
  334. @api.model
  335. def _get_method_codes_using_bank_account(self):
  336. return ['manual']
  337. @api.model
  338. def _get_method_codes_needing_bank_account(self):
  339. return []
  340. @api.depends('payment_method_code')
  341. def _compute_show_require_partner_bank(self):
  342. """ Computes if the destination bank account must be displayed in the payment form view. By default, it
  343. won't be displayed but some modules might change that, depending on the payment type."""
  344. for payment in self:
  345. if payment.journal_id.type == 'cash':
  346. payment.show_partner_bank_account = False
  347. else:
  348. payment.show_partner_bank_account = payment.payment_method_code in self._get_method_codes_using_bank_account()
  349. payment.require_partner_bank_account = payment.state == 'draft' and payment.payment_method_code in self._get_method_codes_needing_bank_account()
  350. @api.depends('amount_total_signed', 'payment_type')
  351. def _compute_amount_company_currency_signed(self):
  352. for payment in self:
  353. liquidity_lines = payment._seek_for_lines()[0]
  354. payment.amount_company_currency_signed = sum(liquidity_lines.mapped('balance'))
  355. @api.depends('amount', 'payment_type')
  356. def _compute_amount_signed(self):
  357. for payment in self:
  358. if payment.payment_type == 'outbound':
  359. payment.amount_signed = -payment.amount
  360. else:
  361. payment.amount_signed = payment.amount
  362. @api.depends('partner_id', 'company_id', 'payment_type', 'destination_journal_id', 'is_internal_transfer')
  363. def _compute_available_partner_bank_ids(self):
  364. for pay in self:
  365. if pay.payment_type == 'inbound':
  366. pay.available_partner_bank_ids = pay.journal_id.bank_account_id
  367. elif pay.is_internal_transfer:
  368. pay.available_partner_bank_ids = pay.destination_journal_id.bank_account_id
  369. else:
  370. pay.available_partner_bank_ids = pay.partner_id.bank_ids\
  371. .filtered(lambda x: x.company_id.id in (False, pay.company_id.id))._origin
  372. @api.depends('available_partner_bank_ids', 'journal_id')
  373. def _compute_partner_bank_id(self):
  374. ''' The default partner_bank_id will be the first available on the partner. '''
  375. for pay in self:
  376. pay.partner_bank_id = pay.available_partner_bank_ids[:1]._origin
  377. @api.depends('partner_id', 'journal_id', 'destination_journal_id')
  378. def _compute_is_internal_transfer(self):
  379. for payment in self:
  380. payment.is_internal_transfer = payment.partner_id \
  381. and payment.partner_id == payment.journal_id.company_id.partner_id \
  382. and payment.destination_journal_id
  383. @api.depends('available_payment_method_line_ids')
  384. def _compute_payment_method_line_id(self):
  385. ''' Compute the 'payment_method_line_id' field.
  386. This field is not computed in '_compute_payment_method_line_fields' because it's a stored editable one.
  387. '''
  388. for pay in self:
  389. available_payment_method_lines = pay.available_payment_method_line_ids
  390. # Select the first available one by default.
  391. if pay.payment_method_line_id in available_payment_method_lines:
  392. pay.payment_method_line_id = pay.payment_method_line_id
  393. elif available_payment_method_lines:
  394. pay.payment_method_line_id = available_payment_method_lines[0]._origin
  395. else:
  396. pay.payment_method_line_id = False
  397. @api.depends('payment_type', 'journal_id', 'currency_id')
  398. def _compute_payment_method_line_fields(self):
  399. for pay in self:
  400. pay.available_payment_method_line_ids = pay.journal_id._get_available_payment_method_lines(pay.payment_type)
  401. to_exclude = pay._get_payment_method_codes_to_exclude()
  402. if to_exclude:
  403. pay.available_payment_method_line_ids = pay.available_payment_method_line_ids.filtered(lambda x: x.code not in to_exclude)
  404. @api.depends('payment_type')
  405. def _compute_available_journal_ids(self):
  406. """
  407. Get all journals having at least one payment method for inbound/outbound depending on the payment_type.
  408. """
  409. journals = self.env['account.journal'].search([
  410. ('company_id', 'in', self.company_id.ids), ('type', 'in', ('bank', 'cash'))
  411. ])
  412. for pay in self:
  413. if pay.payment_type == 'inbound':
  414. pay.available_journal_ids = journals.filtered(
  415. lambda j: j.company_id == pay.company_id and j.inbound_payment_method_line_ids.ids != []
  416. )
  417. else:
  418. pay.available_journal_ids = journals.filtered(
  419. lambda j: j.company_id == pay.company_id and j.outbound_payment_method_line_ids.ids != []
  420. )
  421. def _get_payment_method_codes_to_exclude(self):
  422. # can be overriden to exclude payment methods based on the payment characteristics
  423. self.ensure_one()
  424. return []
  425. @api.depends('journal_id')
  426. def _compute_currency_id(self):
  427. for pay in self:
  428. pay.currency_id = pay.journal_id.currency_id or pay.journal_id.company_id.currency_id
  429. @api.depends('is_internal_transfer')
  430. def _compute_partner_id(self):
  431. for pay in self:
  432. if pay.is_internal_transfer:
  433. pay.partner_id = pay.journal_id.company_id.partner_id
  434. elif pay.partner_id == pay.journal_id.company_id.partner_id:
  435. pay.partner_id = False
  436. else:
  437. pay.partner_id = pay.partner_id
  438. @api.depends('journal_id', 'payment_type', 'payment_method_line_id')
  439. def _compute_outstanding_account_id(self):
  440. for pay in self:
  441. if pay.payment_type == 'inbound':
  442. pay.outstanding_account_id = (pay.payment_method_line_id.payment_account_id
  443. or pay.journal_id.company_id.account_journal_payment_debit_account_id)
  444. elif pay.payment_type == 'outbound':
  445. pay.outstanding_account_id = (pay.payment_method_line_id.payment_account_id
  446. or pay.journal_id.company_id.account_journal_payment_credit_account_id)
  447. else:
  448. pay.outstanding_account_id = False
  449. @api.depends('journal_id', 'partner_id', 'partner_type', 'is_internal_transfer', 'destination_journal_id')
  450. def _compute_destination_account_id(self):
  451. self.destination_account_id = False
  452. for pay in self:
  453. if pay.is_internal_transfer:
  454. pay.destination_account_id = pay.destination_journal_id.company_id.transfer_account_id
  455. elif pay.partner_type == 'customer':
  456. # Receive money from invoice or send money to refund it.
  457. if pay.partner_id:
  458. pay.destination_account_id = pay.partner_id.with_company(pay.company_id).property_account_receivable_id
  459. else:
  460. pay.destination_account_id = self.env['account.account'].search([
  461. ('company_id', '=', pay.company_id.id),
  462. ('account_type', '=', 'asset_receivable'),
  463. ('deprecated', '=', False),
  464. ], limit=1)
  465. elif pay.partner_type == 'supplier':
  466. # Send money to pay a bill or receive money to refund it.
  467. if pay.partner_id:
  468. pay.destination_account_id = pay.partner_id.with_company(pay.company_id).property_account_payable_id
  469. else:
  470. pay.destination_account_id = self.env['account.account'].search([
  471. ('company_id', '=', pay.company_id.id),
  472. ('account_type', '=', 'liability_payable'),
  473. ('deprecated', '=', False),
  474. ], limit=1)
  475. @api.depends('partner_bank_id', 'amount', 'ref', 'currency_id', 'journal_id', 'move_id.state',
  476. 'payment_method_line_id', 'payment_type')
  477. def _compute_qr_code(self):
  478. for pay in self:
  479. if pay.state in ('draft', 'posted') \
  480. and pay.partner_bank_id \
  481. and pay.payment_method_line_id.code == 'manual' \
  482. and pay.payment_type == 'outbound' \
  483. and pay.currency_id:
  484. if pay.partner_bank_id:
  485. qr_code = pay.partner_bank_id.build_qr_code_base64(pay.amount, pay.ref, pay.ref, pay.currency_id, pay.partner_id)
  486. else:
  487. qr_code = None
  488. if qr_code:
  489. pay.qr_code = '''
  490. <br/>
  491. <img class="border border-dark rounded" src="{qr_code}"/>
  492. <br/>
  493. <strong class="text-center">{txt}</strong>
  494. '''.format(txt = _('Scan me with your banking app.'),
  495. qr_code = qr_code)
  496. continue
  497. pay.qr_code = None
  498. @api.depends('move_id.line_ids.matched_debit_ids', 'move_id.line_ids.matched_credit_ids')
  499. def _compute_stat_buttons_from_reconciliation(self):
  500. ''' Retrieve the invoices reconciled to the payments through the reconciliation (account.partial.reconcile). '''
  501. stored_payments = self.filtered('id')
  502. if not stored_payments:
  503. self.reconciled_invoice_ids = False
  504. self.reconciled_invoices_count = 0
  505. self.reconciled_invoices_type = ''
  506. self.reconciled_bill_ids = False
  507. self.reconciled_bills_count = 0
  508. self.reconciled_statement_line_ids = False
  509. self.reconciled_statement_lines_count = 0
  510. return
  511. self.env['account.payment'].flush_model(fnames=['move_id', 'outstanding_account_id'])
  512. self.env['account.move'].flush_model(fnames=['move_type', 'payment_id', 'statement_line_id'])
  513. self.env['account.move.line'].flush_model(fnames=['move_id', 'account_id', 'statement_line_id'])
  514. self.env['account.partial.reconcile'].flush_model(fnames=['debit_move_id', 'credit_move_id'])
  515. self._cr.execute('''
  516. SELECT
  517. payment.id,
  518. ARRAY_AGG(DISTINCT invoice.id) AS invoice_ids,
  519. invoice.move_type
  520. FROM account_payment payment
  521. JOIN account_move move ON move.id = payment.move_id
  522. JOIN account_move_line line ON line.move_id = move.id
  523. JOIN account_partial_reconcile part ON
  524. part.debit_move_id = line.id
  525. OR
  526. part.credit_move_id = line.id
  527. JOIN account_move_line counterpart_line ON
  528. part.debit_move_id = counterpart_line.id
  529. OR
  530. part.credit_move_id = counterpart_line.id
  531. JOIN account_move invoice ON invoice.id = counterpart_line.move_id
  532. JOIN account_account account ON account.id = line.account_id
  533. WHERE account.account_type IN ('asset_receivable', 'liability_payable')
  534. AND payment.id IN %(payment_ids)s
  535. AND line.id != counterpart_line.id
  536. AND invoice.move_type in ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt')
  537. GROUP BY payment.id, invoice.move_type
  538. ''', {
  539. 'payment_ids': tuple(stored_payments.ids)
  540. })
  541. query_res = self._cr.dictfetchall()
  542. self.reconciled_invoice_ids = self.reconciled_invoices_count = False
  543. self.reconciled_bill_ids = self.reconciled_bills_count = False
  544. for res in query_res:
  545. pay = self.browse(res['id'])
  546. if res['move_type'] in self.env['account.move'].get_sale_types(True):
  547. pay.reconciled_invoice_ids += self.env['account.move'].browse(res.get('invoice_ids', []))
  548. pay.reconciled_invoices_count = len(res.get('invoice_ids', []))
  549. else:
  550. pay.reconciled_bill_ids += self.env['account.move'].browse(res.get('invoice_ids', []))
  551. pay.reconciled_bills_count = len(res.get('invoice_ids', []))
  552. self._cr.execute('''
  553. SELECT
  554. payment.id,
  555. ARRAY_AGG(DISTINCT counterpart_line.statement_line_id) AS statement_line_ids
  556. FROM account_payment payment
  557. JOIN account_move move ON move.id = payment.move_id
  558. JOIN account_move_line line ON line.move_id = move.id
  559. JOIN account_account account ON account.id = line.account_id
  560. JOIN account_partial_reconcile part ON
  561. part.debit_move_id = line.id
  562. OR
  563. part.credit_move_id = line.id
  564. JOIN account_move_line counterpart_line ON
  565. part.debit_move_id = counterpart_line.id
  566. OR
  567. part.credit_move_id = counterpart_line.id
  568. WHERE account.id = payment.outstanding_account_id
  569. AND payment.id IN %(payment_ids)s
  570. AND line.id != counterpart_line.id
  571. AND counterpart_line.statement_line_id IS NOT NULL
  572. GROUP BY payment.id
  573. ''', {
  574. 'payment_ids': tuple(stored_payments.ids)
  575. })
  576. query_res = dict((payment_id, statement_line_ids) for payment_id, statement_line_ids in self._cr.fetchall())
  577. for pay in self:
  578. statement_line_ids = query_res.get(pay.id, [])
  579. pay.reconciled_statement_line_ids = [Command.set(statement_line_ids)]
  580. pay.reconciled_statement_lines_count = len(statement_line_ids)
  581. if len(pay.reconciled_invoice_ids.mapped('move_type')) == 1 and pay.reconciled_invoice_ids[0].move_type == 'out_refund':
  582. pay.reconciled_invoices_type = 'credit_note'
  583. else:
  584. pay.reconciled_invoices_type = 'invoice'
  585. # -------------------------------------------------------------------------
  586. # ONCHANGE METHODS
  587. # -------------------------------------------------------------------------
  588. @api.onchange('posted_before', 'state', 'journal_id', 'date')
  589. def _onchange_journal_date(self):
  590. # Before the record is created, the move_id doesn't exist yet, and the name will not be
  591. # recomputed correctly if we change the journal or the date, leading to inconsitencies
  592. if not self.move_id:
  593. self.name = False
  594. # -------------------------------------------------------------------------
  595. # CONSTRAINT METHODS
  596. # -------------------------------------------------------------------------
  597. @api.constrains('payment_method_line_id')
  598. def _check_payment_method_line_id(self):
  599. ''' Ensure the 'payment_method_line_id' field is not null.
  600. Can't be done using the regular 'required=True' because the field is a computed editable stored one.
  601. '''
  602. for pay in self:
  603. if not pay.payment_method_line_id:
  604. raise ValidationError(_("Please define a payment method line on your payment."))
  605. # -------------------------------------------------------------------------
  606. # LOW-LEVEL METHODS
  607. # -------------------------------------------------------------------------
  608. def new(self, values=None, origin=None, ref=None):
  609. payment = super(AccountPayment, self.with_context(is_payment=True)).new(values, origin, ref)
  610. if not payment.journal_id and not payment.default_get(['journal_id']): # might not be computed because declared by inheritance
  611. payment.move_id._compute_journal_id()
  612. return payment
  613. @api.model_create_multi
  614. def create(self, vals_list):
  615. # OVERRIDE
  616. write_off_line_vals_list = []
  617. for vals in vals_list:
  618. # Hack to add a custom write-off line.
  619. write_off_line_vals_list.append(vals.pop('write_off_line_vals', None))
  620. # Force the move_type to avoid inconsistency with residual 'default_move_type' inside the context.
  621. vals['move_type'] = 'entry'
  622. payments = super(AccountPayment, self.with_context(is_payment=True))\
  623. .create([{'name': '/', **vals} for vals in vals_list])\
  624. .with_context(is_payment=False)
  625. for i, pay in enumerate(payments):
  626. write_off_line_vals = write_off_line_vals_list[i]
  627. # Write payment_id on the journal entry plus the fields being stored in both models but having the same
  628. # name, e.g. partner_bank_id. The ORM is currently not able to perform such synchronization and make things
  629. # more difficult by creating related fields on the fly to handle the _inherits.
  630. # Then, when partner_bank_id is in vals, the key is consumed by account.payment but is never written on
  631. # account.move.
  632. to_write = {'payment_id': pay.id}
  633. for k, v in vals_list[i].items():
  634. if k in self._fields and self._fields[k].store and k in pay.move_id._fields and pay.move_id._fields[k].store:
  635. to_write[k] = v
  636. if 'line_ids' not in vals_list[i]:
  637. to_write['line_ids'] = [(0, 0, line_vals) for line_vals in pay._prepare_move_line_default_vals(write_off_line_vals=write_off_line_vals)]
  638. pay.move_id.write(to_write)
  639. self.env.add_to_compute(self.env['account.move']._fields['name'], pay.move_id)
  640. # We need to reset the cached name, since it was recomputed on the delegate account.move model
  641. payments.invalidate_recordset(fnames=['name'])
  642. return payments
  643. def write(self, vals):
  644. # OVERRIDE
  645. res = super().write(vals)
  646. self._synchronize_to_moves(set(vals.keys()))
  647. return res
  648. def unlink(self):
  649. # OVERRIDE to unlink the inherited account.move (move_id field) as well.
  650. moves = self.with_context(force_delete=True).move_id
  651. res = super().unlink()
  652. moves.unlink()
  653. return res
  654. @api.depends('move_id.name')
  655. def name_get(self):
  656. return [(payment.id, payment.move_id.name != '/' and payment.move_id.name or _('Draft Payment')) for payment in self]
  657. # -------------------------------------------------------------------------
  658. # SYNCHRONIZATION account.payment <-> account.move
  659. # -------------------------------------------------------------------------
  660. def _synchronize_from_moves(self, changed_fields):
  661. ''' Update the account.payment regarding its related account.move.
  662. Also, check both models are still consistent.
  663. :param changed_fields: A set containing all modified fields on account.move.
  664. '''
  665. if self._context.get('skip_account_move_synchronization'):
  666. return
  667. for pay in self.with_context(skip_account_move_synchronization=True):
  668. # After the migration to 14.0, the journal entry could be shared between the account.payment and the
  669. # account.bank.statement.line. In that case, the synchronization will only be made with the statement line.
  670. if pay.move_id.statement_line_id:
  671. continue
  672. move = pay.move_id
  673. move_vals_to_write = {}
  674. payment_vals_to_write = {}
  675. if 'journal_id' in changed_fields:
  676. if pay.journal_id.type not in ('bank', 'cash'):
  677. raise UserError(_("A payment must always belongs to a bank or cash journal."))
  678. if 'line_ids' in changed_fields:
  679. all_lines = move.line_ids
  680. liquidity_lines, counterpart_lines, writeoff_lines = pay._seek_for_lines()
  681. if len(liquidity_lines) != 1:
  682. raise UserError(_(
  683. "Journal Entry %s is not valid. In order to proceed, the journal items must "
  684. "include one and only one outstanding payments/receipts account.",
  685. move.display_name,
  686. ))
  687. if len(counterpart_lines) != 1:
  688. raise UserError(_(
  689. "Journal Entry %s is not valid. In order to proceed, the journal items must "
  690. "include one and only one receivable/payable account (with an exception of "
  691. "internal transfers).",
  692. move.display_name,
  693. ))
  694. if any(line.currency_id != all_lines[0].currency_id for line in all_lines):
  695. raise UserError(_(
  696. "Journal Entry %s is not valid. In order to proceed, the journal items must "
  697. "share the same currency.",
  698. move.display_name,
  699. ))
  700. if any(line.partner_id != all_lines[0].partner_id for line in all_lines):
  701. raise UserError(_(
  702. "Journal Entry %s is not valid. In order to proceed, the journal items must "
  703. "share the same partner.",
  704. move.display_name,
  705. ))
  706. if counterpart_lines.account_id.account_type == 'asset_receivable':
  707. partner_type = 'customer'
  708. else:
  709. partner_type = 'supplier'
  710. liquidity_amount = liquidity_lines.amount_currency
  711. move_vals_to_write.update({
  712. 'currency_id': liquidity_lines.currency_id.id,
  713. 'partner_id': liquidity_lines.partner_id.id,
  714. })
  715. payment_vals_to_write.update({
  716. 'amount': abs(liquidity_amount),
  717. 'partner_type': partner_type,
  718. 'currency_id': liquidity_lines.currency_id.id,
  719. 'destination_account_id': counterpart_lines.account_id.id,
  720. 'partner_id': liquidity_lines.partner_id.id,
  721. })
  722. if liquidity_amount > 0.0:
  723. payment_vals_to_write.update({'payment_type': 'inbound'})
  724. elif liquidity_amount < 0.0:
  725. payment_vals_to_write.update({'payment_type': 'outbound'})
  726. move.write(move._cleanup_write_orm_values(move, move_vals_to_write))
  727. pay.write(move._cleanup_write_orm_values(pay, payment_vals_to_write))
  728. @api.model
  729. def _get_trigger_fields_to_synchronize(self):
  730. return (
  731. 'date', 'amount', 'payment_type', 'partner_type', 'payment_reference', 'is_internal_transfer',
  732. 'currency_id', 'partner_id', 'destination_account_id', 'partner_bank_id', 'journal_id'
  733. )
  734. def _synchronize_to_moves(self, changed_fields):
  735. ''' Update the account.move regarding the modified account.payment.
  736. :param changed_fields: A list containing all modified fields on account.payment.
  737. '''
  738. if self._context.get('skip_account_move_synchronization'):
  739. return
  740. if not any(field_name in changed_fields for field_name in self._get_trigger_fields_to_synchronize()):
  741. return
  742. for pay in self.with_context(skip_account_move_synchronization=True):
  743. liquidity_lines, counterpart_lines, writeoff_lines = pay._seek_for_lines()
  744. # Make sure to preserve the write-off amount.
  745. # This allows to create a new payment with custom 'line_ids'.
  746. write_off_line_vals = []
  747. if liquidity_lines and counterpart_lines and writeoff_lines:
  748. write_off_line_vals.append({
  749. 'name': writeoff_lines[0].name,
  750. 'account_id': writeoff_lines[0].account_id.id,
  751. 'partner_id': writeoff_lines[0].partner_id.id,
  752. 'currency_id': writeoff_lines[0].currency_id.id,
  753. 'amount_currency': sum(writeoff_lines.mapped('amount_currency')),
  754. 'balance': sum(writeoff_lines.mapped('balance')),
  755. })
  756. line_vals_list = pay._prepare_move_line_default_vals(write_off_line_vals=write_off_line_vals)
  757. line_ids_commands = [
  758. Command.update(liquidity_lines.id, line_vals_list[0]) if liquidity_lines else Command.create(line_vals_list[0]),
  759. Command.update(counterpart_lines.id, line_vals_list[1]) if counterpart_lines else Command.create(line_vals_list[1])
  760. ]
  761. for line in writeoff_lines:
  762. line_ids_commands.append((2, line.id))
  763. for extra_line_vals in line_vals_list[2:]:
  764. line_ids_commands.append((0, 0, extra_line_vals))
  765. # Update the existing journal items.
  766. # If dealing with multiple write-off lines, they are dropped and a new one is generated.
  767. pay.move_id\
  768. .with_context(skip_invoice_sync=True)\
  769. .write({
  770. 'partner_id': pay.partner_id.id,
  771. 'currency_id': pay.currency_id.id,
  772. 'partner_bank_id': pay.partner_bank_id.id,
  773. 'line_ids': line_ids_commands,
  774. })
  775. def _create_paired_internal_transfer_payment(self):
  776. ''' When an internal transfer is posted, a paired payment is created
  777. with opposite payment_type and swapped journal_id & destination_journal_id.
  778. Both payments liquidity transfer lines are then reconciled.
  779. '''
  780. for payment in self:
  781. paired_payment = payment.copy({
  782. 'journal_id': payment.destination_journal_id.id,
  783. 'destination_journal_id': payment.journal_id.id,
  784. 'payment_type': payment.payment_type == 'outbound' and 'inbound' or 'outbound',
  785. 'move_id': None,
  786. 'ref': payment.ref,
  787. 'paired_internal_transfer_payment_id': payment.id,
  788. 'date': payment.date,
  789. })
  790. paired_payment.move_id._post(soft=False)
  791. payment.paired_internal_transfer_payment_id = paired_payment
  792. body = _(
  793. "This payment has been created from %s",
  794. payment._get_html_link(),
  795. )
  796. paired_payment.message_post(body=body)
  797. body = _(
  798. "A second payment has been created: %s",
  799. paired_payment._get_html_link(),
  800. )
  801. payment.message_post(body=body)
  802. lines = (payment.move_id.line_ids + paired_payment.move_id.line_ids).filtered(
  803. lambda l: l.account_id == payment.destination_account_id and not l.reconciled)
  804. lines.reconcile()
  805. # -------------------------------------------------------------------------
  806. # BUSINESS METHODS
  807. # -------------------------------------------------------------------------
  808. def mark_as_sent(self):
  809. self.write({'is_move_sent': True})
  810. def unmark_as_sent(self):
  811. self.write({'is_move_sent': False})
  812. def action_post(self):
  813. ''' draft -> posted '''
  814. self.move_id._post(soft=False)
  815. self.filtered(
  816. lambda pay: pay.is_internal_transfer and not pay.paired_internal_transfer_payment_id
  817. )._create_paired_internal_transfer_payment()
  818. def action_cancel(self):
  819. ''' draft -> cancelled '''
  820. self.move_id.button_cancel()
  821. def action_draft(self):
  822. ''' posted -> draft '''
  823. self.move_id.button_draft()
  824. def button_open_invoices(self):
  825. ''' Redirect the user to the invoice(s) paid by this payment.
  826. :return: An action on account.move.
  827. '''
  828. self.ensure_one()
  829. action = {
  830. 'name': _("Paid Invoices"),
  831. 'type': 'ir.actions.act_window',
  832. 'res_model': 'account.move',
  833. 'context': {'create': False},
  834. }
  835. if len(self.reconciled_invoice_ids) == 1:
  836. action.update({
  837. 'view_mode': 'form',
  838. 'res_id': self.reconciled_invoice_ids.id,
  839. })
  840. else:
  841. action.update({
  842. 'view_mode': 'list,form',
  843. 'domain': [('id', 'in', self.reconciled_invoice_ids.ids)],
  844. })
  845. return action
  846. def button_open_bills(self):
  847. ''' Redirect the user to the bill(s) paid by this payment.
  848. :return: An action on account.move.
  849. '''
  850. self.ensure_one()
  851. action = {
  852. 'name': _("Paid Bills"),
  853. 'type': 'ir.actions.act_window',
  854. 'res_model': 'account.move',
  855. 'context': {'create': False},
  856. }
  857. if len(self.reconciled_bill_ids) == 1:
  858. action.update({
  859. 'view_mode': 'form',
  860. 'res_id': self.reconciled_bill_ids.id,
  861. })
  862. else:
  863. action.update({
  864. 'view_mode': 'list,form',
  865. 'domain': [('id', 'in', self.reconciled_bill_ids.ids)],
  866. })
  867. return action
  868. def button_open_statement_lines(self):
  869. ''' Redirect the user to the statement line(s) reconciled to this payment.
  870. :return: An action on account.move.
  871. '''
  872. self.ensure_one()
  873. action = {
  874. 'name': _("Matched Transactions"),
  875. 'type': 'ir.actions.act_window',
  876. 'res_model': 'account.bank.statement.line',
  877. 'context': {'create': False},
  878. }
  879. if len(self.reconciled_statement_line_ids) == 1:
  880. action.update({
  881. 'view_mode': 'form',
  882. 'res_id': self.reconciled_statement_line_ids.id,
  883. })
  884. else:
  885. action.update({
  886. 'view_mode': 'list,form',
  887. 'domain': [('id', 'in', self.reconciled_statement_line_ids.ids)],
  888. })
  889. return action
  890. def button_open_journal_entry(self):
  891. ''' Redirect the user to this payment journal.
  892. :return: An action on account.move.
  893. '''
  894. self.ensure_one()
  895. return {
  896. 'name': _("Journal Entry"),
  897. 'type': 'ir.actions.act_window',
  898. 'res_model': 'account.move',
  899. 'context': {'create': False},
  900. 'view_mode': 'form',
  901. 'res_id': self.move_id.id,
  902. }
  903. def action_open_destination_journal(self):
  904. ''' Redirect the user to this destination journal.
  905. :return: An action on account.move.
  906. '''
  907. self.ensure_one()
  908. action = {
  909. 'name': _("Destination journal"),
  910. 'type': 'ir.actions.act_window',
  911. 'res_model': 'account.journal',
  912. 'context': {'create': False},
  913. 'view_mode': 'form',
  914. 'target': 'new',
  915. 'res_id': self.destination_journal_id.id,
  916. }
  917. return action
  918. # For optimization purpose, creating the reverse relation of m2o in _inherits saves
  919. # a lot of SQL queries
  920. class AccountMove(models.Model):
  921. _name = "account.move"
  922. _inherit = ['account.move']
  923. payment_ids = fields.One2many('account.payment', 'move_id', string='Payments')