Debian Codegraph @

addons/l10n_sa_edi/models/account_edi_format.py

raw
1 import logging
2
3 from markupsafe import Markup
4 from hashlib import sha256
5 from base64 import b64decode, b64encode
6 from lxml import etree
7 from datetime import datetime
8 from odoo import models, fields, _, api
9 from odoo.exceptions import UserError
10
11 _logger = logging.getLogger(__name__)
12
13
14 class AccountEdiFormat(models.Model):
15 _inherit = 'account.edi.format'
16
17 """
18 Once the journal has been successfully onboarded, we can clear/report invoices through the ZATCA API:
19 A) STANDARD Invoice:
20 Make a call to the Clearance API '/invoices/clearance/single'.
21 This will validate the invoice, sign it and apply a QR code then return the result.
22 B) SIMPLIFIED Invoice:
23 Make a call to the Reporting API '/invoices/reporting/single'.
24 This will validate the invoice then return the result.
25 The X509 Certificate and password from the PCSID API need to be provided in the request headers.
26 """
27
28 # ====== Helper Functions =======
29
30 def _l10n_sa_get_zatca_datetime(self, timestamp):
31 return fields.Datetime.context_timestamp(self.with_context(tz='Asia/Riyadh'), timestamp)
32
33 def _l10n_sa_xml_node_content(self, root, xpath, namespaces=None):
34 namespaces = namespaces or self.env['account.edi.xml.ubl_21.zatca']._l10n_sa_get_namespaces()
35 return etree.tostring(root.xpath(xpath, namespaces=namespaces)[0], with_tail=False,
36 encoding='utf-8', method='xml')
37
38 # ====== Xades Signing =======
39
40 @api.model
41 def _l10n_sa_get_digital_signature(self, company_id, invoice_hash):
42 """
43 Generate an ECDSA SHA256 digital signature for the XML eInvoice
44 """
45 decoded_hash = b64decode(invoice_hash).decode()
46 return company_id.sudo().l10n_sa_private_key_id._sign(decoded_hash, formatting='base64')
47
48 def _l10n_sa_calculate_signed_properties_hash(self, issuer_name, serial_number, signing_time, public_key):
49 """
50 Calculate the SHA256 value of the SignedProperties XML node. The algorithm used by ZATCA expects the indentation
51 of the nodes to start with 40 spaces, except for the root SignedProperties node.
52 """
53 signed_properties = etree.fromstring(self.env['ir.qweb']._render('l10n_sa_edi.export_sa_zatca_ubl_signed_properties', {
54 'issuer_name': issuer_name,
55 'serial_number': serial_number,
56 'signing_time': signing_time,
57 'public_key_hashing': public_key,
58 }))
59 etree.indent(signed_properties, space=' ')
60 signed_properties_split = etree.tostring(signed_properties).decode().split('\n')
61 signed_properties_final = ""
62 for index, line in enumerate(signed_properties_split):
63 if index == 0:
64 signed_properties_final += line
65 else:
66 signed_properties_final += (' ' * 36) + line
67 if index != len(signed_properties_final) - 1:
68 signed_properties_final += '\n'
69 signed_properties_final = etree.tostring(etree.fromstring(signed_properties_final))
70 return b64encode(sha256(signed_properties_final).hexdigest().encode()).decode()
71
72 def _l10n_sa_sign_xml(self, xml_content, certificate, signature):
73 """
74 Function that signs XML content of a UBL document with a provided B64 encoded X509 certificate
75 """
76 root = etree.fromstring(xml_content)
77 etree.indent(root, space=' ')
78
79 def _set_content(xpath, content):
80 node = root.xpath(xpath)[0]
81 node.text = content
82
83 der_cert = certificate._get_der_certificate_bytes(formatting='base64')
84
85 issuer_name = certificate._l10n_sa_get_issuer_name()
86 serial_number = certificate.serial_number
87 signing_time = self._l10n_sa_get_zatca_datetime(datetime.now()).strftime('%Y-%m-%dT%H:%M:%SZ')
88 public_key_hashing = b64encode(sha256(der_cert).hexdigest().encode()).decode()
89
90 signed_properties_hash = self._l10n_sa_calculate_signed_properties_hash(issuer_name, serial_number,
91 signing_time, public_key_hashing)
92
93 _set_content("//*[local-name()='X509IssuerName']", issuer_name)
94 _set_content("//*[local-name()='X509SerialNumber']", serial_number)
95 _set_content("//*[local-name()='SignedSignatureProperties']/*[local-name()='SigningTime']", signing_time)
96 _set_content("//*[local-name()='SignedSignatureProperties']//*[local-name()='DigestValue']", public_key_hashing)
97
98 prehash_content = etree.tostring(root)
99 invoice_hash = self.env['account.edi.xml.ubl_21.zatca']._l10n_sa_generate_invoice_xml_hash(prehash_content,
100 'digest')
101
102 _set_content("//*[local-name()='SignatureValue']", signature)
103 _set_content("//*[local-name()='X509Certificate']", der_cert.decode())
104 _set_content("//*[local-name()='SignatureInformation']//*[local-name()='DigestValue']", invoice_hash)
105 _set_content("//*[@URI='#xadesSignedProperties']/*[local-name()='DigestValue']", signed_properties_hash)
106
107 return etree.tostring(root, with_tail=False)
108
109 def _l10n_sa_assert_clearance_status(self, invoice, clearance_data):
110 """
111 Assert Clearance status. To be overridden in case there are any other cases to be accounted for
112 """
113 mode = 'reporting' if invoice._l10n_sa_is_simplified() else 'clearance'
114 if mode == 'clearance' and clearance_data.get('clearanceStatus', '') != 'CLEARED':
115 return {'error': _("Invoice could not be cleared:\n%s", clearance_data), 'blocking_level': 'error'}
116 elif mode == 'reporting' and clearance_data.get('reportingStatus', '') != 'REPORTED':
117 return {'error': _("Invoice could not be reported:\n%s", clearance_data), 'blocking_level': 'error'}
118 return clearance_data
119
120 # ====== UBL Document Rendering & Submission =======
121
122 def _l10n_sa_postprocess_zatca_template(self, xml_content):
123 """
124 Post-process xml content generated according to the ZATCA UBL specifications. Specifically, this entails:
125 - Force the xmlns:ext namespace on the root element (Invoice). This is required, since, by default
126 the generated UBL file does not have any ext namespaced element, so the namespace is removed
127 since it is unused.
128 """
129
130 # Append UBLExtensions to the XML content
131 ubl_extensions = etree.fromstring(self.env['ir.qweb']._render('l10n_sa_edi.export_sa_zatca_ubl_extensions'))
132 root = etree.fromstring(xml_content)
133 root.insert(0, ubl_extensions)
134
135 # Force xmlns:ext namespace on UBl file
136 ns_map = {'ext': 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2'}
137 etree.cleanup_namespaces(root, top_nsmap=ns_map, keep_ns_prefixes=['ext'])
138
139 return etree.tostring(root, with_tail=False).decode()
140
141 def _l10n_sa_generate_zatca_template(self, invoice):
142 """
143 Render the ZATCA UBL file
144 """
145 xml_content, errors = self.env['account.edi.xml.ubl_21.zatca']._export_invoice(invoice)
146 if errors:
147 return {
148 'error': _("Could not generate Invoice UBL content: %s", ", \n".join(errors)),
149 'blocking_level': 'error'
150 }
151 return self._l10n_sa_postprocess_zatca_template(xml_content)
152
153 def _l10n_sa_submit_einvoice(self, invoice, signed_xml, PCSID_data):
154 """
155 Submit a generated Invoice UBL file by making calls to the following APIs:
156 - A. Clearance API: Submit a standard Invoice to ZATCA for validation, returns signed UBL
157 - B. Reporting API: Submit a simplified Invoice to ZATCA for validation
158 """
159 clearance_data = invoice.journal_id._l10n_sa_api_clearance(invoice, signed_xml.decode(), PCSID_data)
160 if error := clearance_data.get('json_errors'):
161 error_msg = ''
162 if status_code := error.get('status_code'):
163 error_msg = Markup("<b>[%s] </b>") % status_code
164
165 is_warning = True
166 validation_results = error.get('validationResults', {})
167 for err in validation_results.get('warningMessages', []):
168 error_msg += Markup('<b>%s</b> : %s <br/>') % (err['code'], err['message'])
169 for err in validation_results.get('errorMessages', []):
170 is_warning = False
171 error_msg += Markup('<b>%s</b> : %s <br/>') % (err['code'], err['message'])
172 return {
173 'error': error_msg,
174 'rejected': not is_warning,
175 'response': signed_xml.decode(),
176 'blocking_level': 'warning' if is_warning else 'error',
177 'status_code': status_code,
178 }
179 if not clearance_data.get('error') and clearance_data.get("status_code") != 409:
180 return self._l10n_sa_assert_clearance_status(invoice, clearance_data)
181 return clearance_data
182
183 def _l10n_sa_postprocess_einvoice_submission(self, invoice, signed_xml, clearance_data):
184 """
185 Once an invoice has been successfully submitted, it is returned as a Cleared invoice, on which data
186 from ZATCA was applied. To be overridden to account for other cases, such as Reporting.
187 """
188 if invoice._l10n_sa_is_simplified():
189 # if invoice is B2C, it is a SIMPLIFIED invoice, and thus it is only reported and returns
190 # no signed invoice. In this case, we just return the original content
191 return signed_xml.decode()
192 return b64decode(clearance_data['clearedInvoice']).decode()
193
194 def _l10n_sa_apply_qr_code(self, invoice, xml_content):
195 """
196 Apply QR code on Invoice UBL content
197 """
198 root = etree.fromstring(xml_content)
199 qr_code = invoice.l10n_sa_qr_code_str
200 qr_node = root.xpath('//*[local-name()="ID"][text()="QR"]/following-sibling::*/*')[0]
201 qr_node.text = qr_code
202 return etree.tostring(root, with_tail=False)
203
204 def _l10n_sa_get_signed_xml(self, invoice, unsigned_xml, certificate):
205 """
206 Helper method to sign the provided XML, apply the QR code in the case if Simplified invoices (B2C), then
207 return the signed XML
208 """
209 signed_xml = self._l10n_sa_sign_xml(unsigned_xml, certificate, invoice.l10n_sa_invoice_signature)
210 if invoice._l10n_sa_is_simplified():
211 # Applying with_prefetch() to set the _prefetch_ids = _ids,
212 # preventing premature QR code computation for other invoices.
213 invoice = invoice.with_prefetch()
214 return self._l10n_sa_apply_qr_code(invoice, signed_xml)
215 return signed_xml
216
217 def _l10n_sa_export_zatca_invoice(self, invoice, xml_content=None):
218 """
219 Generate a ZATCA compliant UBL file, make API calls to authenticate, sign and include QR Code and
220 Cryptographic Stamp, then create an attachment with the final contents of the UBL file
221 """
222 self.ensure_one()
223
224 # Prepare UBL invoice values and render XML file
225 unsigned_xml = xml_content or self._l10n_sa_generate_zatca_template(invoice)
226
227 # Load PCISD data and certificate
228 try:
229 PCSID_data, certificate = invoice.journal_id._l10n_sa_api_get_pcsid()
230 except UserError as e:
231 return ({
232 'error': e.args[0],
233 'blocking_level': 'error',
234 'response': unsigned_xml
235 }, unsigned_xml)
236
237 certificate_sudo = self.env['certificate.certificate'].sudo().browse(certificate)
238
239 # Apply Signature/QR code on the generated XML document
240 try:
241 signed_xml = self._l10n_sa_get_signed_xml(invoice, unsigned_xml, certificate_sudo)
242 except UserError:
243 return ({
244 'error': _("Something went wrong. Please retry, and if that does not work, then onboard the journal again."),
245 'blocking_level': 'error',
246 'response': unsigned_xml
247 }, unsigned_xml)
248
249 # Once the XML content has been generated and signed, we submit it to ZATCA
250 return self._l10n_sa_submit_einvoice(invoice, signed_xml, PCSID_data), signed_xml
251
252 def _l10n_sa_check_seller_missing_info(self, invoice):
253 """
254 Helper function to check if ZATCA mandated partner fields are missing for the seller
255 """
256 partner_id = invoice.company_id.partner_id.commercial_partner_id
257 missing_fields = []
258 if not partner_id.state_id:
259 missing_fields.append(_('State'))
260 if not partner_id.city:
261 missing_fields.append(_('City'))
262 return missing_fields
263
264 def _l10n_sa_check_buyer_missing_info(self, invoice):
265 """
266 Helper function to check if ZATCA mandated partner fields are missing for the buyer
267 """
268 partner_id = invoice.commercial_partner_id
269 missing = []
270 identification_scheme = partner_id.l10n_sa_edi_additional_identification_scheme
271 if (
272 any(
273 tax.l10n_sa_exemption_reason_code in ('VATEX-SA-HEA', 'VATEX-SA-EDU')
274 for tax in invoice.invoice_line_ids.filtered(
275 lambda line: line.display_type == 'product'
276 ).tax_ids
277 )
278 and (
279 identification_scheme != 'NAT'
280 or not partner_id.l10n_sa_edi_additional_identification_number
281 )
282 ):
283 missing.append(_(
284 "Please set the Identification Scheme as National ID and Identification Number as the respective "
285 "number on the Customer as the Tax Exemption Reason is set either as VATEX-SA-HEA or VATEX-SA-EDU"
286 ))
287 if identification_scheme == 'TIN' and not partner_id.vat:
288 missing.append(_("Please set the VAT Number as the Identification Scheme is Tax Identification Number"))
289 return missing
290
291 def _l10n_sa_post_zatca_edi(self, invoice): # no batch ensure that there is only one invoice
292 """
293 Post invoice to ZATCA and return a dict of invoices and their success/attachment
294 """
295
296 # Chain integrity check: chain head must have been REALLY posted, and did not time out
297 # When a submission times out, we reset the chain index of the invoice to False, so it has to be submitted again
298 # According to ZATCA, if we end up submitting the same invoice more than once, they will directly reach out
299 # to the taxpayer for clarifications
300 chain_head = invoice.journal_id._l10n_sa_get_last_posted_invoice()
301 if chain_head and chain_head != invoice and not chain_head._l10n_sa_is_in_chain():
302 invoice.l10n_sa_edi_chain_head_id = chain_head
303 return {invoice: {
304 'error': _("Error: This invoice is blocked due to %s. Please check it.", chain_head.name),
305 'blocking_level': 'error',
306 'response': None,
307 }}
308
309 xml_content = None
310 if not invoice.l10n_sa_chain_index:
311 # If the Invoice doesn't have a chain index, it means it either has not been submitted before,
312 # or it was submitted and rejected. Either way, we need to assign it a new Chain Index and regenerate
313 # the data that depends on it before submitting (UUID, XML content, signature)
314 invoice.l10n_sa_chain_index = invoice.journal_id._l10n_sa_edi_get_next_chain_index()
315 xml_content = invoice._l10n_sa_generate_unsigned_data()
316
317 # Generate Invoice name for attachment
318 attachment_name = self.env['account.edi.xml.ubl_21.zatca']._export_invoice_filename(invoice)
319
320 # Generate XML, sign it, then submit it to ZATCA
321 response_data, submitted_xml = self._l10n_sa_export_zatca_invoice(invoice, xml_content)
322
323 # Check for submission errors
324 if response_data.get('error'):
325
326 # If the request was rejected, we save the signed xml content as an attachment
327 # If request timedout, just log note a warning message
328 invoice._l10n_sa_log_results(submitted_xml, response_data, error=response_data.get('rejected'))
329
330 # If the request returned an exception (Timeout, ValueError... etc.) it means we're not sure if the
331 # invoice was successfully cleared/reported, and thus we keep the Index Chain.
332 # Else, we recalculate the submission Index (ICV), UUID, XML content and Signature
333 if not response_data.get('excepted'):
334 invoice.l10n_sa_chain_index = False
335
336 return {
337 invoice: {
338 **response_data,
339 'response': submitted_xml
340 }
341 }
342
343 # Once submission is done with no errors, check submission status
344 cleared_xml = self._l10n_sa_postprocess_einvoice_submission(invoice, submitted_xml, response_data)
345
346 # Set 'l10n_sa_edi_is_production' to True upon the first invoice submission in Production mode
347 if not invoice.company_id.l10n_sa_edi_is_production:
348 invoice.company_id.l10n_sa_edi_is_production = invoice.company_id.l10n_sa_api_mode == 'prod'
349
350 # Save the submitted/returned invoice XML content once the submission has been completed successfully
351 invoice._l10n_sa_log_results(cleared_xml.encode(), response_data)
352 invoice.journal_id._l10n_sa_reset_chain_head_error()
353 return {
354 invoice: {
355 'success': True,
356 'response': cleared_xml,
357 'message': '',
358 'attachment': self.env['ir.attachment'].create({
359 'name': attachment_name,
360 'raw': cleared_xml.encode(),
361 'res_model': 'account.move',
362 'res_id': invoice.id,
363 'mimetype': 'application/xml'
364 })
365 }
366 }
367
368 # ====== EDI Format Overrides =======
369
370 def _is_required_for_invoice(self, invoice):
371 """
372 Override to add ZATCA edi checks on required invoices
373 """
374 self.ensure_one()
375 if self.code != 'sa_zatca':
376 return super()._is_required_for_invoice(invoice)
377
378 return invoice.is_sale_document() and invoice.country_code == 'SA'
379
380 def _check_move_configuration(self, invoice):
381 """
382 Override to add ZATCA compliance checks on the Invoice
383 """
384
385 journal = invoice.journal_id
386 company = invoice.company_id
387
388 errors = super()._check_move_configuration(invoice)
389 if self.code != 'sa_zatca' or company.country_id and company.country_id.code != 'SA':
390 return errors
391
392 if invoice.commercial_partner_id == invoice.company_id.partner_id.commercial_partner_id:
393 errors.append(_("- Invoice cannot be posted as the Supplier and Buyer are the same."))
394
395 if not all(line.tax_ids for line in invoice.invoice_line_ids.filtered(lambda line: line.display_type == 'product' and line._check_edi_line_tax_required())):
396 errors.append(_("- Invoice lines need at least one tax. Please input it and try again."))
397
398 if not journal._l10n_sa_ready_to_submit_einvoices():
399 errors.append(_("- The Journal (%s) is not onboarded yet. Please onboard it and try again.", journal.name))
400
401 if not company._l10n_sa_check_organization_unit():
402 errors.append(
403 _("- The company VAT identification must contain 15 digits, with the first and last digits being '3' as per the BR-KSA-39 and BR-KSA-40 of ZATCA KSA business rule."))
404 if not journal.company_id.sudo().l10n_sa_private_key_id:
405 errors.append(
406 _("- No Private Key was generated for company %s. A Private Key is mandatory in order to generate Certificate Signing Requests (CSR).", company.name))
407
408 supplier_missing_info = self._l10n_sa_check_seller_missing_info(invoice)
409 customer_missing_info = self._l10n_sa_check_buyer_missing_info(invoice)
410
411 if supplier_missing_info:
412 errors.append(
413 _(
414 "- Please set the following fields on the %(company_name)s: %(missing_fields)s",
415 company_name=company.name,
416 missing_fields=", ".join(supplier_missing_info),
417 )
418 )
419 if customer_missing_info:
420 errors.append(
421 _(
422 "- %(missing_info)s",
423 missing_info=", ".join(customer_missing_info),
424 )
425 )
426 if invoice.invoice_date > fields.Date.context_today(self.with_context(tz='Asia/Riyadh')):
427 errors.append(_("- Please set the Invoice Date to be either less than or equal to today."))
428
429 if invoice.l10n_sa_show_reason and not invoice.l10n_sa_reason:
430 errors.append(_("- Please make sure the 'ZATCA Reason' for the issuance of the Credit/Debit Note is specified."))
431 if invoice.l10n_sa_show_reason and not invoice._l10n_sa_check_billing_reference():
432 errors.append(_("- Please make sure the 'Customer Reference' contains the sequential number of the original invoice(s) that the Credit/Debit Note is related to."))
433 return errors
434
435 def _needs_web_services(self):
436 """
437 Override to add a check on edi document format code
438 """
439 self.ensure_one()
440 return self.code == 'sa_zatca' or super()._needs_web_services()
441
442 def _is_compatible_with_journal(self, journal):
443 """
444 Override to add a check on journal type & country code (SA)
445 """
446 self.ensure_one()
447 if self.code != 'sa_zatca':
448 return super()._is_compatible_with_journal(journal)
449 return journal.type == 'sale' and journal.country_code == 'SA'
450
451 def _l10n_sa_get_invoice_content_edi(self, invoice):
452 """
453 Return contents of the submitted UBL file or generate it if the invoice has not been submitted yet
454 """
455 doc = invoice.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'sa_zatca' and d.state == 'sent')
456 return doc.attachment_id.raw or self._l10n_sa_generate_zatca_template(invoice).encode()
457
458 def _get_move_applicability(self, move):
459 # EXTENDS account_edi
460 self.ensure_one()
461 if self.code != 'sa_zatca' or move.country_code != 'SA' or move.move_type not in ('out_invoice', 'out_refund'):
462 return super()._get_move_applicability(move)
463
464 return {
465 'post': self._l10n_sa_post_zatca_edi,
466 'edi_content': self._l10n_sa_get_invoice_content_edi,
467 }
468
469 def _prepare_invoice_report(self, pdf_writer, edi_document):
470 """
471 Prepare invoice report to be printed.
472 :param pdf_writer: The pdf writer with the invoice pdf content loaded.
473 :param edi_document: The edi document to be added to the pdf file.
474 """
475 self.ensure_one()
476 super()._prepare_invoice_report(pdf_writer, edi_document)
477 if self.code != 'sa_zatca' or edi_document.move_id.country_code != 'SA':
478 return
479
480 attachment = edi_document.sudo().attachment_id
481 if not attachment or not attachment.datas:
482 _logger.warning("No attachment found for invoice %s", edi_document.move_id.name)
483 return
484
485 xml_content = attachment.raw
486 file_name = attachment.name
487
488 pdf_writer.addAttachment(file_name, xml_content, subtype='text/xml')
489 if not pdf_writer.is_pdfa:
490 try:
491 pdf_writer.convert_to_pdfa()
492 except Exception:
493 _logger.exception("Error while converting to PDF/A")
494 content = self.env['ir.qweb']._render(
495 'account_edi_ubl_cii.account_invoice_pdfa_3_facturx_metadata',
496 {
497 'title': edi_document.move_id.name,
498 'date': fields.Date.context_today(self),
499 },
500 )
501 if "<pdfaid:conformance>B</pdfaid:conformance>" in content:
502 content.replace("<pdfaid:conformance>B</pdfaid:conformance>", "<pdfaid:conformance>A</pdfaid:conformance>")
503 pdf_writer.add_file_metadata(content.encode())