Debian Codegraph @

addons/l10n_my_edi/models/myinvois_document.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 import base64
3 import datetime
4 import re
5 import time
6 from collections import defaultdict
7
8 import dateutil
9 import werkzeug
10 from lxml import etree
11
12 from odoo import SUPERUSER_ID, api, fields, models, modules
13 from odoo.exceptions import UserError
14 from odoo.fields import Domain
15 from odoo.tools import config, date_utils, split_every
16 from odoo.tools.image import image_data_uri
17
18 from odoo.addons.account.tools import dict_to_xml
19
20 # Holds the maximum amount of records that can be sent in a single submission.
21 SUBMISSION_MAX_SIZE = 100
22 MAX_SUBMISSION_UPDATE = 25
23 CANCELLED_STATES = {'invalid', 'cancelled'}
24
25
26 class MyInvoisDocument(models.Model):
27 """
28 Represents a single document on the MyInvois platform.
29
30 In Odoo, a document represent either an invoice, or a group of PoS order.
31 """
32 _name = 'myinvois.document'
33 _inherit = ['mail.thread', 'mail.activity.mixin', 'sequence.mixin']
34 _description = "MyInvois Document"
35 _order = "myinvois_issuance_date desc, id desc"
36 _check_company_auto = True
37 _sequence_date_field = "myinvois_issuance_date"
38
39 # ------------------
40 # Fields declaration
41 # ------------------
42
43 name = fields.Char(
44 compute='_compute_name',
45 store=True,
46 copy=False,
47 index='trigram',
48 )
49 active = fields.Boolean(
50 string="Active",
51 default=True,
52 )
53 company_id = fields.Many2one(
54 comodel_name="res.company",
55 required=True,
56 readonly=True,
57 default=lambda self: self.env.company,
58 )
59 currency_id = fields.Many2one(
60 comodel_name='res.currency',
61 required=True,
62 )
63 company_currency_id = fields.Many2one(
64 string='Company Currency',
65 related='company_id.currency_id',
66 )
67 myinvois_issuance_date = fields.Date(
68 string="Issuance Date",
69 readonly=True,
70 copy=False,
71 )
72 # File fields
73 myinvois_file_id = fields.Many2one(
74 comodel_name='ir.attachment',
75 compute=lambda self: self._compute_linked_attachment_id('myinvois_file_id', 'myinvois_file'),
76 depends=['myinvois_file'],
77 copy=False,
78 export_string_translation=False,
79 )
80 myinvois_file = fields.Binary(
81 string='MyInvois XML File',
82 copy=False,
83 readonly=True,
84 export_string_translation=False,
85 )
86 # Odoo Implementation fields
87 myinvois_state = fields.Selection(
88 string='MyInvois State',
89 help='State of this document on the MyInvois portal.\nA document awaiting validation will be automatically updated once the validation status is available.',
90 selection=[
91 ('in_progress', 'Validation In Progress'),
92 ('valid', 'Valid'),
93 ('rejected', 'Rejected'), # Technically not a state on MyInvois, but having it here helps with managing bills.
94 ('invalid', 'Invalid'),
95 ('cancelled', 'Cancelled'),
96 ],
97 copy=False,
98 readonly=True,
99 tracking=True,
100 )
101 myinvois_error_document_hash = fields.Char(
102 string="Document Hash",
103 copy=False,
104 readonly=True,
105 export_string_translation=False,
106 )
107 myinvois_retry_at = fields.Char(
108 string="Document Retry At",
109 copy=False,
110 readonly=True,
111 export_string_translation=False,
112 )
113 myinvois_exemption_reason = fields.Char(
114 string="Tax Exemption Reason",
115 help="Buyer’s sales tax exemption certificate number, special exemption as per gazette orders, etc.\n"
116 "Only applicable if you are using a tax with a type 'Exempt'.",
117 )
118 myinvois_custom_form_reference = fields.Char(
119 string="Customs Form Reference Number",
120 help="Reference Number of Customs Form No.1, 9, etc.",
121 )
122 # API information fields
123 myinvois_submission_uid = fields.Char(
124 string='Submission UID',
125 help="Unique ID assigned to a batch of documents when sent to MyInvois.",
126 copy=False,
127 readonly=True,
128 )
129 myinvois_external_uuid = fields.Char(
130 string="MyInvois ID",
131 help="Unique ID assigned to a specific document when sent to MyInvois.",
132 copy=False,
133 index=True,
134 readonly=True,
135 )
136 myinvois_validation_time = fields.Datetime(
137 string='Validation Time',
138 copy=False,
139 readonly=True,
140 )
141 myinvois_document_long_id = fields.Char(
142 string="MyInvois Long ID",
143 copy=False,
144 readonly=True,
145 )
146 # Note: the field is present but unused for now.
147 invoice_ids = fields.Many2many(
148 name="Invoices",
149 comodel_name="account.move",
150 relation="myinvois_document_invoice_rel",
151 column1="document_id",
152 column2="invoice_id",
153 check_company=True,
154 )
155
156 # --------------------------------
157 # Compute, inverse, search methods
158 # --------------------------------
159
160 @api.depends('myinvois_issuance_date')
161 def _compute_name(self):
162 """ Compute the name by using the sequence mixin. """
163 for document in self.sorted(key=lambda d: (d.myinvois_issuance_date, d._origin.id)):
164 document_has_name = document.name and document.name != '/'
165 if document_has_name:
166 if not document._sequence_matches_date():
167 document.name = False
168 continue
169 if document.myinvois_issuance_date and not document_has_name:
170 document._set_next_sequence()
171
172 self.filtered(lambda m: not m.name).name = '/'
173
174 def _compute_linked_attachment_id(self, attachment_field, binary_field):
175 """
176 Helper to retrieve Attachment from Binary fields
177 This is needed because fields.Many2one('ir.attachment') makes all
178 attachments available to the user.
179 """
180 attachments = self.env['ir.attachment'].search([
181 ('res_model', '=', self._name),
182 ('res_id', 'in', self.ids),
183 ('res_field', '=', binary_field),
184 ])
185 attachments_per_res_id = attachments.grouped('res_id')
186 for document in self:
187 document[attachment_field] = attachments_per_res_id.get(document._origin.id, False)
188
189 @api.depends('name')
190 def _compute_display_name(self):
191 for document in self:
192 document.display_name = document.name if document.name != '/' else document.env._('Draft')
193
194 # -----------------------
195 # CRUD, inherited methods
196 # -----------------------
197
198 def _get_starting_sequence(self):
199 """ Defines the default sequence to use by MyInvois Documents. """
200 self.ensure_one()
201 return "MYINV/%04d/00000" % self.myinvois_issuance_date.year
202
203 def _get_last_sequence_domain(self, relaxed=False):
204 """ Returns the SQL WHERE statement to use when fetching the latest record with the same sequence, and its params. """
205 self.ensure_one()
206 if not self.myinvois_issuance_date:
207 return "WHERE FALSE", {}
208 where_string = "WHERE name != '/'"
209 param = {}
210
211 if not relaxed:
212 domain = [('id', '!=', self.id or self._origin.id), ('name', 'not in', ('/', '', False))]
213 reference_name = self.sudo().search(domain + [('myinvois_issuance_date', '<=', self.myinvois_issuance_date)], limit=1).name
214 if not reference_name:
215 reference_name = self.sudo().search(domain, order='myinvois_issuance_date asc', limit=1).name
216 sequence_number_reset = self._deduce_sequence_number_reset(reference_name)
217 date_start, date_end, *_ = self._get_sequence_date_range(sequence_number_reset)
218 where_string += """ AND myinvois_issuance_date BETWEEN %(date_start)s AND %(date_end)s"""
219 param['date_start'] = date_start
220 param['date_end'] = date_end
221 if sequence_number_reset in ('year', 'year_range'):
222 param['anti_regex'] = re.sub(r"\?P<\w+>", "?:", self._sequence_monthly_regex.split('(?P<seq>')[0]) + '$'
223 elif sequence_number_reset == 'never':
224 param['anti_regex'] = re.sub(r"\?P<\w+>", "?:", self._sequence_yearly_regex.split('(?P<seq>')[0]) + '$'
225
226 if param.get('anti_regex'):
227 where_string += " AND sequence_prefix !~ %(anti_regex)s "
228
229 return where_string, param
230
231 def _get_sequence_date_range(self, reset):
232 """ Make sure that the sequence date range follows the company's fiscal year """
233 if reset == 'year_range':
234 company = self.company_id
235 return date_utils.get_fiscal_year(self.myinvois_issuance_date, day=company.fiscalyear_last_day, month=int(company.fiscalyear_last_month))
236 return super()._get_sequence_date_range(reset)
237
238 @api.ondelete(at_uninstall=False)
239 def _unlink_check(self):
240 for document in self:
241 if document.myinvois_state in ["in_progress", "valid", "rejected"]:
242 raise UserError(document.env._('You cannot delete a document that is active on MyInvois.\nYou must cancel it first.'))
243
244 # --------------
245 # Action methods
246 # --------------
247
248 def action_submit_to_myinvois(self):
249 """
250 Submit all new documents in self to MyInvois.
251 This can also be used on invalid documents to re-submit them after correcting the error.
252 """
253 documents = self.filtered(lambda d: d.myinvois_state in [False, 'invalid'])
254 if not documents:
255 return
256
257 # Documents linked to an invoice, and whose invoice is cancelled or draft, shouldn't be sent.
258 invalid_documents = documents.filtered(lambda d: d.invoice_ids and any(invoice.state in ('draft', 'cancel') for invoice in d.invoice_ids))
259 if invalid_documents:
260 raise UserError(self.env._('You cannot send this document to MyInvois because the related invoice(s) %s are in draft or canceled state.', ','.join(invalid_documents.mapped('name'))))
261
262 # Required for the file, this is the exact date at which the consolidated invoice was sent to MyInvois.
263 documents.myinvois_issuance_date = fields.Date.context_today(documents)
264 documents._submit_to_myinvois()
265
266 def action_update_submission_status(self):
267 """
268 Fetches the status of all the documents in self.
269 Note that the endpoint reached to do so will differ based on the amount of documents in the recordset.
270 """
271 if len(self) == 1:
272 self._myinvois_single_status_update()
273 else:
274 self._myinvois_submission_statuses_update()
275
276 def action_generate_xml_file(self):
277 """
278 Generate a xml file for each of the MyInvois documents in self.
279 If the document already as a file, the previous file's name is updated to include an (old) tag to avoid confusion in the attachment list.
280 """
281 new_documents_data = []
282 for document in self:
283 if document.myinvois_file_id:
284 document.myinvois_file_id.write({
285 'name': f"{document.myinvois_file_id.name} (old)",
286 'res_field': False, # Remove the link between the old attachment and the record's field
287 })
288
289 xml_data, errors = document._myinvois_generate_xml_file()
290 if errors:
291 raise UserError(document.env._("Error when generating the documents' files:\n\n- %(errors)s", errors='\n- '.join(errors)))
292
293 new_documents_data.append({
294 "name": f'{document.name.replace("/", "_")}_myinvois.xml' if document.name != "/" else "myinvois.xml",
295 "raw": xml_data,
296 "mimetype": "application/xml",
297 "res_model": document._name,
298 "res_id": document.id,
299 "res_field": "myinvois_file",
300 })
301
302 self.env["ir.attachment"].with_user(SUPERUSER_ID).create(new_documents_data)
303 self.invalidate_recordset(fnames=['myinvois_file_id', 'myinvois_file'])
304
305 def action_cancel_submission(self):
306 """ Cancel the document on the platform. """
307 self.ensure_one()
308 return self._action_myinvois_update_document(new_status='cancelled')
309
310 def action_show_myinvois_documents(self):
311 """ Open the documents in self in the correct view based on the amount of records. """
312 if len(self) == 1:
313 action_vals = {
314 'type': 'ir.actions.act_window',
315 'res_model': 'myinvois.document',
316 'view_mode': 'form',
317 'res_id': self.id,
318 'views': [(self.env.ref('l10n_my_edi.myinvois_document_form_view').id, 'form')],
319 }
320 else:
321 action_vals = {
322 'name': self.env._("Consolidated Invoices"),
323 'type': 'ir.actions.act_window',
324 'res_model': 'myinvois.document',
325 'view_mode': 'list,form',
326 'views': [(self.env.ref('l10n_my_edi.myinvois_document_list_view').id, 'list'), (self.env.ref('l10n_my_edi.myinvois_document_form_view').id, 'form')],
327 'domain': [('id', 'in', self.ids)],
328 }
329 return action_vals
330
331 # ----------------
332 # Business methods
333 # ----------------
334
335 # Most of the logic here is written to work regardless of the linked document;
336
337 def _myinvois_get_proxy_user(self):
338 """
339 Models implementing the mixin should define the logic to get the record's proxy user here.
340 Typically, the one linked to the record's company.
341 :return: The proxy user that should be used to send the record to MyInvois.
342 """
343 self.ensure_one()
344 company = self.company_id or self.env.company
345
346 proxy_user = company.sudo().l10n_my_edi_proxy_user_id
347 if not proxy_user:
348 raise UserError(self.env._("Please register for the E-Invoicing service in the settings first."))
349
350 return proxy_user
351
352 def _myinvois_log_message(self, message=None, bodies=None):
353 """
354 Small helper to use when logging in the chatter to automatically broadcast the message to the invoice.
355
356 Supports receiving a simple message string, or a dict of bodies targeted to self.
357 """
358 if message:
359 self._message_log_batch(bodies={document.id: message for document in self})
360 if self.invoice_ids:
361 self.invoice_ids._message_log_batch(bodies={move.id: message for move in self.invoice_ids})
362
363 documents_per_id = self.grouped('id')
364 if bodies:
365 self._message_log_batch(bodies=bodies)
366 if self.invoice_ids:
367 invoice_bodies = {}
368 for document_id, message in bodies.items():
369 invoice_bodies.update({invoice.id: message for invoice in documents_per_id[document_id].invoice_ids})
370 self.invoice_ids._message_log_batch(bodies=invoice_bodies)
371
372 @api.model
373 def _myinvois_map_error(self, error):
374 """ This helper will take in an error code coming from the proxy, and return a translatable error message. """
375 error_map = {
376 # These errors should be returned when we send malformed request to the EDI, ... tldr; this should never happen unless we have bugs.
377 "internal_server_error": self.env._(
378 "Server error; If the problem persists, please contact the Odoo support."
379 ),
380 # The proxy user credentials are either incorrect, or Odoo does not have the permission to invoice on their behalf.
381 "invalid_tin": self.env._(
382 "Please make sure that your company TIN is correct, and that you gave Odoo sufficient permissions on the MyInvois platform."
383 ),
384 # The api rate limit has been reached. If this happens, we need to ask the user to wait. This is also handled proxy side to be safe
385 "rate_limit_exceeded": self.env._(
386 "The api request limit has been reached. Please wait until %(limit_reset_datetime)s to try again.",
387 limit_reset_datetime=error.get("data"),
388 ), # Note, should be UTC. The TZ name is present in the formatted date.
389 "hash_resubmitted": self.env._(
390 "This document has already been submitted and was deemed invalid.\n"
391 "Please correct the document based on the previous error, or wait before retrying."
392 ),
393 # This happens when the MyInvois TIN validator cannot validate the TIN of the user using the provided identification type and number.
394 "document_tin_not_found": self.env._(
395 "MyInvois could not match your TIN with the identification information you provided on the company."
396 ),
397 # This happens when the TIN of the supplier doesn't match with the TIN registered on the Proxy. Data contains the TIN.
398 "document_tin_mismatch": self.env._(
399 "The TIN number of the supplier in the invoices does not match with the one provided at the time of registering for the e-invoice service.\n"
400 "If the TIN of the supplier's record changed after that, you will need to archive your EDI Proxy User and re-register.\n"
401 "The TIN found in the document is %(tin_number)s",
402 tin_number=error.get("data"),
403 ),
404 # This happens when a batch of invoices contains multiple different identifier for the supplier. Data contains the invoice.
405 "multiple_documents_id": self.env._(
406 "Multiple different supplier identification information were found in the invoices.\n"
407 "If the company identification information changed, you may need to delete your invoice attachments and regenerate them."
408 ),
409 # Same as the previous error, but with the supplier TIN
410 "multiple_documents_tin": self.env._(
411 "Multiple different supplier TIN were found in the invoices.\n"
412 "If the company TIN changed, you may need to delete your invoice attachments and regenerate them."
413 ),
414 # You cannot cancel an invoice that has been rejected or that is invalid
415 "update_incorrect_state": self.env._(
416 "You can only update the status of invoices in the valid state."
417 ),
418 "update_period_over": self.env._(
419 "It has been more than 72h since the invoice validation, you can no longer update it.\n"
420 "Instead, you should issue or request a debit or credit note."
421 ),
422 "update_active_documents": self.env._(
423 "You cannot update this invoice, has it has been referenced by a debit or credit note.\n"
424 "If you still want to update it, you must first update the debit/credit note."
425 ),
426 "update_forbidden": self.env._("You do not have the permission to update this invoice."),
427 "search_date_invalid": self.env._("The search params are invalid."), # Should never happen
428 'document_not_found': self.env._('The document provided in the request does not exist.'), # Should never happen
429 'submission_too_large': self.env._('The submission is too large, try to send fewer invoices at once.'),
430 'action_forbidden': self.env._('Permission to do this action has not been granted. Please ensure that Odoo has sufficient permissions on the MyInvois platform.'),
431 }
432
433 if error.get('target'):
434 # When validating a part of the invoice, they give random numerical codes with no explanation whatsoever.
435 # So instead of trying to guess what they mean, we just give a generic "this is not valid" error and hope for the best.
436 # For future bugfixer => To avoid issues as much as possible, please add additional checks in the UBL python file to avoid these.
437 return self.env._('An error occurred while validating the invoice: "%(property_name)s" is invalid.', property_name=error['target'])
438
439 return error_map.get(error['reference'], self.env._("An unexpected error has occurred."))
440
441 @staticmethod
442 def _can_commit():
443 """ Helper to know if we can commit the current transaction or not.
444
445 :returns: True if commit is acceptable, False otherwise.
446 """
447 return not config['test_enable'] and not modules.module.current_test
448
449 def _get_mail_thread_data_attachments(self):
450 res = super()._get_mail_thread_data_attachments()
451 # else, attachments with 'res_field' get excluded
452 return res | self.myinvois_file_id
453
454 def _get_active_myinvois_document(self, including_in_progress=False):
455 """
456 Returns the first document in self that is considered active on the platform.
457 An active document is a document that has been successfully sent, but no cancelled.
458
459 There are no flows at the moment where we intend to have more than one active document at a time
460 for a specific record.
461
462 :param including_in_progress: if set to true, invoices of state in_progress will be included.
463 """
464 active_states = ['valid', 'rejected'] + (['in_progress'] if including_in_progress else [])
465 return self.filtered(lambda d: d.myinvois_state in active_states)[:1]
466
467 def _generate_myinvois_qr_code(self):
468 """ Generate the qr code for which can be used to access this document. """
469 self.ensure_one()
470
471 if not self.myinvois_document_long_id: # Only valid invoices have a long id
472 return None
473
474 # We need to add the portal url to the qr
475 proxy_user = self._myinvois_get_proxy_user()
476 if proxy_user.edi_mode == 'prod':
477 portal_url = "myinvois.hasil.gov.my"
478 else:
479 portal_url = "preprod.myinvois.hasil.gov.my"
480
481 try:
482 qr_code = self.env['ir.actions.report'].barcode(
483 barcode_type='QR',
484 width=128,
485 height=128,
486 humanreadable=1,
487 value=f'https://{portal_url}/{self.myinvois_external_uuid}/share/{self.myinvois_document_long_id}',
488 )
489 except (ValueError, AttributeError):
490 raise werkzeug.exceptions.HTTPException(description='Cannot convert into QR Code.')
491
492 return image_data_uri(base64.b64encode(qr_code))
493
494 def _is_refund_document(self):
495 """
496 :return: True if this document is linked to a single refund invoice.
497 """
498 has_single_document = self.invoice_ids and len(self.invoice_ids) == 1
499 return has_single_document and self.invoice_ids[0].move_type in ('out_refund', 'in_refund')
500
501 def _get_rounded_base_lines(self):
502 """
503 The base lines used when exporting the document will highly differ based on whether this is
504 or not a consolidated invoice, as well as whether this is for PoS.
505
506 :return: The rounded base lines to be used when exporting the document.
507 """
508 self.ensure_one()
509 # Refunds of consolidated invoices are treated as regular invoice besides for the fixed customer.
510 if self._is_consolidated_invoice():
511 AccountTax = self.env['account.tax']
512 grouped_records = self._split_consolidated_invoice_record_in_lines()
513
514 tax_data_fields = (
515 "raw_base_amount_currency",
516 "raw_base_amount",
517 "raw_tax_amount_currency",
518 "raw_tax_amount",
519 "base_amount_currency",
520 "base_amount",
521 "tax_amount_currency",
522 "tax_amount",
523 )
524 consolidated_base_lines = []
525 for index, records in enumerate(grouped_records):
526 base_lines = []
527 for record in records:
528 base_lines += self._get_record_rounded_base_lines(record)
529
530 # Aggregate the base lines into one.
531 new_tax_details = {
532 "raw_total_excluded_currency": 0.0,
533 "total_excluded_currency": 0.0,
534 "raw_total_excluded": 0.0,
535 "total_excluded": 0.0,
536 "raw_total_included_currency": 0.0,
537 "total_included_currency": 0.0,
538 "raw_total_included": 0.0,
539 "total_included": 0.0,
540 "delta_total_excluded_currency": 0.0,
541 "delta_total_excluded": 0.0,
542 }
543 new_taxes_data_map = {}
544
545 taxes = self.env["account.tax"]
546 for base_line in base_lines:
547 tax_details = base_line["tax_details"]
548 sign = -1 if base_line["is_refund"] else 1
549 for key in new_tax_details:
550 new_tax_details[key] += sign * tax_details[key]
551 for tax_data in tax_details["taxes_data"]:
552 tax = tax_data["tax"]
553 taxes |= tax
554 if tax in new_taxes_data_map:
555 for key in tax_data_fields:
556 new_taxes_data_map[tax][key] += sign * tax_data[key]
557 else:
558 new_taxes_data_map[tax] = dict(tax_data)
559 for key in tax_data_fields:
560 new_taxes_data_map[tax][key] = sign * tax_data[key]
561
562 total_amount_discounted = new_tax_details["total_excluded"] + new_tax_details["delta_total_excluded"]
563 total_amount_discounted_currency = new_tax_details["total_excluded_currency"] + new_tax_details["delta_total_excluded_currency"]
564 total_amount = total_amount_currency = 0.0
565 for base_line in base_lines:
566 sign = -1 if base_line["is_refund"] else 1
567 total_amount += sign * (
568 (base_line["price_unit"] / base_line["rate"])
569 * base_line["quantity"]
570 )
571 total_amount_currency += sign * (
572 base_line["price_unit"] * base_line["quantity"]
573 )
574
575 # Only compute discount if any base_line has an actual discount percentage
576 has_discount = any(base_line['discount'] for base_line in base_lines)
577 discount_amount = (total_amount - total_amount_discounted) if has_discount else 0.0
578 discount_amount_currency = (total_amount_currency - total_amount_discounted_currency) if has_discount else 0.0
579
580 # for the line name, when consolidating, we want to show first sequence - last sequence
581 sequenced_records = records.sorted(key=lambda r: r.name)
582 new_base_line = AccountTax._prepare_base_line_for_taxes_computation(
583 {},
584 tax_ids=taxes,
585 price_unit=total_amount_currency,
586 discount_amount=discount_amount,
587 discount_amount_currency=discount_amount_currency,
588 quantity=1.0,
589 currency_id=self.currency_id,
590 tax_details={
591 **new_tax_details,
592 "taxes_data": list(new_taxes_data_map.values()),
593 },
594 line_name=f"{sequenced_records[0].name}-{sequenced_records[-1].name}" if len(sequenced_records) > 1 else sequenced_records[0].name,
595 )
596 consolidated_base_lines.append(new_base_line)
597
598 base_lines = consolidated_base_lines
599 else:
600 invoice = self.invoice_ids[0] # Otherwise it would be a consolidated invoice.
601 base_lines, _tax_lines = invoice._get_rounded_base_and_tax_lines()
602 # In any cases, we'll provide a reference to the document in the base lines.
603 # This will help later on when it is time to handle tax grouping as we may need to get the
604 # tax exemption info.
605 for base_line in base_lines:
606 base_line['myinvois_document'] = self
607
608 return base_lines
609
610 # Consolidated invoices helpers.
611
612 def _is_consolidated_invoice(self):
613 """
614 In a few flows, we need to know if we're dealing with a consolidated invoice in order to set
615 the correct customer for example.
616 This method is here for that; in practice we will be dealing with a consolidated invoice when:
617 - The document is linked to multiple records or;
618 - The document is a refund/credit note of another document linked to multiple records.
619
620 :return: True if this invoice is a consolidated invoice or the refund of one.
621 """
622 self.ensure_one()
623 return len(self.invoice_ids) > 1
624
625 def _is_consolidated_invoice_refund(self):
626 """
627 :return: True if this document is a refund specifically for a consolidated invoice.
628 """
629 is_consolidated_invoice_refund = False
630 if self._is_refund_document():
631 refunded_invoice = self.invoice_ids.reversed_entry_id
632 refunded_document = refunded_invoice.l10n_my_edi_document_ids._get_active_myinvois_document(including_in_progress=True)
633 is_consolidated_invoice_refund = len(refunded_document.invoice_ids) > 1
634 return is_consolidated_invoice_refund
635
636 def _split_consolidated_invoice_record_in_lines(self):
637 """
638 When dealing with consolidated invoices, all continuous records are grouped in a single line,
639 with a split happening only when the continuity is broken (a document was sent individually,...)
640
641 The role of this method is to handle this grouping so that it can be used later when preparing the
642 base lines for export.
643
644 :return: a list of recordset containing the related records split into one recordset per line.
645 """
646 if not self._is_consolidated_invoice() or not self.invoice_ids:
647 return []
648
649 # We will be working on that soon, but for now we do not support it.
650 raise NotImplementedError("Support for consolidated invoices in the invoicing app is not yet implemented.")
651
652 def _get_record_rounded_base_lines(self, record):
653 """
654 Little helper to return the rounded base line for a record.
655 It is extracted in order to allow extending the logic to support other business models.
656 :param record: The record from which to get the base lines.
657 :return: The rounder base line for the provided record.
658 """
659 self.ensure_one()
660 record.ensure_one()
661 base_lines = []
662 if record and record._name == 'account.move':
663 base_lines, _tax_lines = record._get_rounded_base_and_tax_lines()
664 return base_lines
665
666 # Submission
667
668 def _myinvois_submit_documents(self, submissions_content):
669 """
670 Contact our IAP service in order to send the current document's xml to the MyInvois API.
671 Only records in self having a xml_file_content in xml_contents will be sent.
672
673 Please mind that the logic will commit for each batch being sent to the platform.
674
675 :param submissions_content: A dict of the format {record: {'name': '', 'xml': ''}}
676 :return: a dict of potential errors in the format {record: errors_list}
677 """
678 def _format_error_messages(errors_list):
679 AccountMoveSend = self.env['account.move.send']
680 error_data = {
681 'error_title': self.env._("Error when sending the documents to the E-invoicing service."),
682 'errors': errors_list,
683 }
684 return {
685 'html_error': AccountMoveSend._format_error_html(error_data),
686 'plain_text_error': AccountMoveSend._format_error_text(error_data),
687 }
688
689 records_to_send = self.filtered(lambda record: record in submissions_content)
690 if not records_to_send:
691 return None
692
693 # Ensure to lock the records that will be sent, to avoid risking sending them twice.
694 self.env['res.company']._with_locked_records(records_to_send)
695
696 error_messages = {}
697 success_messages = {}
698 invoice_to_cancel = self.env['account.move']
699
700 # We will group per proxy_user, then batch the records in batches of SUBMISSION_MAX_SIZE
701 records_per_proxy_users = records_to_send.grouped(lambda r: r._myinvois_get_proxy_user())
702
703 # MyInvois only supports up to 100 document per submission. To avoid timing out on big batches, we split it client side.
704 for proxy_user, records_to_send in records_per_proxy_users.items():
705 for batch in split_every(SUBMISSION_MAX_SIZE, records_to_send.ids, self.env['myinvois.document'].browse):
706 batch_result = proxy_user._l10n_my_edi_contact_proxy(
707 endpoint='api/l10n_my_edi/1/submit_invoices',
708 params={
709 'documents': [{
710 'move_id': record.id,
711 'move_name': submissions_content[record]['name'],
712 'error_document_hash': record.myinvois_error_document_hash,
713 'retry_at': record.myinvois_retry_at,
714 'data': base64.b64encode(submissions_content[record]['xml'].encode()).decode(),
715 } for record in batch],
716 },
717 )
718 # If an error is present in the result itself (and not per document), it means that the whole submission failed.
719 # We don't add to the result but instead directly in the errors.
720 if 'error' in batch_result:
721 error_string = self._myinvois_map_error(batch_result['error'])
722 error_messages.update({record.id: _format_error_messages([error_string]) for record in batch})
723 else:
724 records_per_id = batch.grouped('id')
725 for document_result in batch_result['documents']:
726 record = records_per_id[document_result['move_id']]
727 success = document_result['success']
728
729 updated_values = {
730 'myinvois_external_uuid': document_result.get('uuid'), # rejected documents do not have an uuid.
731 'myinvois_submission_uid': batch_result['submission_uid'],
732 'myinvois_state': 'in_progress' if success else 'invalid',
733 }
734
735 if success:
736 # Ids are logged for future references. An invalid document may be reset to resend it after correction, which would be a new submission/uuid.
737 success_messages[record.id] = self.env._('The document has been sent to MyInvois with uuid "%(uuid)s" and submission id "%(submission_id)s".\nValidation results will be available shortly.',
738 uuid=document_result['uuid'], submission_id=batch_result['submission_uid'])
739 else:
740 # When we raise a "hash_resubmitted" error, we don't resend the same hash/retry at and don't want to rewrite.
741 if 'error_document_hash' in document_result:
742 updated_values.update({
743 'myinvois_error_document_hash': document_result['error_document_hash'],
744 'myinvois_retry_at': document_result['retry_at'],
745 })
746 error_messages[record.id] = _format_error_messages([self._myinvois_map_error(error) for error in document_result['errors']])
747 if self.invoice_ids:
748 invoice_to_cancel |= self.invoice_ids
749
750 record.write(updated_values)
751
752 if self._can_commit():
753 self.env.cr.commit()
754
755 if success_messages:
756 successful_records = self.browse(list(success_messages.keys()))
757 successful_records._myinvois_log_message(
758 bodies=success_messages,
759 )
760 if error_messages:
761 unsuccessful_records = self.browse(list(error_messages.keys()))
762 unsuccessful_records._myinvois_log_message(
763 bodies={rid: msg['html_error'] for rid, msg in error_messages.items()},
764 )
765
766 if invoice_to_cancel:
767 # Invalid moves should be considered as cancelled; they need to be reset to draft, corrected and sent again.
768 invoice_to_cancel._l10n_my_edi_cancel_moves()
769
770 return error_messages
771
772 def _myinvois_get_submission_status(self):
773 """
774 Fetches the status of the submissions in self.
775
776 :return: A dict of the format: {submission_uid: {'error': '', 'statuses': {record: document_statuses}}}
777 """
778 def _make_deep_default_dict():
779 return defaultdict(_make_deep_default_dict)
780
781 if not self:
782 return None
783
784 results = _make_deep_default_dict()
785 for proxy_user, records in self.grouped(lambda r: r._myinvois_get_proxy_user()).items():
786 if not proxy_user:
787 continue
788
789 for submission_uid, submission_records in records.grouped('myinvois_submission_uid').items():
790 # Filter the submission records to skip batches that we don't want to fetch yet.
791 submission_records.filtered(lambda r: not r.myinvois_retry_at or fields.Datetime.from_string(r.myinvois_retry_at) <= datetime.datetime.now())
792
793 if not submission_uid or not submission_records:
794 continue
795
796 self.env["res.company"]._with_locked_records(submission_records)
797
798 records_per_uuid = submission_records.grouped('myinvois_external_uuid')
799
800 result = proxy_user._l10n_my_edi_contact_proxy(
801 endpoint='api/l10n_my_edi/1/get_submission_statuses',
802 params={
803 'submission_uid': submission_uid,
804 'page': 1,
805 },
806 )
807 if 'error' in result:
808 results[submission_uid]['error'] = self._myinvois_map_error(result['error'])
809 else:
810 # While unlikely, if we end up with too many documents we will start by getting all the info.
811 if result['document_count'] > 100:
812 for page in range(2, (result['document_count'] // 100) + 1):
813 if self._can_commit(): # avoid the sleep in tests.
814 time.sleep(0.3)
815 page_result = proxy_user._l10n_my_edi_contact_proxy(
816 endpoint='api/l10n_my_edi/1/get_submission_statuses',
817 params={
818 'submission_uid': submission_uid,
819 'page': page,
820 },
821 )
822 result['statuses'].update(page_result['statuses'])
823
824 for uuid, status in result['statuses'].items():
825 record = records_per_uuid.get(uuid)
826 if record:
827 results[submission_uid]['statuses'][record] = status
828
829 if self._can_commit(): # avoid the sleep in tests.
830 time.sleep(0.3)
831 return results
832
833 def _myinvois_submission_statuses_update(self, with_commit=True):
834 """
835 Fetches and update the status of a group of documents.
836
837 :param with_commit: If True, we will commit after retrieving the status if we can.
838 """
839 statuses = self._myinvois_get_submission_status()
840 for submission_uid, results in statuses.items():
841 records = self.browse(list(results['statuses'].keys()))
842
843 if results['error']:
844 message = self.env["account.move.send"]._format_error_html({
845 "error_title": self.env._("The status update failed with the following errors:"),
846 "errors": results['error'],
847 })
848 records._myinvois_log_message(bodies={document.id: message for document in self})
849 if with_commit and self._can_commit():
850 self.env.cr.commit()
851 continue
852
853 for record, status in results['statuses'].items():
854 # For valid documents, we always want to update the try time; it's pointless to fetch too often.
855 if record.myinvois_state == 'valid' or status['status'] == 'valid':
856 record.myinvois_retry_at = fields.Datetime.now() + datetime.timedelta(hours=1)
857
858 # If the status did not change, we do not need to do anything more.
859 if record.myinvois_state == status['status']:
860 if with_commit and self._can_commit():
861 self.env.cr.commit()
862 continue
863
864 # Invalid documents may not all have a reason, but we still want to log something.
865 # We will have a reason when documents are cancelled/rejected though, and we want to log that too.
866 message = None
867 if status.get('reason') or status['status'] == 'invalid':
868 if status.get('reason'):
869 message = record.env._('The MyInvois platform returned a "%(status)s" status for this document for reason: %(reason)s', status=status['reason'], reason=status['reason'])
870 else:
871 message = record.env._('The MyInvois platform returned an "%(status)s" status for this document.', status=status['reason'])
872
873 record._myinvois_set_state(status["status"], message)
874 record._myinvois_set_validation_fields(status)
875
876 if with_commit and self._can_commit():
877 self.env.cr.commit()
878
879 def _validate_taxes(self):
880 """ Makes use of account.edi.xml.ubl_myinvois_my to validate the taxes for the records in self."""
881 if self.invoice_ids:
882 self.env["account.edi.xml.ubl_myinvois_my"]._validate_taxes(self.invoice_ids.invoice_line_ids.tax_ids)
883
884 def _myinvois_generate_xml_file(self):
885 """ Generate the xml file representing this record(s) attached to this document. """
886 self.ensure_one()
887 builder = self.env['account.edi.xml.ubl_myinvois_my']
888 # 1. Validate the structure of the taxes
889 self._validate_taxes()
890 # 2. Export the file data
891 vals = {'myinvois_document': self.with_context(lang=self.env.company.partner_id.lang)}
892 document_node = builder._get_myinvois_document_node(vals)
893 vals['document_node'] = document_node
894 # 3. Check for any issue with the data
895 errors = [constraint for constraint in builder._export_myinvois_document_constraints(vals).values() if constraint]
896 # 4. Generate the xml file
897 template = builder._get_document_template(vals)
898 nsmap = builder._get_document_nsmap(vals)
899 xml_content = dict_to_xml(document_node, nsmap=nsmap, template=template)
900 return etree.tostring(xml_content, xml_declaration=True, encoding='UTF-8'), set(errors)
901
902 def _submit_to_myinvois(self):
903 """
904 Submit the documents in self to MyInvois.
905 This action will re-generate a new XML file, in order to ensure that we always send an up-to-date version.
906 """
907 # Make sure that all documents in self have a file ready to be sent.
908 self.action_generate_xml_file()
909
910 # Submit the documents to the API
911 errors = self._myinvois_submit_documents({
912 document: {
913 'name': document.name,
914 'xml': base64.b64decode(document.myinvois_file).decode('utf-8'),
915 } for document in self
916 })
917
918 # When sending an individual document, we can raise once we are sure we logged the errors.
919 if len(self) == 1 and errors:
920 if self._can_commit():
921 self.env.cr.commit() # Save the error logged in the chatter.
922 raise UserError(errors[self.id]['plain_text_error'])
923
924 # Try and get the status, up to three time, stopping if all documents have a status already.
925 for _i in range(3):
926 self._myinvois_submission_statuses_update()
927 if not any(document.myinvois_state == 'in_progress' for document in self):
928 break
929 if self._can_commit(): # avoid the sleep in tests.
930 time.sleep(1)
931
932 # Status Update
933
934 def _myinvois_check_can_update_status(self):
935 """ The document status can only be updated (for rejection, or cancellation) up to 72h after the validation time.
936 After that, any update will be rejected by the platform, as you are expected to issue a debit/credit note.
937
938 This helper will raise if the status cannot be updated.
939 """
940 self.ensure_one()
941 if not self.myinvois_validation_time:
942 return
943
944 time_difference = datetime.datetime.now() - self.myinvois_validation_time
945 if time_difference >= datetime.timedelta(days=3):
946 raise UserError(self.env._('It has been more than 72h since the document validation, you can no longer cancel it.\n'
947 'Instead, you should issue a debit or credit note.'))
948 if self.myinvois_state not in ['valid', 'rejected']:
949 raise UserError(self.env._('You can only change the state of a document in the valid or rejected states.'))
950
951 def _action_myinvois_update_document(self, new_status='cancelled'):
952 """
953 Returns the action to open the status updated wizard for the mode passed in params.
954
955 Valid values for new status are 'cancelled' and 'rejected'.
956 """
957 self._myinvois_check_can_update_status()
958 return {
959 "name": self.env._("Cancel Document"),
960 "type": "ir.actions.act_window",
961 "view_mode": "form",
962 "res_model": "myinvois.document.status.update.wizard",
963 "target": "new",
964 "context": {
965 "default_document_id": self.id,
966 "default_new_status": new_status,
967 },
968 }
969
970 def _myinvois_update_document(self, status, reason):
971 """
972 This method will try to update the status of a document on the platform, and if needed also the status in Odoo.
973
974 There is no "Rejected" status on the platform. The document stays as 'valid' until action is taken by the vendor.
975 At that point, the invoice will be cancelled if need be by the call to _myinvois_set_state.
976 """
977 self.ensure_one()
978 self.env['res.company']._with_locked_records(self)
979 proxy_user = self._myinvois_get_proxy_user()
980
981 # While we do this check before opening the wizard (to avoid filling the wizard for nothing), it is safer to
982 # recheck here in case we exceeded the limit in the meantime or if this is called from elsewhere.
983 self._myinvois_check_can_update_status()
984
985 successfully_updated_documents = self.env['myinvois.document']
986 for document in self:
987 result = proxy_user._l10n_my_edi_contact_proxy(
988 endpoint='api/l10n_my_edi/1/update_status',
989 params={
990 'status_values': {
991 'uuid': document.myinvois_external_uuid,
992 'reason': reason,
993 'status': status,
994 },
995 },
996 )
997
998 # If it is not a success, it will have raised an error.
999 if 'error' in result:
1000 document._myinvois_log_message(message=self._myinvois_map_error(result['error']))
1001 else:
1002 successfully_updated_documents |= document
1003
1004 if status in self._fields['myinvois_state'].get_values(self.env):
1005 successfully_updated_documents._myinvois_set_state(
1006 state=status,
1007 message=self.env._('This document has been %(status)s for reason: %(reason)s', status=status, reason=reason),
1008 )
1009
1010 if self._can_commit():
1011 self.env.cr.commit()
1012
1013 def _myinvois_set_state(self, state, message=None):
1014 """
1015 Helper to call when the state of one or more documents change.
1016 It will handle logging a message if needed, updating the state, cancelling the move when required, and update
1017 essential fields that should not be forgotten.
1018 """
1019 if message:
1020 self._myinvois_log_message(message)
1021
1022 self.myinvois_state = state
1023
1024 # Once invalid, an invoice is not acceptable by the platform.
1025 # An invalid invoice will never be visible by a customer and should, from my understanding, be considered void.
1026 # In Odoo, the best way to represent that is by cancelling the invoice.
1027 if state in CANCELLED_STATES and self.invoice_ids:
1028 self.invoice_ids._l10n_my_edi_cancel_moves()
1029
1030 def _myinvois_set_validation_fields(self, validation_result):
1031 self.ensure_one()
1032 if self.myinvois_state != 'valid':
1033 return
1034
1035 # We receive a timezone_aware datetime, but it should always be in UTC.
1036 # Odoo expect a timezone unaware datetime in UTC, so we can safely remove the info without any more work needed.
1037 utc_tz_aware_datetime = dateutil.parser.isoparse(validation_result['valid_datetime'])
1038 self.write({
1039 'myinvois_validation_time': utc_tz_aware_datetime.replace(tzinfo=None),
1040 'myinvois_document_long_id': validation_result['long_id'],
1041 })
1042
1043 def _myinvois_single_status_update(self):
1044 """
1045 Fetches and update the status of a single document.
1046 More efficient than using the submission status endpoint.
1047 """
1048 self.ensure_one()
1049 proxy_user = self._myinvois_get_proxy_user()
1050
1051 self.env['res.company']._with_locked_records(self)
1052
1053 result = proxy_user._l10n_my_edi_contact_proxy(
1054 endpoint='api/l10n_my_edi/1/get_status',
1055 params={
1056 'document_uuid': self.myinvois_external_uuid,
1057 },
1058 )
1059
1060 if 'error' in result:
1061 raise UserError(self._myinvois_map_error(result['error']))
1062
1063 if result['status'] == self.myinvois_state:
1064 return
1065
1066 message = None
1067 if 'validation_errors' in result:
1068 message = self.env['account.move.send']._format_error_html({
1069 'error_title': self.env._('The validation failed with the following errors:'),
1070 'errors': result['validation_errors'],
1071 })
1072 elif result.get('status_reason'):
1073 message = self.env._('This document has been %(status)s for reason: %(reason)s', status=result['status'], reason=result['status_reason'])
1074
1075 self._myinvois_set_state(result['status'], message)
1076 self._myinvois_set_validation_fields(result)
1077
1078 @api.model
1079 def _myinvois_statuses_update_cron(self):
1080 """
1081 This cron is based on the recommended method to fetch the status of the documents according to their doc.
1082 MAX_SUBMISSION_UPDATE defines how many submissions to process in a single cron run.
1083 """
1084 # First step is to get the documents for which the status is not yet final.
1085 # A document whose status will not change anymore is: (cancelled or invalid) or has been validated more than 74h ago.
1086 # /!\ when a document validation is pending, myinvois_validation_time is still None. These also need to be updated.
1087 datetime_threshold = datetime.datetime.now() - datetime.timedelta(hours=74)
1088 # We always want to fetch in_progress document, it's very likely that their status is already there.
1089 domain = Domain('myinvois_state', 'in', ('in_progress', False))
1090 # For valid document, we want them if their myinvois_validation_time is less than 74h ago, and if their myinvois_retry_at in the past.
1091 domain |= Domain([
1092 ('myinvois_state', '=', 'valid'),
1093 ('myinvois_validation_time', '>', datetime_threshold),
1094 '|',
1095 ('myinvois_retry_at', '<=', datetime.datetime.now()),
1096 ('myinvois_retry_at', '=', False),
1097 ])
1098 grouped_documents = self.env['myinvois.document']._read_group(
1099 domain,
1100 groupby=['myinvois_submission_uid'],
1101 aggregates=['id:recordset'],
1102 limit=MAX_SUBMISSION_UPDATE,
1103 )
1104 document_count = self.search_count(domain) # Count the total amount of documents to process.
1105
1106 processed_documents = 0
1107 for index, (submission_uid, documents) in enumerate(grouped_documents):
1108 # Update the status for that one submission. In case of errors, we log it and continue.
1109 # Errors are quite unlikely in this flow.
1110 documents._myinvois_submission_statuses_update(with_commit=False) # We handle the commit after notifying of progress.
1111
1112 processed_documents += len(documents)
1113 # Commit if we can, in case an issue arises later.
1114 if self._can_commit():
1115 self.env['ir.cron']._commit_progress(processed=processed_documents, remaining=document_count - processed_documents)
1116
1117 # Avoid sleeping on the last loop and in tests (due to the commit check)
1118 if index != (len(grouped_documents) - 1):
1119 time.sleep(0.3) # There is a limit of how many calls we can do, so we spread them out a bit.
1120 if self._can_commit():
1121 self.env['ir.cron']._commit_progress(processed=processed_documents, remaining=document_count - processed_documents)