Debian Codegraph @

addons/l10n_sa_edi/models/account_journal.py

raw
1 import json
2 import logging
3 from base64 import b64decode, b64encode
4 from datetime import datetime
5
6 import requests
7 from lxml import etree
8 from markupsafe import Markup
9 from requests.exceptions import HTTPError, RequestException
10
11 from odoo import _, fields, models
12 from odoo.exceptions import UserError
13 from odoo.tools.misc import file_open
14 from odoo.tools.translate import LazyTranslate
15 from odoo.tools.urls import urljoin
16
17 _lt = LazyTranslate(__name__)
18
19 ZATCA_API_URLS = {
20 "sandbox": "https://gw-fatoora.zatca.gov.sa/e-invoicing/developer-portal/",
21 "preprod": "https://gw-fatoora.zatca.gov.sa/e-invoicing/simulation/",
22 "prod": "https://gw-fatoora.zatca.gov.sa/e-invoicing/core/",
23 "apis": {
24 "ccsid": "compliance",
25 "pcsid": "production/csids",
26 "compliance": "compliance/invoices",
27 "reporting": "invoices/reporting/single",
28 "clearance": "invoices/clearance/single",
29 }
30 }
31
32 # This SANDBOX_AUTH is only used for testing purposes, and is shared to all users of the sandbox environment
33 SANDBOX_AUTH = {
34 'binarySecurityToken': "TUlJRDFEQ0NBM21nQXdJQkFnSVRid0FBZTNVQVlWVTM0SS8rNVFBQkFBQjdkVEFLQmdncWhrak9QUVFEQWpCak1SVXdFd1lLQ1pJbWlaUHlMR1FCR1JZRmJHOWpZV3d4RXpBUkJnb0praWFKay9Jc1pBRVpGZ05uYjNZeEZ6QVZCZ29Ka2lhSmsvSXNaQUVaRmdkbGVIUm5ZWHAwTVJ3d0dnWURWUVFERXhOVVUxcEZTVTVXVDBsRFJTMVRkV0pEUVMweE1CNFhEVEl5TURZeE1qRTNOREExTWxvWERUSTBNRFl4TVRFM05EQTFNbG93U1RFTE1Ba0dBMVVFQmhNQ1UwRXhEakFNQmdOVkJBb1RCV0ZuYVd4bE1SWXdGQVlEVlFRTEV3MW9ZWGxoSUhsaFoyaHRiM1Z5TVJJd0VBWURWUVFERXdreE1qY3VNQzR3TGpFd1ZqQVFCZ2NxaGtqT1BRSUJCZ1VyZ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na3JCZ0VFQVlJM0ZRb0VHakFZTUFvR0NDc0dBUVVGQndNQ01Bb0dDQ3NHQVFVRkJ3TURNQW9HQ0NxR1NNNDlCQU1DQTBrQU1FWUNJUUNWd0RNY3E2UE8rTWNtc0JYVXovdjFHZGhHcDdycVNhMkF4VEtTdjgzOElBSWhBT0JOREJ0OSszRFNsaWpvVmZ4enJkRGg1MjhXQzM3c21FZG9HV1ZyU3BHMQ==",
35 'secret': "Xlj15LyMCgSC66ObnEO/qVPfhSbs3kDTjWnGheYhfSs="
36 }
37
38 ERROR_MESSAGE = _lt("Something went wrong. Please onboard the journal again.")
39
40 _logger = logging.getLogger(__name__)
41
42
43 class AccountJournal(models.Model):
44 _inherit = 'account.journal'
45
46 """
47 In order to clear/report an invoice through the ZATCA API, we need to onboard each journal by following
48 three steps:
49
50 STEP 1:
51 Make a call to the Compliance CSID API '/compliance'.
52 This will return three things:
53 - X509 Compliance Cryptographic Stamp Identifier (CCSID/Certificate)
54 - Password (Secret)
55 - Compliance Request ID
56 STEP 2:
57 Make a call to the Compliance Checks API '/compliance/invoices', by passing the hashed xml content
58 of the files available in the tests/compliance folder. This will check if the provided
59 Standard/Simplified Invoices comply with UBL 2.1 standards in line with ZATCA specifications
60 STEP 3:
61 Make a call to the Production CSID API '/production/csids' including the Compliance Certificate,
62 Password and Request ID from STEP 1.
63 This will return three things:
64 - X509 Production Certificate
65 - Password (Secret)
66 - Production Request ID
67 """
68
69 l10n_sa_csr = fields.Binary(attachment=True, copy=False, groups="base.group_system",
70 help="The Certificate Signing Request that is submitted to the Compliance API")
71 l10n_sa_csr_errors = fields.Html("Onboarding Errors", copy=False)
72
73 l10n_sa_compliance_csid_json = fields.Char("CCSID JSON", copy=False, groups="base.group_system",
74 help="Compliance CSID data received from the Compliance CSID API "
75 "in dumped json format")
76 l10n_sa_production_csid_certificate_id = fields.Many2one(string="PCSID Certificate", comodel_name="certificate.certificate",
77 domain=[('is_valid', '=', True)])
78 l10n_sa_production_csid_json = fields.Char("PCSID JSON", copy=False, groups="base.group_system",
79 help="Production CSID data received from the Production CSID API "
80 "in dumped json format")
81 l10n_sa_production_csid_validity = fields.Datetime(related="l10n_sa_production_csid_certificate_id.date_end")
82 l10n_sa_compliance_csid_certificate_id = fields.Many2one(string="CCSID certificate", comodel_name="certificate.certificate",
83 domain=[('is_valid', '=', True)])
84 l10n_sa_compliance_checks_passed = fields.Boolean("Compliance Checks Done", default=False, copy=False,
85 help="Specifies if the Compliance Checks have been completed successfully")
86
87 l10n_sa_chain_sequence_id = fields.Many2one('ir.sequence', string='ZATCA account.move chain sequence',
88 readonly=True, copy=False)
89
90 l10n_sa_latest_submission_hash = fields.Char("Latest Submission Hash", copy=False,
91 help="Hash of the latest submitted invoice to be used as the Previous Invoice Hash (KSA-13)")
92
93 def _l10n_sa_reset_chain_head_error(self):
94 """
95 Reset the chain head error from the journal's stuck invoices
96 """
97 stuck_invoices = self.env['account.move'].search([
98 ('l10n_sa_edi_chain_head_id', '!=', False),
99 ('journal_id', 'in', self.ids),
100 ])
101 # We only need to remove blocking errors, so webservices do not need to be triggered
102 stuck_invoices._retry_edi_documents_error()
103
104 # ====== Utility Functions =======
105
106 def _l10n_sa_ready_to_submit_einvoices(self):
107 """
108 Helper function to know if the required CSIDs have been obtained, and the compliance checks have been
109 completed
110 """
111 self.ensure_one()
112 return self.sudo().l10n_sa_production_csid_json
113
114 def _l10n_sa_api_onboard_sanity_checks(self):
115 """
116 Perform a sanity check to validate that the journal is ready to be onboarded
117 """
118
119 # If the invoice wasn't sent to ZATCA because of a timeout, it will retain its existing chain index
120 # Make sure there are no opened invoices with the journal's existing sequence
121 move_ids = self.env['account.move'].search(
122 [
123 ('journal_id', '=', self.id),
124 ('l10n_sa_chain_index', '!=', 0)
125 ]
126 )
127 stuck_moves = [move for move in move_ids if not move._l10n_sa_is_in_chain()]
128 if stuck_moves:
129 raise UserError(_("Oops! The journal is stuck. Please submit the pending invoices to ZATCA and try again."))
130
131 # ====== CSR Generation =======
132
133 def _l10n_sa_csr_required_fields(self):
134 """ Return the list of fields required to generate a valid CSR as per ZATCA requirements """
135 return ['l10n_sa_private_key_id', 'vat', 'name', 'city', 'country_id', 'state_id']
136
137 def _l10n_sa_generate_csr(self):
138 """
139 Generate a CSR for the Journal to be used for the Onboarding process and Invoice submissions
140 """
141 self.ensure_one()
142 if any(not self.company_id[f] for f in self._l10n_sa_csr_required_fields()):
143 raise UserError(
144 _(
145 "Please set the following on %(company_name)s: %(fields)s",
146 company_name=self.company_id.name,
147 fields=", ".join(
148 self.company_id._fields[f].string
149 for f in self._l10n_sa_csr_required_fields()
150 if not self.company_id[f]
151 ),
152 ),
153 )
154 self._l10n_sa_reset_certificates()
155 self.l10n_sa_csr = self.env['certificate.certificate'].sudo()._l10n_sa_get_csr_str(self)
156
157 # ====== Certificate Methods =======
158
159 def _l10n_sa_get_csid_error(self, csid):
160 """
161 Return a formatted error string if the CSID response has an 'error' or 'errors'
162 key or doesn't have a 'binarySecurityToken'
163 """
164 error_msg = ""
165 unknown_error_msg = _("Unknown response returned from ZATCA. Please check the logs.")
166 if error := csid.get('error'):
167 error_msg = error
168 elif errors := csid.get('errors'):
169 error_msg = " <br/>" + " <br/>- ".join([err['message'] if isinstance(err, dict) else err for err in errors])
170 elif 'error' in [csid.get('type', "").lower(), csid.get('status', "").lower()]:
171 error_msg = csid.get('message') or unknown_error_msg
172 elif not csid.get('binarySecurityToken'):
173 error_msg = unknown_error_msg
174
175 if error_msg:
176 _logger.warning("Failed to obtain CSID: %s", csid)
177
178 return error_msg
179
180 def _l10n_sa_reset_certificates(self):
181 """
182 Reset all certificate values, including CSR and compliance checks
183 """
184 for journal in self.sudo():
185 journal.l10n_sa_csr = False
186 journal.l10n_sa_production_csid_json = False
187 journal.l10n_sa_compliance_csid_json = False
188 journal.l10n_sa_compliance_checks_passed = False
189
190 def _l10n_sa_api_onboard_journal(self, otp):
191 """
192 Perform the onboarding for the journal. The onboarding consists of three steps:
193 1. Get the Compliance CSID
194 2. Perform the Compliance Checks
195 3. Get the Production CSID
196 """
197 self.ensure_one()
198 # we want to perform sanity checks to ensure that the journal is ready to be onboarded
199 # If the check fails, we do not want to revoke the existing PCSID because the user might still need it to post hanging invoices
200 self._l10n_sa_api_onboard_sanity_checks()
201
202 try:
203 # If the company does not have a private key, we generate it.
204 # The private key is used to generate the CSR but also to sign the invoices
205 ec_private_key_sudo = self.company_id.sudo().l10n_sa_private_key_id
206 if not ec_private_key_sudo:
207 ec_private_key_sudo = self.env['certificate.key'].sudo()._generate_ec_private_key(self.company_id, name='CCSID private key')
208 self.company_id.l10n_sa_private_key_id = ec_private_key_sudo
209 self._l10n_sa_generate_csr()
210 # STEP 1: The first step of the process is to get the CCSID
211 self._l10n_sa_get_compliance_CSID(otp)
212 # STEP 2: Once we have the CCSID, we preform the compliance checks
213 self._l10n_sa_run_compliance_checks()
214 # STEP 3: Once the compliance checks are completed, we request the PCSID
215 self._l10n_sa_get_production_CSID()
216 # Once all three steps are completed, we set the errors field to False
217 self.l10n_sa_csr_errors = False
218 # Regenerate a new chain sequence
219 self._l10n_sa_edi_icv_onboarding()
220 except (RequestException, HTTPError, UserError) as e:
221 # In case of an exception returned from ZATCA (not timeout), we will need to regenerate the CSR
222 # As the same CSR cannot be used twice for the same CCSID request
223 self._l10n_sa_reset_certificates()
224 self.l10n_sa_csr_errors = e.args[0] or _("Journal could not be onboarded")
225
226 def _l10n_sa_get_compliance_CSID(self, otp):
227 """
228 Request a Compliance Cryptographic Stamp Identifier (CCSID) from ZATCA
229 """
230 CCSID_data = self._l10n_sa_api_get_compliance_CSID(otp)
231 if error := self._l10n_sa_get_csid_error(CCSID_data):
232 raise UserError(_("Please check the details below and onboard the journal again: %s", error))
233
234 cert_id = self.env['certificate.certificate'].sudo().create({
235 'name': 'CCSID Certificate',
236 'content': b64decode(CCSID_data['binarySecurityToken']),
237 'private_key_id': self.company_id.sudo().l10n_sa_private_key_id.id,
238 'company_id': self.company_id.id,
239 }).id
240 self.sudo().write({
241 'l10n_sa_compliance_csid_json': json.dumps(CCSID_data),
242 'l10n_sa_compliance_csid_certificate_id': cert_id,
243 'l10n_sa_production_csid_json': False,
244 'l10n_sa_compliance_checks_passed': False,
245 })
246
247 def _l10n_sa_get_production_CSID(self, OTP=None):
248 """
249 Request a Production Cryptographic Stamp Identifier (PCSID) from ZATCA
250 """
251
252 self_sudo = self.sudo()
253
254 if not self_sudo.l10n_sa_compliance_csid_json or not self_sudo.l10n_sa_compliance_csid_certificate_id or not self_sudo.l10n_sa_compliance_checks_passed:
255 raise UserError(str(ERROR_MESSAGE))
256
257 renew = False
258 zatca_format = self.env.ref('l10n_sa_edi.edi_sa_zatca')
259
260 if self_sudo.l10n_sa_production_csid_json:
261 time_now = zatca_format._l10n_sa_get_zatca_datetime(datetime.now())
262 validity_time = self_sudo.l10n_sa_production_csid_validity
263 if zatca_format._l10n_sa_get_zatca_datetime(validity_time) < time_now:
264 renew = True
265 else:
266 raise UserError(_("The Journal is valid until (%s) and can only be renewed upon expiry.", validity_time))
267
268 CCSID_data = json.loads(self_sudo.l10n_sa_compliance_csid_json)
269 PCSID_data = self_sudo._l10n_sa_request_production_csid(CCSID_data, renew, OTP)
270 if error := self._l10n_sa_get_csid_error(PCSID_data):
271 raise UserError(_("Could not obtain Production CSID: %s", error))
272 self_sudo.l10n_sa_production_csid_json = json.dumps(PCSID_data)
273 pcsid_certificate = self_sudo.env['certificate.certificate'].create({
274 'name': 'PCSID Certificate',
275 'content': b64decode(PCSID_data['binarySecurityToken']),
276 })
277 self.l10n_sa_production_csid_certificate_id = pcsid_certificate
278
279 # ====== Compliance Checks =======
280
281 def _l10n_sa_get_compliance_files(self):
282 """
283 Return the list of files to be used for the compliance checks.
284 """
285 file_names, compliance_files = [
286 'standard/invoice.xml', 'standard/credit.xml', 'standard/debit.xml',
287 'simplified/invoice.xml', 'simplified/credit.xml', 'simplified/debit.xml',
288 ], {}
289 for file in file_names:
290 fpath = f'l10n_sa_edi/tests/compliance/{file}'
291 with file_open(fpath, 'rb', filter_ext=('.xml',)) as ip:
292 compliance_files[file] = ip.read().decode()
293 return compliance_files
294
295 def _l10n_sa_run_compliance_checks(self):
296 """
297 Run Compliance Checks once the CCSID has been obtained.
298
299 The goal of the Compliance Checks is to make sure our system is able to produce, sign and send Invoices
300 correctly. For this we use dummy invoice UBL files available under the tests/compliance folder:
301
302 Standard Invoice, Standard Credit Note, Standard Debit Note, Simplified Invoice, Simplified Credit Note,
303 Simplified Debit Note.
304
305 We read each one of these files separately, sign them, then process them through the Compliance Checks API.
306 """
307
308 self.ensure_one()
309 self_sudo = self.sudo()
310 if self.country_code != 'SA':
311 raise UserError(_("Please change the (%s)'s country to Saudi Arabia and try again.", self.company_id.name))
312 if not self_sudo.l10n_sa_compliance_csid_json or not self_sudo.l10n_sa_compliance_csid_certificate_id:
313 raise UserError(str(ERROR_MESSAGE))
314 CCSID_data = json.loads(self_sudo.l10n_sa_compliance_csid_json)
315 compliance_files = self._l10n_sa_get_compliance_files()
316 for fname, fval in compliance_files.items():
317 invoice_hash_hex = self.env['account.edi.xml.ubl_21.zatca']._l10n_sa_generate_invoice_xml_hash(
318 fval).decode()
319 digital_signature = self.env.ref('l10n_sa_edi.edi_sa_zatca')._l10n_sa_get_digital_signature(self.company_id, invoice_hash_hex).decode()
320 prepared_xml = self._l10n_sa_prepare_compliance_xml(fname, fval, self_sudo.l10n_sa_compliance_csid_certificate_id, digital_signature)
321 result = self._l10n_sa_api_compliance_checks(prepared_xml.decode(), CCSID_data)
322 if result.get('error'):
323 raise UserError(Markup("<p class='mb-0'>%s</p>") % (str(ERROR_MESSAGE)))
324 if result['validationResults']['status'] == 'WARNING':
325 warnings = Markup().join(Markup("<li><b>%(code)s</b>: %(message)s </li>") % e for e in result['validationResults']['warningMessages'])
326 self.l10n_sa_csr_errors = Markup("<br/><br/><ul class='pl-3'><b>%s</b>%s</ul>") % (_("Warnings:"), warnings)
327 elif result['validationResults']['status'] != 'PASS':
328 raise UserError(Markup("<p class='mb-0'>%s</p>") % (str(ERROR_MESSAGE)))
329 self.l10n_sa_compliance_checks_passed = True
330
331 def _l10n_sa_prepare_compliance_xml(self, xml_name, xml_raw, certificate, signature):
332 """
333 Prepare XML content to be used for Compliance checks
334 """
335 xml_content = self._l10n_sa_prepare_invoice_xml(xml_raw)
336 signed_xml = self.env.ref('l10n_sa_edi.edi_sa_zatca')._l10n_sa_sign_xml(xml_content, certificate, signature)
337 if xml_name.startswith('simplified'):
338 qr_code_str = self.env['account.move']._l10n_sa_get_qr_code(self.company_id, signed_xml, certificate, signature, True)
339 root = etree.fromstring(signed_xml)
340 qr_node = root.xpath('//*[local-name()="ID"][text()="QR"]/following-sibling::*/*')[0]
341 qr_node.text = b64encode(qr_code_str).decode()
342 return etree.tostring(root, with_tail=False)
343 return signed_xml
344
345 def _l10n_sa_prepare_invoice_xml(self, xml_content):
346 """
347 Prepare the XML content of the test invoices before running the compliance checks
348 """
349 ubl_extensions = etree.fromstring(self.env['ir.qweb']._render('l10n_sa_edi.export_sa_zatca_ubl_extensions'))
350 root = etree.fromstring(xml_content.encode())
351 root.insert(0, ubl_extensions)
352 ns_map = self.env['account.edi.xml.ubl_21.zatca']._l10n_sa_get_namespaces()
353
354 def _get_node(xpath_str):
355 return root.xpath(xpath_str, namespaces=ns_map)[0]
356
357 # Update the Company VAT number in the test invoice
358 vat_el = _get_node('//cbc:CompanyID')
359 vat_el.text = self.company_id.vat
360
361 # Update the Company Name in the test invoice
362 name_nodes = ['cac:PartyName/cbc:Name', 'cac:PartyLegalEntity/cbc:RegistrationName', 'cac:Contact/cbc:Name']
363 for node in name_nodes:
364 comp_name_el = _get_node('//cac:AccountingSupplierParty/cac:Party/' + node)
365 comp_name_el.text = self.company_id.display_name
366
367 return etree.tostring(root)
368
369 # ====== Index Chain & Previous Invoice Calculation =======
370 def _l10n_sa_edi_icv_onboarding(self):
371 """
372 Onboarding method to create or reset ICV sequence for the journal
373 """
374 self.ensure_one()
375 if self.l10n_sa_chain_sequence_id:
376 self.l10n_sa_chain_sequence_id.number_next = 1
377 message = _("Journal re-onboarded with ZATCA successfully")
378 else:
379 self.l10n_sa_chain_sequence_id = self._l10n_sa_edi_create_new_chain()
380 message = _("Journal onboarded with ZATCA successfully")
381 self.message_post(body=message)
382
383 def _l10n_sa_edi_create_new_chain(self):
384 self.ensure_one()
385 return self.env['ir.sequence'].create({
386 'name': f'ZATCA account move sequence for Journal {self.name} (id: {self.id})',
387 'code': f'l10n_sa_edi.account.move.{self.id}',
388 'implementation': 'no_gap',
389 'company_id': self.company_id.id,
390 })
391
392 def _l10n_sa_edi_get_next_chain_index(self):
393 self.ensure_one()
394 if not self.l10n_sa_chain_sequence_id:
395 self.l10n_sa_chain_sequence_id = self._l10n_sa_edi_create_new_chain()
396 return self.l10n_sa_chain_sequence_id.next_by_id()
397
398 def _l10n_sa_get_last_posted_invoice(self):
399 """
400 Returns the last invoice posted to this journal's chain.
401 That invoice may have been received by the govt or not (eg. in case of a timeout).
402 Only upon confirmed reception/refusal of that invoice can another one be posted.
403 """
404 self.ensure_one()
405 return self.env['account.move'].search(
406 [
407 ('journal_id', '=', self.id),
408 ('l10n_sa_chain_index', '!=', 0)
409 ],
410 limit=1, order='l10n_sa_chain_index desc'
411 )
412
413 # ====== API Calls to ZATCA =======
414
415 def _l10n_sa_api_get_compliance_CSID(self, otp):
416 """
417 API call to the Compliance CSID API to generate a CCSID certificate, password and compliance request_id
418 Requires a CSR token and a One Time Password (OTP)
419 """
420 self.ensure_one()
421 if not otp:
422 raise UserError(_("The OTP is invalid. Please try again."))
423 if not self.l10n_sa_csr:
424 raise UserError(str(ERROR_MESSAGE))
425 request_data = {
426 'body': json.dumps({'csr': self.l10n_sa_csr.decode()}),
427 'header': {'OTP': otp}
428 }
429 return self._l10n_sa_call_api(request_data, ZATCA_API_URLS['apis']['ccsid'], 'POST')
430
431 def _l10n_sa_api_get_production_CSID(self, CCSID_data):
432 """
433 API call to the Production CSID API to generate a PCSID certificate, password and production request_id
434 Requires a requestID from the Compliance CSID API
435 """
436 request_data = {
437 'body': json.dumps({'compliance_request_id': str(CCSID_data['requestID'])}),
438 'header': {'Authorization': self._l10n_sa_authorization_header(CCSID_data)}
439 }
440 return self._l10n_sa_call_api(request_data, ZATCA_API_URLS['apis']['pcsid'], 'POST')
441
442 def _l10n_sa_api_renew_production_CSID(self, PCSID_data, OTP):
443 """
444 API call to the Production CSID API to renew a PCSID certificate, password and production request_id
445 Requires an expired Production CSIDPCSID_data
446 """
447 self.ensure_one()
448 auth_data = PCSID_data
449 # For renewal, the sandbox API expects a specific Username/Password, which are set in the SANDBOX_AUTH dict
450 if self.company_id.l10n_sa_api_mode == 'sandbox':
451 auth_data = SANDBOX_AUTH
452 request_data = {
453 'body': json.dumps({'csr': self.l10n_sa_csr.decode()}),
454 'header': {
455 'OTP': OTP,
456 'Authorization': self._l10n_sa_authorization_header(auth_data)
457 }
458 }
459 return self._l10n_sa_call_api(request_data, ZATCA_API_URLS['apis']['pcsid'], 'PATCH')
460
461 def _l10n_sa_api_compliance_checks(self, xml_content, CCSID_data):
462 """
463 API call to the COMPLIANCE endpoint to generate a security token used for subsequent API calls
464 Requires a CSR token and a One Time Password (OTP)
465 """
466 invoice_tree = etree.fromstring(xml_content)
467
468 # Get the Invoice Hash from the XML document
469 invoice_hash_node = invoice_tree.xpath('//*[@Id="invoiceSignedData"]/*[local-name()="DigestValue"]')[0]
470 invoice_hash = invoice_hash_node.text
471
472 # Get the Invoice UUID from the XML document
473 invoice_uuid_node = invoice_tree.xpath('//*[local-name()="UUID"]')[0]
474 invoice_uuid = invoice_uuid_node.text
475
476 request_data = {
477 'body': json.dumps({
478 "invoiceHash": invoice_hash,
479 "uuid": invoice_uuid,
480 "invoice": b64encode(xml_content.encode()).decode()
481 }),
482 'header': {
483 'Authorization': self._l10n_sa_authorization_header(CCSID_data),
484 'Clearance-Status': '1'
485 }
486 }
487 return self._l10n_sa_call_api(request_data, ZATCA_API_URLS['apis']['compliance'], 'POST')
488
489 def _l10n_sa_get_api_clearance_url(self, invoice):
490 """
491 Return the API to be used for clearance. To be overridden to account for other cases, such as reporting.
492 """
493 return ZATCA_API_URLS['apis']['reporting' if invoice._l10n_sa_is_simplified() else 'clearance']
494
495 def _l10n_sa_api_clearance(self, invoice, xml_content, PCSID_data):
496 """
497 API call to the CLEARANCE/REPORTING endpoint to sign an invoice
498 - If SIMPLIFIED invoice: Reporting
499 - If STANDARD invoice: Clearance
500 """
501 invoice_tree = etree.fromstring(xml_content)
502 invoice_hash_node = invoice_tree.xpath('//*[@Id="invoiceSignedData"]/*[local-name()="DigestValue"]')[0]
503 invoice_hash = invoice_hash_node.text
504 request_data = {
505 'body': json.dumps({
506 "invoiceHash": invoice_hash,
507 "uuid": invoice.l10n_sa_uuid,
508 "invoice": b64encode(xml_content.encode()).decode()
509 }),
510 'header': {
511 'Authorization': self._l10n_sa_authorization_header(PCSID_data),
512 'Clearance-Status': '1'
513 }
514 }
515 url_string = self._l10n_sa_get_api_clearance_url(invoice)
516 return self._l10n_sa_call_api(request_data, url_string, 'POST')
517
518 # ====== Certificate Methods =======
519
520 def _l10n_sa_request_production_csid(self, csid_data, renew=False, otp=None):
521 """
522 Generate company Production CSID data
523 """
524 self.ensure_one()
525 return (
526 self._l10n_sa_api_renew_production_CSID(csid_data, otp)
527 if renew
528 else self._l10n_sa_api_get_production_CSID(csid_data)
529 )
530
531 def _l10n_sa_api_get_pcsid(self):
532 """
533 Get CSIDs required to perform ZATCA api calls, and regenerate them if they need to be regenerated.
534 """
535 self.ensure_one()
536 self_sudo = self.sudo()
537 if not self_sudo.l10n_sa_production_csid_json or not self_sudo.l10n_sa_production_csid_certificate_id:
538 raise UserError(str(ERROR_MESSAGE))
539 certificate = self_sudo.l10n_sa_production_csid_certificate_id
540 if not certificate.is_valid and self.company_id.l10n_sa_api_mode != 'sandbox':
541 raise UserError(_("The Journal is not valid anymore. Please Renew it."))
542 return json.loads(self_sudo.l10n_sa_production_csid_json), certificate.id
543
544 # ====== API Helper Methods =======
545
546 def _l10n_sa_call_api(self, request_data, request_url, method):
547 """
548 Helper function to make api calls to the ZATCA API Endpoint
549 """
550 api_url = ZATCA_API_URLS[self.company_id.l10n_sa_api_mode]
551 request_url = urljoin(api_url, request_url)
552 status_code = False
553 try:
554 request_response = requests.request(method, request_url, data=request_data.get('body'),
555 headers={
556 **self._l10n_sa_api_headers(),
557 **request_data.get('header')
558 }, timeout=30)
559 request_response.raise_for_status()
560 except (ValueError, HTTPError) as ex:
561 # The 400 case means that it is rejected by ZATCA, but we need to update the hash as done for accepted.
562 # In the 401+ cases, it is like the server is overloaded e.g. and we still need to resend later. We do not
563 # erase the index chain (excepted) because for ZATCA, one ICV (index chain) needs to correspond to one invoice.
564 if (status_code := ex.response.status_code) not in {400, 409}:
565 return {
566 'error': (Markup("<b>[%s]</b>") % status_code) + _("Server returned an unexpected error: %(error)s",
567 error=(request_response.text or str(ex))),
568 'blocking_level': 'warning',
569 'status_code': status_code,
570 'excepted': True,
571 }
572 except RequestException as ex:
573 # Usually only happens if a Timeout occurs. In this case we're not sure if the invoice was accepted or
574 # rejected, or if it even made it to ZATCA
575 return {'error': str(ex), 'blocking_level': 'warning', 'excepted': True}
576
577 if request_response.status_code == '303':
578 return {'error': _('Clearance and reporting seem to have been mixed up. '),
579 'blocking_level': 'warning', 'excepted': True}
580
581 try:
582 response_data = request_response.json()
583 except json.decoder.JSONDecodeError:
584 return {
585 'error': _("JSON response from ZATCA could not be decoded"),
586 'blocking_level': 'error'
587 }
588 response_data['status_code'] = request_response.status_code
589
590 if status_code == 409:
591 return response_data
592
593 val_res = response_data.get('validationResults', {})
594 if not request_response.ok and (val_res.get('errorMessages') or val_res.get('warningMessages')):
595 error = "" if not status_code else Markup("<b>[%s]</b>") % (status_code)
596 if isinstance(response_data, dict) and val_res.get('errorMessages'):
597 error += _("Invoice submission to ZATCA returned errors")
598 return {
599 'error': error,
600 'json_errors': response_data,
601 'blocking_level': 'error',
602 }
603 error += request_response.reason
604 return {
605 'error': error,
606 'blocking_level': 'error',
607 }
608 return response_data
609
610 def _l10n_sa_api_headers(self):
611 """
612 Return the base headers to be included in ZATCA API calls
613 """
614 return {
615 'Content-Type': 'application/json',
616 'Accept-Language': 'en',
617 'Accept-Version': 'V2'
618 }
619
620 def _l10n_sa_authorization_header(self, CSID_data):
621 """
622 Compute the Authorization header by combining the CSID and the Secret key, then encode to Base64
623 """
624 auth_data = CSID_data
625 auth_str = "%s:%s" % (auth_data['binarySecurityToken'], auth_data['secret'])
626 return 'Basic ' + b64encode(auth_str.encode()).decode()
627
628 def _l10n_sa_load_edi_demo_data(self):
629 self.ensure_one()
630 self.company_id.l10n_sa_private_key_id = self.env['certificate.key']._generate_ec_private_key(self.company_id)
631 self.write({
632 'l10n_sa_compliance_checks_passed': True,
633 'l10n_sa_csr': b'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS0KTUlJQ2NqQ0NBaGNDQVFBd2djRXhDekFKQmdOVkJBWVRBbE5CTVJNd0VRWURWUVFMREFvek1UQXhOelV6T1RjMApNUk13RVFZRFZRUUtEQXBUUVNCRGIyMXdZVzU1TVJNd0VRWURWUVFEREFwVFFTQkRiMjF3WVc1NU1SZ3dGZ1lEClZRUmhEQTh6TVRBeE56VXpPVGMwTURBd01ETXhEekFOQmdOVkJBZ01CbEpwZVdGa2FERklNRVlHQTFVRUJ3dy8KdzVqQ3A4T1o0b0NldzVuaWdLYkRtTUt2dzVuRm9NT1o0b0NndzVqQ3FTRERtTUtudzVuaWdKN0RtZUtBcHNPWgo0b0NndzVuTGhzT1l3ckhEbU1LcE1GWXdFQVlIS29aSXpqMENBUVlGSzRFRUFBb0RRZ0FFN2ZpZWZWQ21HcTlzCmV0OVl4aWdQNzZWUmJxZlh0VWNtTk1VN3FkTlBiSm5NNGh5R1QwanpPcXUrSWNXWW5IelFJYmxJVmsydENPQnQKYjExanY4MGVwcUNCOVRDQjhnWUpLb1pJaHZjTkFRa09NWUhrTUlIaE1DUUdDU3NHQVFRQmd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I5bUsyWWJZcVNEWXA5bUUyWVhaaHRtSTJMSFlxVEJXTUJBR0J5cUdTTTQ5QWdFR0JTdUJCQUFLQTBJQUJOVlB3N0hGNjhUVWtQTkJQb29uT0Y2NnRPMm5IcmxUNlRMcmk3MEpLY1MvYmVMWitoRVE0MmdXdUtYckp5RmxnWm9kUVJzTFQyMEtQZnE0Q3N2YlFJMmpnY3d3Z2Nrd0RBWURWUjBUQVFIL0JBSXdBRENCdUFZRFZSMFJCSUd3TUlHdHBJR3FNSUduTVRRd01nWURWUVFFRENzeExVOWtiMjk4TWkweE5Yd3pMVk5KUkVrekxVTkNUVkJTTFV3eVJEaFlMVXROTUV0T0xWZzBTVk5LTVI4d0hRWUtDWkltaVpQeUxHUUJBUXdQTXprNU9UazVPVGs1T1RBd01EQXpNUTB3Q3dZRFZRUU1EQVF4TVRBd01TOHdMUVlEVlFRYURDWkJiQ0JCYldseUlFMXZhR0Z0YldWa0lFSnBiaUJCWW1SMWJDQkJlbWw2SUZOMGNtVmxkREVPTUF3R0ExVUVEd3dGVDNSb1pYSXdDZ1lJS29aSXpqMEVBd0lEU0FBd1JRSWdTeVhlZExqOUtMVTRUMWFBbVQvL09GZDBGWWxLQnIraFFIeGNDM0c2ajc4Q0lRRGdlNjNsQkVqTU1ETktqTm1pTklaQlBWSnlHRzl5bVJaSHdvUzV5TEQyZXc9PQ==", "secret": "uMpSz85cV0h/e/uqpJ+FaZkdYZ76uoaRYOevGufcup0=", "errors": null}""",
635 'l10n_sa_production_csid_json': """{"requestID": 30368, "tokenType": "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3", "dispositionMessage": "ISSUED", "binarySecurityToken": "TUlJRDNqQ0NBNFNnQXdJQkFnSVRFUUFBT0FQRjkwQWpzL3hjWHdBQkFBQTRBekFLQmdncWhrak9QUVFEQWpCaU1SVXdFd1lLQ1pJbWlaUHlMR1FCR1JZRmJHOWpZV3d4RXpBUkJnb0praWFKay9Jc1pBRVpG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