Debian Codegraph @

addons/l10n_latam_check/models/account_payment.py

raw
1 from odoo import fields, models, api, Command, _
2 from odoo.exceptions import UserError, ValidationError
3 from odoo.tools.misc import format_date
4
5
6 class AccountPayment(models.Model):
7 _inherit = 'account.payment'
8
9 l10n_latam_new_check_ids = fields.One2many('l10n_latam.check', 'payment_id', string='Checks')
10 l10n_latam_move_check_ids = fields.Many2many(
11 comodel_name='l10n_latam.check',
12 relation='l10n_latam_check_account_payment_rel',
13 column1="payment_id",
14 column2="check_id",
15 required=True,
16 copy=False,
17 string="Checks Operations"
18 )
19 # Warning message in case of unlogical third party check operations
20 l10n_latam_check_warning_msg = fields.Text(compute='_compute_l10n_latam_check_warning_msg')
21 amount = fields.Monetary(compute="_compute_amount", readonly=False, store=True)
22
23 @api.constrains('state', 'move_id')
24 def _check_move_id(self):
25 for payment in self:
26 if (
27 not payment.move_id and
28 payment.payment_method_code in ('own_checks', 'new_third_party_checks', 'in_third_party_checks', 'out_third_party_checks', 'return_third_party_checks') and
29 not payment.outstanding_account_id
30 ):
31 raise ValidationError(_("A payment with any Third Party Check or Own Check payment methods needs an outstanding account"))
32
33 @api.depends('l10n_latam_move_check_ids.amount', 'l10n_latam_new_check_ids.amount', 'payment_method_code')
34 def _compute_amount(self):
35 for rec in self:
36 checks = rec.l10n_latam_new_check_ids if rec._is_latam_check_payment(check_subtype='new_check') else rec.l10n_latam_move_check_ids
37 if checks:
38 rec.amount = sum(checks.mapped('amount'))
39
40 def _is_latam_check_payment(self, check_subtype=False):
41 if check_subtype == 'move_check':
42 codes = ['in_third_party_checks', 'out_third_party_checks', 'return_third_party_checks']
43 elif check_subtype == 'new_check':
44 codes = ['new_third_party_checks', 'own_checks']
45 else:
46 codes = ['in_third_party_checks', 'out_third_party_checks', 'return_third_party_checks', 'new_third_party_checks', 'own_checks']
47 return self.payment_method_code in codes
48
49 def action_post(self):
50 # unlink checks if payment method code is not for checks. We do it on post and not when changing payment
51 # method so that the user don't loose checks data in case of changing payment method and coming back again
52 # also, changing partner recompute payment method so all checks would be cleaned
53 for payment in self.filtered(lambda x: x.l10n_latam_new_check_ids and not x._is_latam_check_payment(check_subtype='new_check')):
54 payment.l10n_latam_new_check_ids.unlink()
55 if not self.env.context.get('l10n_ar_skip_remove_check'):
56 for payment in self.filtered(lambda x: x.l10n_latam_move_check_ids and not x._is_latam_check_payment(check_subtype='move_check')):
57 payment.l10n_latam_move_check_ids = False
58 msgs = self._get_blocking_l10n_latam_warning_msg()
59 if msgs:
60 error_msg = "\n".join(f"* {msg}" for msg in msgs)
61 raise ValidationError(error_msg)
62 super().action_post()
63 self._l10n_latam_check_split_move()
64
65 def _get_latam_checks(self):
66 self.ensure_one()
67 if self._is_latam_check_payment(check_subtype='new_check'):
68 return self.l10n_latam_new_check_ids
69 elif self._is_latam_check_payment(check_subtype='move_check'):
70 return self.l10n_latam_move_check_ids
71 else:
72 return self.env['l10n_latam.check']
73
74 def _get_blocking_l10n_latam_warning_msg(self):
75 msgs = []
76 for rec in self.filtered(lambda x: x.state == 'draft' and x._is_latam_check_payment()):
77 if any(rec.currency_id != check.currency_id for check in rec._get_latam_checks()):
78 msgs.append(_('The currency of the payment and the currency of the check must be the same.'))
79 if not rec.currency_id.is_zero(sum(rec._get_latam_checks().mapped('amount')) - rec.amount):
80 msgs.append(
81 _('The amount of the payment does not match the amount of the selected check. '
82 'Please try to deselect and select the check again.')
83 )
84 # checks being moved
85 if rec._is_latam_check_payment(check_subtype='move_check'):
86 if any(check.payment_id.state == 'draft' for check in rec.l10n_latam_move_check_ids):
87 msgs.append(
88 _('Selected checks "%s" are not posted', rec.l10n_latam_move_check_ids.filtered(lambda x: x.payment_id.state == 'draft').mapped('display_name'))
89 )
90 elif rec.payment_type == 'outbound' and any(check.current_journal_id != rec.journal_id for check in rec.l10n_latam_move_check_ids):
91 # check outbound payment and transfer or inbound transfer
92 msgs.append(_(
93 'Some checks are not anymore in journal, it seems it has been moved by another payment.')
94 )
95 elif rec.payment_type == 'inbound' and not rec._is_latam_check_transfer() and any(rec.l10n_latam_move_check_ids.mapped('current_journal_id')):
96 msgs.append(
97 _("Some checks are already in hand and can't be received again. Checks: %s",
98 ', '.join(rec.l10n_latam_move_check_ids.mapped('display_name')))
99 )
100
101 for check in rec.l10n_latam_move_check_ids:
102 date = rec.date or fields.Datetime.now()
103
104 last_operation = check._get_last_operation()
105 if last_operation and last_operation[0].date > date:
106 msgs.append(
107 _(
108 "It seems you're trying to move a check with a date (%(date)s) prior to last "
109 "operation done with the check (%(last_operation)s). This may be wrong, please "
110 "double check it. By continue, the last operation on "
111 "the check will remain being %(last_operation)s",
112 date=format_date(self.env, date), last_operation=last_operation.display_name
113 )
114 )
115 return msgs
116
117 def _get_reconciled_checks_error(self):
118 checks_reconciled = self.l10n_latam_new_check_ids.filtered(lambda x: x.issue_state in ['debited', 'voided'])
119 if checks_reconciled:
120 raise UserError(
121 _("You can't cancel or re-open a payment with checks if some check has been debited or been voided. "
122 "Checks:\n%s", ('\n'.join(['* %s (%s)' % (x.name, x.issue_state) for x in checks_reconciled])))
123 )
124
125 def action_cancel(self):
126 self._get_reconciled_checks_error()
127 super().action_cancel()
128
129 def action_draft(self):
130 self._get_reconciled_checks_error()
131 super().action_draft()
132
133 def _l10n_latam_check_split_move(self):
134 for payment in self.filtered(lambda x: x.payment_method_code == 'own_checks' and x.payment_type == 'outbound'):
135 if len(payment.l10n_latam_new_check_ids) == 1:
136 liquidity_line = payment._seek_for_lines()[0]
137 payment.l10n_latam_new_check_ids.outstanding_line_id = liquidity_line.id
138 continue
139
140 vals = {
141 'journal_id': payment.journal_id.id,
142 'move_type': 'entry',
143 'line_ids': [],
144 }
145 payment_liquidity_line = payment._seek_for_lines()[0]
146
147 # One line per check
148 checks_total = sum(payment.l10n_latam_new_check_ids.mapped('amount'))
149 liquidity_balance_total = 0.0
150 for check in payment.l10n_latam_new_check_ids:
151 liquidity_amount_currency = -check.amount
152
153 if check == payment.l10n_latam_new_check_ids[-1]:
154 liquidity_balance = payment.currency_id.round(payment_liquidity_line.balance - liquidity_balance_total)
155 else:
156 liquidity_balance = payment.currency_id.round(payment_liquidity_line.balance * check.amount / checks_total)
157 liquidity_balance_total += liquidity_balance
158
159 vals['line_ids'].append(
160 Command.create({
161 'name': _(
162 'Check %(check_number)s - %(suffix)s',
163 check_number=check.name,
164 suffix=''.join([item[1] for item in payment._get_aml_default_display_name_list()])),
165 'date_maturity': check.payment_date,
166 'amount_currency': liquidity_amount_currency,
167 'currency_id': check.currency_id.id,
168 'debit': max(0.0, liquidity_balance),
169 'credit': -min(liquidity_balance, 0.0),
170 'partner_id': payment_liquidity_line.partner_id.id,
171 'account_id': payment_liquidity_line.account_id.id,
172 'l10n_latam_check_ids': [Command.link(check.id)]
173 }),
174 )
175
176 # Cancel payment line
177 vals['line_ids'].append(
178 Command.create({
179 'name': payment_liquidity_line.name,
180 'date_maturity': payment_liquidity_line.date_maturity,
181 'amount_currency': -payment_liquidity_line.amount_currency,
182 'currency_id': payment_liquidity_line.currency_id.id,
183 'debit': -payment_liquidity_line.debit,
184 'credit': -payment_liquidity_line.credit,
185 'partner_id': payment_liquidity_line.partner_id.id,
186 'account_id': payment_liquidity_line.account_id.id,
187 }),
188 )
189 move_id = self.env['account.move'].create(vals)
190 move_id.action_post()
191 split_move_counterpart_line = move_id.line_ids.filtered(lambda x: x.amount_currency == -payment_liquidity_line.amount_currency)
192 (split_move_counterpart_line + payment_liquidity_line).reconcile()
193
194 def _l10n_latam_check_unlink_split_move(self):
195 self.ensure_one()
196 for check in self.l10n_latam_new_check_ids:
197 if self.move_id == check.outstanding_line_id.move_id:
198 check.outstanding_line_id = False
199 continue
200 check.outstanding_line_id.move_id.button_draft()
201 check.outstanding_line_id.move_id.unlink()
202
203 @api.depends(
204 'payment_method_line_id', 'state', 'date', 'amount', 'currency_id', 'company_id',
205 'l10n_latam_move_check_ids.issuer_vat', 'l10n_latam_move_check_ids.bank_id', 'l10n_latam_move_check_ids.payment_id.date',
206 'l10n_latam_new_check_ids.amount', 'l10n_latam_new_check_ids.name',
207 )
208 def _compute_l10n_latam_check_warning_msg(self):
209 """
210 Compute warning message for latam checks checks
211 We use l10n_latam_check_number as de dependency because on the interface this is the field the user is using.
212 Another approach could be to add an onchange on _inverse_l10n_latam_check_number method
213 """
214 self.l10n_latam_check_warning_msg = False
215 for rec in self.filtered(lambda x: x._is_latam_check_payment()):
216 msgs = rec._get_blocking_l10n_latam_warning_msg()
217 # new third party check uniqueness warning (on own checks it's done by a sql constraint)
218 if rec.payment_method_code == 'new_third_party_checks':
219 same_checks = self.env['l10n_latam.check']
220 for check in rec.l10n_latam_new_check_ids.filtered(
221 lambda x: x.name and x.payment_method_line_id.code == 'new_third_party_checks' and
222 x.bank_id and x.issuer_vat):
223 same_checks += same_checks.search([
224 ('company_id', '=', rec.company_id.id),
225 ('bank_id', '=', check.bank_id.id),
226 ('issuer_vat', '=', check.issuer_vat),
227 ('name', '=', check.name),
228 ('payment_id.state', 'not in', ['draft', 'canceled']),
229 ('id', '!=', check._origin.id)], limit=1)
230 if same_checks:
231 msgs.append(
232 _("Other checks were found with same number, issuer and bank. Please double check you are not "
233 "encoding the same check more than once. List of other payments/checks: %s",
234 ", ".join(same_checks.mapped('display_name')))
235 )
236 rec.l10n_latam_check_warning_msg = msgs and '* %s' % '\n* '.join(msgs) or False
237
238 @api.model
239 def _get_trigger_fields_to_synchronize(self):
240 res = super()._get_trigger_fields_to_synchronize()
241 return res + ('l10n_latam_new_check_ids',)
242
243 def _prepare_move_line_default_vals(self, write_off_line_vals=None, force_balance=None):
244 """ Add check name and operation on liquidity line """
245 res = super()._prepare_move_line_default_vals(write_off_line_vals=write_off_line_vals, force_balance=force_balance)
246
247 # if only one check we don't create the split line, we add same data on liquidity line
248 if self.payment_method_code == 'own_checks' and self.payment_type == 'outbound' and len(self.l10n_latam_new_check_ids) == 1:
249 res[0].update({
250 'name': _(
251 'Check %(check_number)s - %(suffix)s',
252 check_number=self.l10n_latam_new_check_ids.name,
253 suffix=''.join([item[1] for item in self._get_aml_default_display_name_list()])),
254 'date_maturity': self.l10n_latam_new_check_ids.payment_date,
255 })
256 # we dont check the payment method code because when deposited on bank/cash journals pay method is manual but we still change the label
257 # we dont want this names on the own checks because it doesn't add value, already each split/check line will have it name
258 elif (self.l10n_latam_new_check_ids or self.l10n_latam_move_check_ids) and self.payment_method_code != 'own_checks':
259 check_name = [check_name for check_name in (self.l10n_latam_new_check_ids | self.l10n_latam_move_check_ids).mapped('name') if check_name]
260 document_name = (
261 _('Checks %s received') if self.payment_type == 'inbound' else _('Checks %s delivered')) % (
262 ', '.join(check_name)
263 )
264 res[0].update({
265 'name': document_name + ' - ' + ''.join([item[1] for item in self._get_aml_default_display_name_list()]),
266 })
267 return res
268
269 @api.depends('l10n_latam_move_check_ids')
270 def _compute_destination_account_id(self):
271 # EXTENDS 'account'
272 super()._compute_destination_account_id()
273 for payment in self:
274 if payment.l10n_latam_move_check_ids and (not payment.partner_id or payment.partner_id == payment.company_id.partner_id):
275 payment.destination_account_id = payment.company_id.transfer_account_id.id
276
277 def _is_latam_check_transfer(self):
278 self.ensure_one()
279 return not self.partner_id and self.destination_account_id == self.company_id.transfer_account_id