Debian Codegraph @

addons/l10n_hu_edi/models/account_move.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import math
4 import base64
5 import logging
6 import re
7
8 from lxml import etree
9
10 from odoo import fields, models, api, _
11 from odoo.http import request
12 from odoo.exceptions import LockError, UserError, ValidationError
13 from odoo.tools import formatLang, float_compare, float_is_zero, float_round, float_repr, cleanup_xml_node, groupby
14 from odoo.tools.misc import split_every
15 from odoo.addons.base_iban.models.res_partner_bank import normalize_iban
16 from odoo.addons.l10n_hu_edi.models.l10n_hu_edi_connection import format_bool, L10nHuEdiConnection, L10nHuEdiConnectionError
17
18 _logger = logging.getLogger(__name__)
19
20
21 class AccountMove(models.Model):
22 _inherit = 'account.move'
23
24 l10n_hu_payment_mode = fields.Selection(
25 [
26 ("TRANSFER", "Transfer"),
27 ("CASH", "Cash"),
28 ("CARD", "Credit/debit card"),
29 ("VOUCHER", "Voucher"),
30 ("OTHER", "Other"),
31 ],
32 string="Payment mode",
33 help="NAV expected payment mode of the invoice.",
34 )
35
36 # === EDI Fields === #
37 l10n_hu_edi_state = fields.Selection(
38 ######################################################################################################################
39 # STATE DIAGRAM
40 # * False, rejected, cancelled --[upload]--> False, sent, send_timeout
41 # * sent --[query_status]--> sent, confirmed, confirmed_warning, rejected
42 # * confirmed, confirmed_warning --[request_cancel]--> cancel_sent, cancel_timeout
43 # * cancel_sent, cancel_pending --[query_status]--> confirmed_warning, cancel_pending, cancelled
44 # * send_timeout --[recover_timeout]--> False, send_timeout, confirmed, confirmed_warning, rejected,
45 # * cancel_timeout --[recover_timeout]--> confirmed_warning, cancel_sent, cancel_timeout, cancel_pending, cancelled
46 ######################################################################################################################
47 selection=[
48 ('sent', 'Sent, waiting for response'),
49 ('send_timeout', 'Timeout when sending'),
50 ('confirmed', 'Confirmed'),
51 ('confirmed_warning', 'Confirmed with warnings'),
52 ('rejected', 'Rejected'),
53 ('cancel_sent', 'Cancellation request sent'),
54 ('cancel_timeout', 'Timeout when requesting cancellation'),
55 ('cancel_pending', 'Cancellation request pending'),
56 ('cancelled', 'Cancelled'),
57 ],
58 string='NAV 3.0 status',
59 copy=False,
60 index='btree_not_null',
61 )
62 l10n_hu_edi_batch_upload_index = fields.Integer(
63 string='Index of invoice within a batch upload',
64 copy=False,
65 )
66 l10n_hu_edi_attachment = fields.Binary(
67 string='Invoice XML file',
68 attachment=True,
69 copy=False,
70 )
71 l10n_hu_edi_send_time = fields.Datetime(
72 string='Invoice upload time',
73 copy=False,
74 )
75 l10n_hu_edi_transaction_code = fields.Char(
76 string='Transaction Code',
77 index='trigram',
78 copy=False,
79 tracking=True,
80 )
81
82 # A dict with the following structure:
83 # {
84 # 'error_title': the main heading of the message
85 # 'errors': a list of message items
86 # 'blocking_level': {'error' | 'warning' | None}
87 # directs which blocking behaviour to adopt in the Send and Print:
88 # * error: blocks PDF generation and sending by e-mail
89 # * warning: PDF is generated and sent by e-mail, but a warning appears in the banner
90 # * None: PDF is generated and sent by e-mail, no warning appears
91 # }
92 l10n_hu_edi_messages = fields.Json(
93 string='Transaction messages (JSON)',
94 copy=False,
95 )
96
97 l10n_hu_invoice_chain_index = fields.Integer(
98 string='Invoice Chain Index',
99 help="""
100 Index in the chain of modification invoices:
101 -1 for a base invoice;
102 1, 2, 3, ... for modification invoices;
103 0 for rejected/cancelled invoices or if it has not yet been set.
104 """,
105 copy=False,
106 )
107 l10n_hu_edi_attachment_filename = fields.Char(
108 string='Invoice XML filename',
109 compute='_compute_l10n_hu_edi_attachment_filename',
110 )
111 l10n_hu_edi_message_html = fields.Html(
112 string='Transaction messages',
113 compute='_compute_message_html',
114 )
115
116 # === Constraints === #
117
118 @api.constrains('l10n_hu_edi_state', 'state')
119 def _check_posted_if_active(self):
120 """ Enforce the constraint that you cannot reset to draft / cancel a posted invoice if it was already sent to NAV. """
121 for move in self:
122 if move.state in ['draft', 'cancel'] and move.l10n_hu_edi_state not in [False, 'rejected', 'cancelled']:
123 raise ValidationError(_('Cannot reset to draft or cancel invoice %s because an electronic document was already sent to NAV!', move.name))
124
125 # === Computes === #
126
127 @api.depends('delivery_date')
128 def _compute_expected_currency_rate(self):
129 super()._compute_expected_currency_rate()
130
131 def _get_invoice_currency_rate_date(self):
132 self.ensure_one()
133 if self.country_code == 'HU' and self.delivery_date:
134 return self.delivery_date
135 return super()._get_invoice_currency_rate_date()
136
137 @api.depends('l10n_hu_edi_messages')
138 def _compute_message_html(self):
139 for move in self:
140 if move.l10n_hu_edi_messages:
141 move.l10n_hu_edi_message_html = self.env['account.move.send']._format_error_html(move.l10n_hu_edi_messages)
142 else:
143 move.l10n_hu_edi_message_html = False
144
145 @api.depends('l10n_hu_edi_state', 'state')
146 def _compute_show_reset_to_draft_button(self):
147 super()._compute_show_reset_to_draft_button()
148 self.filtered(lambda m: m.l10n_hu_edi_state not in [False, 'rejected', 'cancelled']).show_reset_to_draft_button = False
149
150 @api.depends('l10n_hu_edi_state')
151 def _compute_need_cancel_request(self):
152 # EXTEND 'account' to add dependencies
153 return super()._compute_need_cancel_request()
154
155 @api.depends('name')
156 def _compute_l10n_hu_edi_attachment_filename(self):
157 for move in self:
158 move.l10n_hu_edi_attachment_filename = f'{move.name.replace("/", "_")}.xml' if move.name else 'nav30.xml'
159
160 # === Inverses === #
161
162 def _inverse_delivery_date(self):
163 super()._inverse_delivery_date()
164 self._conditional_add_to_compute('invoice_currency_rate', lambda m: m.country_code == 'HU')
165
166 # === Overrides === #
167
168 def _need_cancel_request(self):
169 # EXTEND account
170 # Technical annulment should be available only in debug mode
171 return super()._need_cancel_request() or (self.l10n_hu_edi_state in ['confirmed', 'confirmed_warning'] and request and request.session.debug)
172
173 def button_request_cancel(self):
174 # EXTEND 'account'
175 if self._need_cancel_request() and self.l10n_hu_edi_state in ['confirmed', 'confirmed_warning']:
176 return {
177 "name": _("Technical Annulment"),
178 "type": "ir.actions.act_window",
179 "view_type": "form",
180 "view_mode": "form",
181 "res_model": "l10n_hu_edi.cancellation",
182 "target": "new",
183 "context": {"default_invoice_id": self.id},
184 }
185
186 return super().button_request_cancel()
187
188 # === Actions === #
189
190 def l10n_hu_edi_button_update_status(self, from_cron=False):
191 """ Attempt to update the status of the invoices in `self` """
192 invoices_to_query = self.filtered(lambda m: 'query_status' in m._l10n_hu_edi_get_valid_actions())
193
194 with L10nHuEdiConnection(self.env) as connection:
195 # Call `query_status` on the invoices.
196 invoices_to_query._l10n_hu_edi_query_status(connection)
197
198 # Attempt to recover missing transactions, if any invoice is missing a transaction code
199 # or has a duplicate error.
200 recover_transactions_error = False
201 if any(
202 not m.l10n_hu_edi_transaction_code
203 or any(
204 'INVOICE_NUMBER_NOT_UNIQUE' in error or 'ANNULMENT_IN_PROGRESS' in error
205 for error in m.l10n_hu_edi_messages['errors']
206 )
207 for m in self
208 ):
209 recover_transactions_error = self.company_id._l10n_hu_edi_recover_transactions(connection)
210
211 # Error handling.
212 for invoice in invoices_to_query:
213 # Log invoice status in chatter.
214 formatted_message = self.env['account.move.send']._format_error_html(invoice.l10n_hu_edi_messages)
215 invoice.message_post(body=formatted_message)
216
217 if self.env['account.move.send']._can_commit():
218 self.env.cr.commit()
219
220 # If blocking errors, raise UserError, or log if we are in a cron.
221 for invoice in invoices_to_query:
222 if invoice.l10n_hu_edi_messages.get('blocking_level') == 'error' or recover_transactions_error:
223 if invoice.l10n_hu_edi_messages.get('blocking_level') == 'error':
224 error_text = self.env['account.move.send']._format_error_text(invoice.l10n_hu_edi_messages)
225 else:
226 error_text = self.env['account.move.send']._format_error_text(recover_transactions_error)
227 if not from_cron:
228 raise UserError(error_text)
229 else:
230 _logger.error(error_text)
231
232 def l10n_hu_edi_button_hide_banner(self):
233 messages = self.l10n_hu_edi_messages
234 if messages:
235 messages['hide_banner'] = True
236 self.l10n_hu_edi_messages = messages
237
238 # === Helpers === #
239
240 def _l10n_hu_edi_get_valid_actions(self):
241 """ If any NAV 3.0 flows are applicable to the given invoice, return them, else None. """
242 self.ensure_one()
243 valid_actions = []
244 if (
245 self.country_code == 'HU'
246 and self.is_sale_document()
247 and self.state == 'posted'
248 ):
249 if self.l10n_hu_edi_state in [False, 'rejected', 'cancelled']:
250 valid_actions.append('upload')
251 if self.l10n_hu_edi_transaction_code:
252 valid_actions.append('query_status')
253 if self.l10n_hu_edi_state in ['confirmed', 'confirmed_warning']:
254 valid_actions.append('request_cancel')
255 if not valid_actions:
256 # Placeholder to denote that the invoice was already processed with a NAV flow
257 valid_actions.append(True)
258 return valid_actions
259
260 def _l10n_hu_get_chain_base(self):
261 """ Get the base invoice of the invoice chain. """
262 modification_invoices = self
263 base_invoices = self.env['account.move']
264 while modification_invoices:
265 base_invoices |= modification_invoices.filtered(lambda m: not m.reversed_entry_id and not m.debit_origin_id)
266 modification_invoices = modification_invoices.reversed_entry_id | modification_invoices.debit_origin_id
267 return base_invoices
268
269 def _l10n_hu_get_chain_invoices(self):
270 """ Given base invoices, get all invoices in the chain. """
271 chain_invoices = self
272 next_invoices = self
273 while (next_invoices := next_invoices.reversal_move_ids | next_invoices.debit_note_ids):
274 chain_invoices |= next_invoices
275 return chain_invoices
276
277 def _l10n_hu_get_currency_rate(self):
278 """ Get the invoice currency / HUF rate.
279
280 We don't use `invoice_currency_rate` to avoid rounding error as 1/0.002470 ≃ 404.87,
281 and we want exactly 404.87, i.e. the rate given by the MNB of Hungary, to avoid NAV error
282 upon XML submission.
283 """
284 self.ensure_one()
285 return self.env['res.currency']._get_conversion_rate(
286 from_currency=self.currency_id,
287 to_currency=self.env.ref('base.HUF'),
288 company=self.company_id,
289 date=self._get_invoice_currency_rate_date(),
290 )
291
292 def _l10n_hu_edi_set_chain_index(self):
293 """ Set the l10n_hu_invoice_chain_index field. """
294 self.ensure_one()
295 base_invoice = self._l10n_hu_get_chain_base()
296 if base_invoice == self:
297 self.l10n_hu_invoice_chain_index = -1 # -1 indicates a base invoice (0 indicates the chain index was not set).
298 else:
299 # Lock base invoice to prevent concurrent updates, ensuring sequence integrity.
300 base_invoice._l10n_hu_edi_acquire_lock()
301
302 chain_indexes_already_sent = base_invoice._l10n_hu_get_chain_invoices().filtered(
303 lambda m: m.l10n_hu_edi_state not in ['rejected', 'cancelled']
304 ).mapped('l10n_hu_invoice_chain_index')
305 for i in range(1, len(chain_indexes_already_sent) + 1):
306 if i not in chain_indexes_already_sent:
307 self.l10n_hu_invoice_chain_index = i
308 break
309
310 def _l10n_hu_edi_acquire_lock(self):
311 """ Acquire a write lock on the invoices in self. """
312 try:
313 self.lock_for_update()
314 except LockError:
315 raise UserError(_('Could not acquire lock on invoices - is another user performing operations on them?')) from None
316
317 # === EDI: Flow === #
318
319 def _l10n_hu_edi_check_invoices(self):
320 hu_vat_regex = re.compile(r'(HU)?\d{8}-[1-5]-\d{2}')
321 hu_bank_account_regex = re.compile(r'\d{8}-\d{8}-\d{8}|\d{8}-\d{8}|[A-Z]{2}\d{2}[0-9A-Za-z]{11,30}')
322
323 # This contains all the advance invoices that correspond to final invoices in `self`.
324 advance_invoices = self.filtered(lambda m: not m._is_downpayment()).invoice_line_ids._get_downpayment_lines().mapped('move_id')
325
326 checks = {
327 'company_vat_missing': {
328 'records': self.company_id.filtered(lambda c: not c.vat),
329 'message': _('Please set company VAT number!'),
330 'action_text': _('View Company/ies'),
331 },
332 'company_vat_invalid': {
333 'records': self.company_id.filtered(
334 lambda c: (
335 (c.vat and not hu_vat_regex.fullmatch(c.vat))
336 or (c.l10n_hu_group_vat and not hu_vat_regex.fullmatch(c.l10n_hu_group_vat))
337 )
338 ),
339 'message': _('Please enter the Hungarian VAT (and/or Group VAT) number in 12345678-1-12 format!'),
340 'action_text': _('View Company/ies'),
341 },
342 'company_address_missing': {
343 'records': self.company_id.filtered(lambda c: not c.country_id or not c.zip or not c.city or not c.street),
344 'message': _('Please set company Country, Zip, City and Street!'),
345 'action_text': _('View Company/ies'),
346 },
347 'company_not_huf': {
348 'records': self.company_id.filtered(lambda c: c.currency_id.name not in ['HUF', 'EUR']),
349 'message': _('Please use HUF or EUR as your company currency.'),
350 'action_text': _('View Company/ies'),
351 },
352 'partner_bank_account_invalid': {
353 'records': self.partner_bank_id.filtered(lambda p: not hu_bank_account_regex.fullmatch(p.acc_number)),
354 'message': _('Please set a valid recipient bank account number!'),
355 'action_text': _('View partner(s)'),
356 },
357 'partner_vat_missing': {
358 'records': self.partner_id.commercial_partner_id.filtered(
359 lambda p: p.is_company and not p.vat
360 ),
361 'message': _('Please set partner Tax ID on company partners!'),
362 'action_text': _('View partner(s)'),
363 },
364 'partner_vat_invalid': {
365 'records': self.partner_id.commercial_partner_id.filtered(
366 lambda p: (
367 p.is_company and p.country_code == 'HU'
368 and (
369 (p.vat and not hu_vat_regex.fullmatch(p.vat))
370 or (p.l10n_hu_group_vat and not hu_vat_regex.fullmatch(p.l10n_hu_group_vat))
371 )
372 )
373 ),
374 'message': _('Please enter the Hungarian VAT (and/or Group VAT) number in 12345678-1-12 format!'),
375 'action_text': _('View partner(s)'),
376 },
377 'partner_address_missing': {
378 'records': self.partner_id.commercial_partner_id.filtered(
379 lambda p: p.is_company and (not p.country_id or not p.zip or not p.city or not p.street),
380 ),
381 'message': _('Please set partner Country, Zip, City and Street!'),
382 'action_text': _('View partner(s)'),
383 },
384 'invoice_date_not_today': {
385 'records': self.filtered(lambda m: m.invoice_date != fields.Date.context_today(m)),
386 'message': _('Please set invoice date to today!'),
387 'action_text': _('View invoice(s)'),
388 },
389 'invoice_chain_not_confirmed': {
390 'records': self.env['account.move'].union(*[
391 move._l10n_hu_get_chain_base()._l10n_hu_get_chain_invoices().filtered(
392 lambda m: (
393 m.id < move.id
394 and m.l10n_hu_edi_state in [False, 'rejected', 'cancelled']
395 and m not in self
396 )
397 )
398 for move in self
399 ]),
400 'message': _('The following invoices appear to be earlier in the chain, but have not yet been sent. Please send them first.'),
401 'action_text': _('View invoice(s)'),
402 },
403 'invoice_advance_not_paid': {
404 'records': advance_invoices.filtered(
405 lambda m: (
406 m.payment_state not in ['in_payment', 'paid', 'partial']
407 or m.l10n_hu_edi_state in [False, 'rejected', 'cancelled']
408 and m not in self # It's okay to send an advance and a final invoice together, as we sort by id before sending.
409 )
410 ),
411 'message': _('All advance invoices must be paid and sent to NAV before the final invoice is issued.'),
412 'action_text': _('View advance invoice(s)'),
413 },
414 'invoice_line_not_one_vat_tax': {
415 'records': self.filtered(
416 lambda m: any(
417 len(l.tax_ids.filtered(lambda t: t.l10n_hu_tax_type)) != 1
418 for l in m.invoice_line_ids.filtered(lambda l: l.display_type == 'product')
419 )
420 ),
421 'message': _('Please set exactly one VAT tax on each invoice line!'),
422 'action_text': _('View invoice(s)'),
423 },
424 'invoice_line_non_vat_taxes_misconfigured': {
425 'records': self.invoice_line_ids.tax_ids.filtered(
426 lambda t: not t.l10n_hu_tax_type and (not t.price_include or not t.include_base_amount)
427 ),
428 'message': _("Please set any non-VAT (excise) taxes to be 'Included in Price' and 'Affects subsequent taxes'!"),
429 'action_text': _('View tax(es)'),
430 },
431 'invoice_line_vat_taxes_misconfigured': {
432 'records': self.invoice_line_ids.tax_ids.filtered(
433 lambda t: t.l10n_hu_tax_type and not t.is_base_affected
434 ),
435 'message': _("Please set any VAT taxes to be 'Affected by previous taxes'!"),
436 'action_text': _('View tax(es)'),
437 },
438 }
439
440 errors = {
441 f"l10n_hu_edi_{check}": {
442 'message': values['message'],
443 'action_text': values['action_text'],
444 'action': values['records']._get_records_action(name=values['action_text']),
445 }
446 for check, values in checks.items()
447 if values['records']
448 }
449
450 if companies_missing_credentials := self.company_id.filtered(lambda c: not c.l10n_hu_edi_server_mode):
451 errors['l10n_hu_edi_company_credentials_missing'] = {
452 'message': _('Please set NAV credentials in the Accounting Settings!'),
453 'action_text': _('Open Accounting Settings'),
454 'action': self.env.ref('account.action_account_config').with_company(companies_missing_credentials[0])._get_action_dict(),
455 }
456 return errors
457
458 def _l10n_hu_edi_upload(self, connection):
459 """ Generate invoice XMLs and send to NAV. """
460 invoices_sorted = self.sorted(lambda m: m.id)
461 for invoice in invoices_sorted:
462 # If we come from the 'cancelled' state, this means the previous XML had been confirmed
463 # before it was cancelled.
464 # In that case, we want to keep it as a regular invoice attachment, for future reference.
465 if invoice.l10n_hu_edi_state == 'cancelled':
466 self.env['ir.attachment'].search([
467 ('res_model', '=', self._name),
468 ('res_id', '=', invoice.id),
469 ('res_field', '=', 'l10n_hu_edi_attachment'),
470 ]).write({
471 'res_field': False,
472 'name': f'{invoice.name.replace("/", "_")}_cancelled_{invoice.l10n_hu_edi_transaction_code}.xml',
473 })
474
475 # Set chain index
476 invoice._l10n_hu_edi_set_chain_index()
477
478 # Generate XML
479 invoice.l10n_hu_edi_attachment = base64.b64encode(invoice._l10n_hu_edi_generate_xml())
480
481 # Set name & mimetype on newly-created attachment.
482 attachment = self.env['ir.attachment'].search([
483 ('res_model', '=', self._name),
484 ('res_id', '=', invoice.id),
485 ('res_field', '=', 'l10n_hu_edi_attachment'),
486 ])
487 attachment.write({
488 'name': invoice.l10n_hu_edi_attachment_filename,
489 'mimetype': 'application/xml',
490 })
491
492 # Batch by company, with max 100 invoices per batch.
493 for __, batch_company in groupby(invoices_sorted, lambda m: m.company_id):
494 for batch in split_every(100, batch_company):
495 self.env['account.move'].union(*batch)._l10n_hu_edi_upload_single_batch(connection)
496
497 def _l10n_hu_edi_get_operation_type(self):
498 base_invoice = self._l10n_hu_get_chain_base()
499 modification_invoices = self._l10n_hu_get_chain_invoices() - base_invoice
500
501 all_invoices_residual_zero = all(invoice.amount_residual == 0 for invoice in modification_invoices)
502
503 if self == base_invoice:
504 return 'CREATE'
505 if base_invoice.amount_residual == 0 and all_invoices_residual_zero:
506 return 'STORNO'
507 return 'MODIFY'
508
509 def _l10n_hu_edi_upload_single_batch(self, connection):
510 try:
511 token_result = connection.do_token_exchange(self.company_id.sudo()._l10n_hu_edi_get_credentials_dict())
512 except L10nHuEdiConnectionError as e:
513 return self.write({
514 'l10n_hu_edi_state': 'rejected',
515 'l10n_hu_edi_transaction_code': False,
516 'l10n_hu_edi_messages': {
517 'error_title': _('Could not authenticate with NAV. Check your credentials and try again.'),
518 'errors': e.errors,
519 'blocking_level': 'error',
520 },
521 })
522
523 for i, invoice in enumerate(self, start=1):
524 invoice.l10n_hu_edi_batch_upload_index = i
525
526 invoice_operations = [
527 {
528 'index': invoice.l10n_hu_edi_batch_upload_index,
529 'operation': invoice._l10n_hu_edi_get_operation_type(),
530 'invoice_data': base64.b64decode(invoice.l10n_hu_edi_attachment),
531 }
532 for invoice in self
533 ]
534
535 self.write({'l10n_hu_edi_send_time': fields.Datetime.now()})
536
537 try:
538 transaction_code = connection.do_manage_invoice(
539 self.company_id.sudo()._l10n_hu_edi_get_credentials_dict(),
540 token_result['token'],
541 invoice_operations,
542 )
543 except L10nHuEdiConnectionError as e:
544 if e.code == 'timeout':
545 return self.write({
546 'l10n_hu_edi_state': 'send_timeout',
547 'l10n_hu_edi_transaction_code': False,
548 'l10n_hu_edi_messages': {
549 'error_title': _('Invoice submission timed out. Please wait at least 6 minutes, then update the status.'),
550 'errors': e.errors,
551 'blocking_level': 'warning',
552 },
553 })
554 return self.write({
555 'l10n_hu_edi_state': 'rejected',
556 'l10n_hu_edi_transaction_code': False,
557 'l10n_hu_invoice_chain_index': 0,
558 'l10n_hu_edi_messages': {
559 'error_title': _('Invoice submission failed.'),
560 'errors': e.errors,
561 'blocking_level': 'error',
562 },
563 })
564
565 self.write({
566 'l10n_hu_edi_state': 'sent',
567 'l10n_hu_edi_transaction_code': transaction_code,
568 'l10n_hu_edi_messages': {
569 'error_title': _('Invoice submitted, waiting for response.'),
570 'errors': [],
571 }
572 })
573
574 def _l10n_hu_edi_query_status(self, connection):
575 """ Check the NAV invoice status. """
576 # We should update all invoices with the same company and transaction code at once.
577 invoices = self | self.search([
578 ('company_id', 'in', self.company_id.ids),
579 ('l10n_hu_edi_transaction_code', 'in', self.mapped('l10n_hu_edi_transaction_code')),
580 ('l10n_hu_edi_state', 'in', ['sent', 'cancel_sent']),
581 ])
582
583 # Querying status should be grouped by company and transaction code
584 for __, invoices_grouped in groupby(invoices, lambda m: (m.company_id, m.l10n_hu_edi_transaction_code)):
585 self.env['account.move'].union(*invoices_grouped)._l10n_hu_edi_query_status_single_batch(connection)
586
587 def _l10n_hu_edi_query_status_single_batch(self, connection):
588 """ Check the NAV status for invoices that share the same transaction code (uploaded in a single batch). """
589 try:
590 results = connection.do_query_transaction_status(
591 self.company_id.sudo()._l10n_hu_edi_get_credentials_dict(),
592 self[0].l10n_hu_edi_transaction_code,
593 )
594 except L10nHuEdiConnectionError as e:
595 if self.l10n_hu_edi_state == 'sent':
596 return self.write({
597 'l10n_hu_edi_messages': {
598 'error_title': _('The invoice was sent to the NAV, but there was an error querying its status.'),
599 'errors': e.errors,
600 'blocking_level': 'warning',
601 },
602 })
603 else:
604 return self.write({
605 'l10n_hu_edi_messages': {
606 'error_title': _('The annulment was sent to the NAV, but there was an error querying its status.'),
607 'errors': e.errors,
608 'blocking_level': 'warning',
609 },
610 })
611
612 for processing_result in results['processing_results']:
613 invoice = self.filtered(lambda m: str(m.l10n_hu_edi_batch_upload_index) == processing_result['index'])
614 if not invoice:
615 _logger.error(_('Could not match NAV transaction_code %(code)s, index %(index)s to an invoice in Odoo',
616 code=self[0].l10n_hu_edi_transaction_code,
617 index=processing_result['index']))
618 continue
619
620 invoice._l10n_hu_edi_process_query_transaction_result(processing_result, results['annulment_status'])
621
622 def _l10n_hu_edi_process_query_transaction_result(self, processing_result, annulment_status):
623 def get_errors_from_processing_result(processing_result):
624 return [
625 f'({message["validation_result_code"]}) {message["validation_error_code"]}: {message["message"]}'
626 for message in processing_result.get('business_validation_messages', []) + processing_result.get('technical_validation_messages', [])
627 ]
628
629 self.ensure_one()
630
631 if processing_result['invoice_status'] in ['RECEIVED', 'PROCESSING', 'SAVED']:
632 # The invoice/annulment has not been processed yet.
633 if self.l10n_hu_edi_state in ['sent', 'send_timeout']:
634 self.write({
635 'l10n_hu_edi_state': 'sent',
636 'l10n_hu_edi_messages': {
637 'error_title': _('The invoice was received by the NAV, but has not been confirmed yet.'),
638 'errors': get_errors_from_processing_result(processing_result),
639 'blocking_level': 'warning',
640 },
641 })
642 elif self.l10n_hu_edi_state in ['cancel_sent', 'cancel_timeout']:
643 self.write({
644 'l10n_hu_edi_state': 'cancel_sent',
645 'l10n_hu_edi_messages': {
646 'error_title': _('The annulment request was received by the NAV, but has not been confirmed yet.'),
647 'errors': get_errors_from_processing_result(processing_result),
648 'blocking_level': 'warning',
649 },
650 })
651
652 elif processing_result['invoice_status'] == 'DONE':
653 if self.l10n_hu_edi_state in ['sent', 'send_timeout']:
654 if not processing_result['business_validation_messages'] and not processing_result['technical_validation_messages']:
655 self.write({
656 'l10n_hu_edi_state': 'confirmed',
657 'l10n_hu_edi_messages': {
658 'error_title': _('The invoice was successfully accepted by the NAV.'),
659 'errors': get_errors_from_processing_result(processing_result),
660 },
661 })
662 else:
663 self.write({
664 'l10n_hu_edi_state': 'confirmed_warning',
665 'l10n_hu_edi_messages': {
666 'error_title': _(
667 'The invoice was accepted by the NAV, but warnings were reported. '
668 'To reverse, create a credit note / debit note.'
669 ),
670 'errors': get_errors_from_processing_result(processing_result),
671 'blocking_level': 'warning',
672 },
673 })
674 elif self.l10n_hu_edi_state in ['cancel_sent', 'cancel_timeout', 'cancel_pending']:
675 if annulment_status == 'NOT_VERIFIABLE':
676 self.write({
677 'l10n_hu_edi_state': 'confirmed_warning',
678 'l10n_hu_edi_messages': {
679 'error_title': _('The annulment request was rejected by NAV.'),
680 'errors': get_errors_from_processing_result(processing_result),
681 'blocking_level': 'error',
682 },
683 })
684 elif annulment_status == 'VERIFICATION_PENDING':
685 self.write({
686 'l10n_hu_edi_state': 'cancel_pending',
687 'l10n_hu_edi_messages': {
688 'error_title': _('The annulment request is pending, please confirm it on the OnlineSzámla portal.'),
689 'errors': get_errors_from_processing_result(processing_result),
690 'blocking_level': 'warning',
691 }
692 })
693 elif annulment_status == 'VERIFICATION_DONE':
694 # Annulling a base invoice will also annul all its modification invoices on NAV.
695 to_cancel = self if self.reversed_entry_id or self.debit_origin_id else self._l10n_hu_get_chain_invoices().filtered(lambda m: m.l10n_hu_edi_state)
696 to_cancel.write({
697 'l10n_hu_edi_state': 'cancelled',
698 'l10n_hu_invoice_chain_index': 0,
699 'l10n_hu_edi_messages': {
700 'error_title': _('The annulment request has been approved by the user on the OnlineSzámla portal.'),
701 'errors': get_errors_from_processing_result(processing_result),
702 }
703 })
704 to_cancel.button_cancel()
705 elif annulment_status == 'VERIFICATION_REJECTED':
706 self.write({
707 'l10n_hu_edi_state': 'confirmed_warning',
708 'l10n_hu_edi_messages': {
709 'error_title': _('The annulment request was rejected by the user on the OnlineSzámla portal.'),
710 'errors': get_errors_from_processing_result(processing_result),
711 'blocking_level': 'error',
712 }
713 })
714
715 elif processing_result['invoice_status'] == 'ABORTED':
716 if self.l10n_hu_edi_state in ['sent', 'send_timeout']:
717 self.write({
718 'l10n_hu_edi_state': 'rejected',
719 'l10n_hu_invoice_chain_index': 0,
720 'l10n_hu_edi_messages': {
721 'error_title': _('The invoice was rejected by the NAV.'),
722 'errors': get_errors_from_processing_result(processing_result),
723 'blocking_level': 'error',
724 },
725 })
726 elif self.l10n_hu_edi_state in ['cancel_sent', 'cancel_timeout', 'cancel_pending']:
727 self.write({
728 'l10n_hu_edi_state': 'confirmed_warning',
729 'l10n_hu_edi_messages': {
730 'error_title': _('The cancellation request could not be performed.'),
731 'errors': get_errors_from_processing_result(processing_result),
732 'blocking_level': 'error',
733 },
734 })
735
736 def _l10n_hu_edi_request_cancel(self, connection, code, reason):
737 """ Send a cancellation request for all invoices in `self`. """
738 # Batch by company, with max 100 annulment requests per batch.
739 for __, batch_company in groupby(self, lambda m: m.company_id):
740 for batch in split_every(100, batch_company):
741 self.env['account.move'].union(*batch)._l10n_hu_edi_request_cancel_single_batch(connection, code, reason)
742
743 def _l10n_hu_edi_request_cancel_single_batch(self, connection, code, reason):
744 for i, invoice in enumerate(self, start=1):
745 invoice.l10n_hu_edi_batch_upload_index = i
746
747 annulment_operations = [
748 {
749 'index': invoice.l10n_hu_edi_batch_upload_index,
750 'annulmentReference': invoice.name,
751 'annulmentCode': code,
752 'annulmentReason': reason,
753 }
754 for invoice in self
755 ]
756
757 try:
758 token_result = connection.do_token_exchange(self.company_id.sudo()._l10n_hu_edi_get_credentials_dict())
759 except L10nHuEdiConnectionError as e:
760 return self.write({
761 'l10n_hu_edi_messages': {
762 'error_title': _('Could not authenticate with NAV. Check your credentials and try again.'),
763 'errors': e.errors,
764 'blocking_level': 'error',
765 },
766 })
767
768 self.write({'l10n_hu_edi_send_time': fields.Datetime.now()})
769
770 try:
771 transaction_code = connection.do_manage_annulment(
772 self.company_id.sudo()._l10n_hu_edi_get_credentials_dict(),
773 token_result['token'],
774 annulment_operations,
775 )
776 except L10nHuEdiConnectionError as e:
777 if e.code == 'timeout':
778 return self.write({
779 'l10n_hu_edi_state': 'cancel_timeout',
780 'l10n_hu_edi_messages': {
781 'error_title': _('Cancellation request timed out. Please wait at least 6 minutes, then update the status.'),
782 'errors': e.errors,
783 'blocking_level': 'warning',
784 },
785 })
786 return self.write({
787 'l10n_hu_edi_messages': {
788 'error_title': _('Cancellation request failed.'),
789 'errors': e.errors,
790 'blocking_level': 'error',
791 },
792 })
793
794 self.write({
795 'l10n_hu_edi_state': 'cancel_sent',
796 'l10n_hu_edi_transaction_code': transaction_code,
797 'l10n_hu_edi_messages': {
798 'error_title': _('Cancellation request submitted, waiting for response.'),
799 'errors': [],
800 }
801 })
802
803 # === EDI: XML generation === #
804
805 def _l10n_hu_edi_generate_xml(self):
806 invoice_data = self.env['ir.qweb']._render(
807 self._l10n_hu_edi_get_electronic_invoice_template(),
808 self._l10n_hu_edi_get_invoice_values(),
809 )
810 return etree.tostring(cleanup_xml_node(invoice_data, remove_blank_nodes=False), xml_declaration=True, encoding='UTF-8')
811
812 def _l10n_hu_edi_get_electronic_invoice_template(self):
813 """ For feature extensibility. """
814 return 'l10n_hu_edi.nav_online_invoice_xml_3_0'
815
816 def _l10n_hu_edi_get_invoice_values(self):
817 eu_country_codes = set(self.env.ref('base.europe').country_ids.mapped('code'))
818
819 def get_vat_data(partner, force_vat=None):
820 if partner.country_code == 'HU' or force_vat:
821 return {
822 'tax_number': partner.l10n_hu_group_vat or (force_vat or partner.vat),
823 'group_member_tax_number': partner.l10n_hu_group_vat and (force_vat or partner.vat),
824 }
825 elif partner.country_code in eu_country_codes:
826 return {'community_vat_number': partner.vat}
827 else:
828 return {'third_state_tax_id': partner.vat}
829
830 def format_bank_account_number(bank_account):
831 # Normalize IBANs (no spaces!)
832 if bank_account.acc_type == 'iban':
833 return normalize_iban(bank_account.acc_number)
834 else:
835 return bank_account.acc_number
836
837 supplier = self.company_id.partner_id
838 customer = self.partner_id.commercial_partner_id
839
840 supplier_bank = self.partner_bank_id if self.partner_bank_id and self.move_type == "out_invoice" else supplier.bank_ids[:1]
841 customer_bank = self.partner_bank_id if self.partner_bank_id and self.move_type == "out_refund" else customer.bank_ids[:1]
842
843 currency_huf = self.env.ref('base.HUF')
844 currency_rate = self._l10n_hu_get_currency_rate()
845
846 base_invoice = self._l10n_hu_get_chain_base()
847
848 invoice_values = {
849 'invoice': self,
850 'invoiceIssueDate': self.invoice_date,
851 'completenessIndicator': False,
852 'modifyWithoutMaster': False,
853 'base_invoice': base_invoice if base_invoice != self else None,
854 'supplier': supplier,
855 'supplier_vat_data': get_vat_data(supplier, self.fiscal_position_id.foreign_vat),
856 'supplierBankAccountNumber': format_bank_account_number(supplier_bank),
857 'individualExemption': self.company_id.l10n_hu_tax_regime == 'ie',
858 'customer': customer,
859 'customerVatStatus': (not customer.is_company and 'PRIVATE_PERSON') or (customer.country_code == 'HU' and 'DOMESTIC') or 'OTHER',
860 'customer_vat_data': get_vat_data(customer) if customer.is_company else None,
861 'customerBankAccountNumber': format_bank_account_number(customer_bank),
862 'smallBusinessIndicator': self.company_id.l10n_hu_tax_regime == 'sb',
863 'exchangeRate': currency_rate,
864 'cashAccountingIndicator': self.company_id.l10n_hu_tax_regime == 'ca',
865 'shipping_partner': self.partner_shipping_id,
866 'sales_partner': self.user_id,
867 'mergedItemIndicator': False,
868 'format_bool': format_bool,
869 'float_repr': float_repr,
870 'lines_values': [],
871 }
872
873 sign = 1.0 if self.is_inbound() else -1.0
874
875 prev_chain_invoices = base_invoice._l10n_hu_get_chain_invoices().filtered(
876 lambda m: m.l10n_hu_invoice_chain_index and m.l10n_hu_invoice_chain_index < self.l10n_hu_invoice_chain_index
877 )
878 first_line_number = sum(
879 len(move.line_ids.filtered(lambda l: l.display_type in ['product', 'rounding']))
880 for move in prev_chain_invoices
881 ) + 1
882
883 for (line_number, line) in enumerate(
884 self.line_ids.filtered(lambda l: l.display_type in ['product', 'rounding']).sorted(lambda l: l.display_type),
885 start=first_line_number,
886 ):
887 line_values = {
888 'line': line,
889 'lineNumber': line_number - first_line_number + 1,
890 'lineNumberReference': base_invoice != self and line_number,
891 'lineExpressionIndicator': line.product_id and line.product_uom_id,
892 'lineNatureIndicator': {False: 'OTHER', 'service': 'SERVICE'}.get(line.product_id.type, 'PRODUCT'),
893 'lineDescription': line.name.replace('\n', ' '),
894 }
895
896 if 'is_downpayment' in line and line.is_downpayment:
897 # Advance and final invoices.
898 line_values['advanceIndicator'] = True
899
900 if not self._is_downpayment():
901 # This is a final invoice that deducts one or more advance invoices.
902 # In this case, we add a reference to the *last-paid* advance invoice (NAV only allows us to report one) if one exists,
903 # otherwise we don't add anything.
904
905 advance_invoices = line._get_downpayment_lines().mapped('move_id').filtered(lambda m: m.state == 'posted')
906 reconciled_moves = advance_invoices._get_reconciled_amls().move_id
907 last_reconciled_payment = reconciled_moves.filtered(lambda m: m.origin_payment_id or m.statement_line_id).sorted('date', reverse=True)[:1]
908
909 if last_reconciled_payment:
910 line_values.update({
911 'advanceOriginalInvoice': advance_invoices.filtered(lambda m: last_reconciled_payment in m._get_reconciled_amls().move_id)[0].name,
912 'advancePaymentDate': last_reconciled_payment.date,
913 'advanceExchangeRate': last_reconciled_payment._l10n_hu_get_currency_rate(),
914 })
915
916 if line.display_type == 'product':
917 vat_tax = line.tax_ids.filtered(lambda t: t.l10n_hu_tax_type)
918
919 if line.quantity == 0.0 or line.discount == 100.0:
920 price_unit_signed = 0.0
921 else:
922 price_unit_signed = sign * line.price_subtotal / (1 - line.discount / 100) / line.quantity
923
924 price_net_signed = self.currency_id.round(price_unit_signed * line.quantity * (1 - line.discount / 100.0))
925 discount_value_signed = self.currency_id.round(price_unit_signed * line.quantity - price_net_signed)
926 price_total_signed = sign * line.price_total
927 vat_amount_signed = self.currency_id.round(price_total_signed - price_net_signed)
928
929 line_values.update({
930 'vat_tax': vat_tax,
931 'vatPercentage': float_round(vat_tax.amount / 100.0, 4),
932 'quantity': line.quantity,
933 'unitPrice': price_unit_signed,
934 'unitPriceHUF': currency_huf.round(price_unit_signed * currency_rate),
935 'discountValue': discount_value_signed,
936 'discountRate': line.discount / 100.0,
937 'lineNetAmount': price_net_signed,
938 'lineNetAmountHUF': currency_huf.round(price_net_signed * currency_rate),
939 'lineVatData': not self.currency_id.is_zero(vat_amount_signed),
940 'lineVatAmount': vat_amount_signed,
941 'lineVatAmountHUF': currency_huf.round(vat_amount_signed * currency_rate),
942 'lineGrossAmountNormal': price_total_signed,
943 'lineGrossAmountNormalHUF': currency_huf.round(price_total_signed * currency_rate),
944 })
945
946 elif line.display_type == 'rounding':
947 atk_tax = self.env['account.tax'].search(
948 [
949 ('type_tax_use', '=', 'sale'),
950 ('l10n_hu_tax_type', '=', 'ATK'),
951 ('company_id', '=', self.company_id.id),
952 ],
953 limit=1,
954 )
955 if not atk_tax:
956 raise UserError(_('Please create a sales tax with type ATK (outside the scope of the VAT Act).'))
957
958 amount_huf = line.balance if self.company_id.currency_id == currency_huf else currency_huf.round(line.amount_currency * currency_rate)
959 line_values.update({
960 'vat_tax': atk_tax,
961 'vatPercentage': float_round(atk_tax.amount / 100.0, 4),
962 'quantity': 1.0,
963 'unitPrice': -line.amount_currency,
964 'unitPriceHUF': -amount_huf,
965 'lineNetAmount': -line.amount_currency,
966 'lineNetAmountHUF': -amount_huf,
967 'lineVatData': False,
968 'lineGrossAmountNormal': -line.amount_currency,
969 'lineGrossAmountNormalHUF': -amount_huf,
970 })
971 line_values['lineDescription'] = line_values['lineDescription'] or line.product_id.display_name
972 invoice_values['lines_values'].append(line_values)
973
974 is_company_huf = self.company_id.currency_id == currency_huf
975 tax_amounts_by_tax = {
976 line.tax_line_id: {
977 'vatRateVatAmount': -line.amount_currency,
978 'vatRateVatAmountHUF': -line.balance if is_company_huf else currency_huf.round(-line.amount_currency * currency_rate),
979 }
980 for line in self.line_ids.filtered(lambda l: l.tax_line_id.l10n_hu_tax_type)
981 }
982
983 invoice_values['tax_summary'] = [
984 {
985 'vat_tax': vat_tax,
986 'vatPercentage': float_round(vat_tax.amount / 100.0, 4),
987 'vatRateNetAmount': self.currency_id.round(sum(l['lineNetAmount'] for l in lines_values_by_tax)),
988 'vatRateNetAmountHUF': currency_huf.round(sum(l['lineNetAmountHUF'] for l in lines_values_by_tax)),
989 'vatRateVatAmount': tax_amounts_by_tax.get(vat_tax, {}).get('vatRateVatAmount', 0.0),
990 'vatRateVatAmountHUF': tax_amounts_by_tax.get(vat_tax, {}).get('vatRateVatAmountHUF', 0.0),
991 }
992 for vat_tax, lines_values_by_tax in groupby(invoice_values['lines_values'], lambda l: l['vat_tax'])
993 ]
994
995 total_vat = self.currency_id.round(sum(tax_vals['vatRateVatAmount'] for tax_vals in invoice_values['tax_summary']))
996 total_vat_huf = currency_huf.round(sum(tax_vals['vatRateVatAmountHUF'] for tax_vals in invoice_values['tax_summary']))
997
998 total_gross = self.amount_total_in_currency_signed
999 total_gross_huf = self.amount_total_signed if is_company_huf else currency_huf.round(self.amount_total_in_currency_signed * currency_rate)
1000
1001 total_net = self.currency_id.round(total_gross - total_vat)
1002 total_net_huf = currency_huf.round(total_gross_huf - total_vat_huf)
1003
1004 invoice_values.update({
1005 'invoiceNetAmount': total_net,
1006 'invoiceNetAmountHUF': total_net_huf,
1007 'invoiceVatAmount': total_vat,
1008 'invoiceVatAmountHUF': total_vat_huf,
1009 'invoiceGrossAmount': total_gross,
1010 'invoiceGrossAmountHUF': total_gross_huf,
1011 })
1012
1013 return invoice_values
1014
1015 # === PDF generation === #
1016
1017 def _get_name_invoice_report(self):
1018 self.ensure_one()
1019 return 'l10n_hu_edi.report_invoice_document' if self.country_code == 'HU' else super()._get_name_invoice_report()
1020
1021 def _l10n_hu_get_invoice_totals_for_report(self):
1022 """ In Hungary, tax amounts should appear negative on credit notes.
1023 We therefore apply a post-processing to the tax totals to make them negative. """
1024
1025 def invert_dict(dictionary, keys_to_invert):
1026 """ Replace the values of keys_to_invert by their negative. """
1027 dictionary.update({
1028 key: -value
1029 for key, value in dictionary.items()
1030 if key in keys_to_invert
1031 })
1032
1033 self.ensure_one()
1034 tax_totals = self.tax_totals
1035 if not tax_totals:
1036 return tax_totals
1037
1038 fields_to_reverse = (
1039 'base_amount_currency', 'base_amount',
1040 'display_base_amount_currency', 'display_base_amount',
1041 'tax_amount_currency', 'tax_amount',
1042 'total_amount_currency', 'total_amount',
1043 'cash_rounding_base_amount_currency', 'cash_rounding_base_amount',
1044 )
1045
1046 if self.move_type in ('out_refund', 'in_refund'):
1047 invert_dict(tax_totals, fields_to_reverse)
1048 for subtotal in tax_totals['subtotals']:
1049 invert_dict(subtotal, fields_to_reverse)
1050 for tax_group in subtotal['tax_groups']:
1051 invert_dict(tax_group, fields_to_reverse)
1052
1053 currency_huf = self.env.ref('base.HUF')
1054 tax_totals['total_vat_amount_in_huf'] = sum(
1055 line.balance for line in self.line_ids.filtered(lambda l: l.tax_line_id.l10n_hu_tax_type)
1056 ) * (1 if self.is_purchase_document() else -1)
1057 tax_totals['formatted_total_vat_amount_in_huf'] = formatLang(
1058 self.env, tax_totals['total_vat_amount_in_huf'], currency_obj=currency_huf
1059 )
1060
1061 return tax_totals