Debian Codegraph @

addons/l10n_sa_edi/models/account_edi_xml_ubl_21_zatca.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 from hashlib import sha256
3 from base64 import b64encode
4 from lxml import etree
5 from odoo import models, fields
6 from odoo.tools.misc import file_path
7 import re
8
9 TAX_EXEMPTION_CODES = ['VATEX-SA-29', 'VATEX-SA-29-7', 'VATEX-SA-30']
10 TAX_ZERO_RATE_CODES = ['VATEX-SA-32', 'VATEX-SA-33', 'VATEX-SA-34-1', 'VATEX-SA-34-2', 'VATEX-SA-34-3', 'VATEX-SA-34-4',
11 'VATEX-SA-34-5', 'VATEX-SA-35', 'VATEX-SA-36', 'VATEX-SA-EDU', 'VATEX-SA-HEA']
12
13 PAYMENT_MEANS_CODE = {
14 'bank': 42,
15 'card': 48,
16 'cash': 10,
17 'transfer': 30,
18 'unknown': 1
19 }
20
21
22 class AccountEdiXmlUbl_21Zatca(models.AbstractModel):
23 _name = 'account.edi.xml.ubl_21.zatca'
24 _inherit = ['account.edi.xml.ubl_21']
25 _description = "UBL 2.1 (ZATCA)"
26
27 # -------------------------------------------------------------------------
28 # EXPORT
29 # -------------------------------------------------------------------------
30
31 def _export_invoice_filename(self, invoice):
32 """
33 Generate the name of the invoice XML file according to ZATCA business rules:
34 Seller Vat Number (BT-31), Date (BT-2), Time (KSA-25), Invoice Number (BT-1)
35 """
36 vat = invoice.company_id.partner_id.commercial_partner_id.vat
37 invoice_number = re.sub(r'[^a-zA-Z0-9 -]+', '-', invoice.name)
38 invoice_date = fields.Datetime.context_timestamp(self.with_context(tz='Asia/Riyadh'), invoice.l10n_sa_confirmation_datetime)
39 file_name = f"{vat}_{invoice_date.strftime('%Y%m%dT%H%M%S')}_{invoice_number}"
40 file_format = self.env.context.get('l10n_sa_file_format', 'xml')
41 if file_format:
42 file_name = f'{file_name}.{file_format}'
43 return file_name
44
45 def _add_invoice_config_vals(self, vals):
46 super()._add_invoice_config_vals(vals)
47 vals['document_type'] = 'invoice' # Only use Invoice in ZATCA, even for credit and debit notes
48
49 def _add_invoice_base_lines_vals(self, vals):
50 super()._add_invoice_base_lines_vals(vals)
51 invoice = vals['invoice']
52
53 # Filter out prepayment lines of final invoices
54 if not invoice._is_downpayment():
55 vals['base_lines'] = [
56 base_line
57 for base_line in vals['base_lines']
58 if not base_line['record']._get_downpayment_lines()
59 ]
60
61 # Get downpayment moves' base lines
62 if not invoice._is_downpayment():
63 prepayment_moves = invoice.line_ids._get_downpayment_lines().move_id.filtered(lambda m: m.move_type == 'out_invoice')
64 else:
65 prepayment_moves = self.env['account.move']
66
67 prepayment_moves_base_lines = {}
68 for prepayment_move in prepayment_moves:
69 prepayment_move_base_lines, _dummy = prepayment_move._get_rounded_base_and_tax_lines()
70 prepayment_moves_base_lines[prepayment_move] = prepayment_move_base_lines
71
72 vals['prepayment_moves_base_lines'] = prepayment_moves_base_lines
73
74 def _add_document_tax_grouping_function_vals(self, vals):
75 # OVERRIDE account.edi.xml.ubl_21
76
77 # Always ignore withholding taxes in the UBL
78 def total_grouping_function(base_line, tax_data):
79 if tax_data and tax_data['tax'].l10n_sa_is_retention:
80 return None
81 return True
82
83 def tax_grouping_function(base_line, tax_data):
84 tax = tax_data and tax_data['tax']
85
86 # Ignore withholding taxes
87 if tax and tax.l10n_sa_is_retention:
88 return None
89 return {
90 'tax_category_code': self._get_tax_category_code(vals['customer'].commercial_partner_id, vals['supplier'], tax),
91 **self._get_tax_exemption_reason(vals['customer'].commercial_partner_id, vals['supplier'], tax),
92 'amount': tax.amount if tax else 0.0,
93 'amount_type': tax.amount_type if tax else 'percent',
94 }
95
96 vals['total_grouping_function'] = total_grouping_function
97 vals['tax_grouping_function'] = tax_grouping_function
98
99 # -------------------------------------------------------------------------
100 # EXPORT: Helpers
101 # -------------------------------------------------------------------------
102
103 def _get_tax_category_code(self, customer, supplier, tax):
104 """ Override to include/update values specific to ZATCA's UBL 2.1 specs """
105 if supplier.country_id.code == 'SA':
106 if tax and tax.amount != 0:
107 return 'S'
108 elif tax and tax.l10n_sa_exemption_reason_code in TAX_EXEMPTION_CODES:
109 return 'E'
110 elif tax and tax.l10n_sa_exemption_reason_code in TAX_ZERO_RATE_CODES:
111 return 'Z'
112 else:
113 return 'O'
114 return super()._get_tax_category_code(customer, supplier, tax)
115
116 def _get_tax_exemption_reason(self, customer, supplier, tax):
117 if supplier.country_id.code == 'SA':
118 if tax and tax.amount == 0:
119 exemption_reason_by_code = dict(tax._fields["l10n_sa_exemption_reason_code"]._description_selection(self.env))
120 code = tax.l10n_sa_exemption_reason_code
121 return {
122 'tax_exemption_reason_code': code or "VATEX-SA-OOS",
123 'tax_exemption_reason': (
124 exemption_reason_by_code[code].split(code)[1].lstrip()
125 if code else "Not subject to VAT"
126 )
127 }
128 else:
129 return {
130 'tax_exemption_reason_code': None,
131 'tax_exemption_reason': None,
132 }
133
134 return super()._get_tax_exemption_reason(customer, supplier, tax)
135
136 def _is_document_allowance_charge(self, base_line):
137 return base_line['special_type'] == 'early_payment' or base_line['tax_details']['total_excluded_currency'] < 0
138
139 # -------------------------------------------------------------------------
140 # EXPORT: Templates for document header nodes
141 # -------------------------------------------------------------------------
142
143 def _add_invoice_header_nodes(self, document_node, vals):
144 super()._add_invoice_header_nodes(document_node, vals)
145 invoice = vals['invoice']
146 issue_date = fields.Datetime.context_timestamp(self.with_context(tz='Asia/Riyadh'), invoice.l10n_sa_confirmation_datetime)
147
148 document_node.update({
149 'cbc:ProfileID': {'_text': 'reporting:1.0'},
150 'cbc:UUID': {'_text': invoice.l10n_sa_uuid},
151 'cbc:IssueDate': {'_text': issue_date.strftime('%Y-%m-%d')},
152 'cbc:IssueTime': {'_text': issue_date.strftime('%H:%M:%S')},
153 'cbc:DueDate': None,
154 'cbc:InvoiceTypeCode': {
155 '_text': (
156 383 if invoice.debit_origin_id else
157 381 if invoice.move_type == 'out_refund' else
158 386 if invoice._is_downpayment() else 388
159 ),
160 'name': '0%s00%s00' % (
161 '2' if invoice._l10n_sa_is_simplified() else '1',
162 '1' if invoice.commercial_partner_id.country_id != invoice.company_id.country_id and not invoice._l10n_sa_is_simplified() else '0'
163 ),
164 },
165 'cbc:TaxCurrencyCode': {'_text': vals['company_currency_id'].name},
166 'cac:OrderReference': None,
167 'cac:BillingReference': {
168 'cac:InvoiceDocumentReference': {
169 'cbc:ID': {
170 '_text': (invoice.reversed_entry_id.name or invoice.ref)
171 if invoice.move_type == 'out_refund'
172 else invoice.debit_origin_id.name
173 }
174 }
175 } if invoice.move_type == 'out_refund' or invoice.debit_origin_id else None,
176 'cac:AdditionalDocumentReference': [
177 {
178 'cbc:ID': {'_text': 'QR'},
179 'cac:Attachment': {
180 'cbc:EmbeddedDocumentBinaryObject': {
181 '_text': 'N/A',
182 'mimeCode': 'text/plain',
183 }
184 }
185 } if invoice._l10n_sa_is_simplified() else None,
186 {
187 'cbc:ID': {'_text': 'PIH'},
188 'cac:Attachment': {
189 'cbc:EmbeddedDocumentBinaryObject': {
190 '_text': (
191 "NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ=="
192 if invoice.company_id.l10n_sa_api_mode == 'sandbox' or not invoice.journal_id.l10n_sa_latest_submission_hash
193 else invoice.journal_id.l10n_sa_latest_submission_hash
194 ),
195 'mimeCode': 'text/plain',
196 }
197 }
198 },
199 {
200 'cbc:ID': {'_text': 'ICV'},
201 'cbc:UUID': {'_text': invoice.l10n_sa_chain_index},
202 }
203 ],
204 'cac:Signature': {
205 'cbc:ID': {'_text': "urn:oasis:names:specification:ubl:signature:Invoice"},
206 'cbc:SignatureMethod': {'_text': "urn:oasis:names:specification:ubl:dsig:enveloped:xades"},
207 } if invoice._l10n_sa_is_simplified() else None,
208 'cac:PaymentTerms': None,
209 })
210
211 def _add_invoice_delivery_nodes(self, document_node, vals):
212 super()._add_invoice_delivery_nodes(document_node, vals)
213 invoice = vals['invoice']
214 if 'cac:Delivery' in document_node:
215 if document_node['cac:Delivery']['cac:DeliveryLocation']:
216 document_node['cac:Delivery']['cac:DeliveryLocation'] = None
217
218 if not document_node['cac:Delivery']['cbc:ActualDeliveryDate']['_text']:
219 document_node['cac:Delivery']['cbc:ActualDeliveryDate'] = {'_text': invoice.invoice_date}
220
221 def _add_invoice_payment_means_nodes(self, document_node, vals):
222 """ Override to include/update values specific to ZATCA's UBL 2.1 specs """
223 super()._add_invoice_payment_means_nodes(document_node, vals)
224 payment_means_node = document_node['cac:PaymentMeans']
225 invoice = vals['invoice']
226
227 payment_means_node['cbc:PaymentMeansCode'] = {
228 '_text': PAYMENT_MEANS_CODE.get(
229 self._l10n_sa_get_payment_means_code(invoice),
230 PAYMENT_MEANS_CODE['unknown']
231 ),
232 'listID': 'UN/ECE 4461',
233 }
234 payment_means_node['cbc:InstructionNote'] = {'_text': invoice._l10n_sa_get_adjustment_reason()}
235
236 def _get_address_node(self, vals):
237 partner = vals['partner']
238 country = partner['country' if partner._name == 'res.bank' else 'country_id']
239 state = partner['state' if partner._name == 'res.bank' else 'state_id']
240 building_number = partner.l10n_sa_edi_building_number if partner._name == 'res.partner' else ''
241 edi_plot_identification = partner.l10n_sa_edi_plot_identification if partner._name == 'res.partner' else ''
242
243 return {
244 'cbc:StreetName': {'_text': partner.street},
245 'cbc:BuildingNumber': {'_text': building_number},
246 'cbc:PlotIdentification': {'_text': edi_plot_identification},
247 'cbc:CitySubdivisionName': {'_text': partner.street2},
248 'cbc:CityName': {'_text': partner.city},
249 'cbc:PostalZone': {'_text': partner.zip},
250 'cbc:CountrySubentity': {'_text': state.name},
251 'cbc:CountrySubentityCode': {'_text': state.code},
252 'cac:AddressLine': None,
253 'cac:Country': {
254 'cbc:IdentificationCode': {'_text': country.code},
255 'cbc:Name': {'_text': country.name},
256 }
257 }
258
259 def _get_partner_party_identification_number(self, partner):
260 """ Override to include/update values specific to ZATCA's UBL 2.1 specs """
261 identification_number = partner.l10n_sa_edi_additional_identification_number
262 vat = re.sub(r'[^a-zA-Z0-9]', '', partner.vat or "")
263 if partner.country_code != "SA" and vat:
264 identification_number = vat
265 elif partner.l10n_sa_edi_additional_identification_scheme == 'TIN':
266 # according to ZATCA, the TIN number is always the first 10 digits of the VAT number
267 identification_number = vat[:10]
268 return identification_number
269
270 def _get_party_node(self, vals):
271 partner = vals['partner']
272 role = vals['role']
273 commercial_partner = partner.commercial_partner_id
274
275 party_node = {}
276
277 if identification_number := self._get_partner_party_identification_number(commercial_partner):
278 party_node['cac:PartyIdentification'] = {
279 'cbc:ID': {
280 '_text': identification_number,
281 'schemeID': commercial_partner.l10n_sa_edi_additional_identification_scheme,
282 }
283 }
284
285 party_node.update({
286 'cac:PartyName': {
287 'cbc:Name': {'_text': partner.display_name}
288 },
289 'cac:PostalAddress': self._get_address_node(vals),
290 'cac:PartyTaxScheme': {
291 'cbc:RegistrationName': {'_text': commercial_partner.name},
292 'cbc:CompanyID': {'_text': commercial_partner.vat},
293 'cac:RegistrationAddress': self._get_address_node({'partner': commercial_partner}),
294 'cac:TaxScheme': {
295 'cbc:ID': {'_text': 'VAT'}
296 }
297 } if (role != 'customer' or partner.country_id.code == 'SA') and commercial_partner.vat and commercial_partner.vat != '/' else None, # BR-KSA-46
298 'cac:PartyLegalEntity': {
299 'cbc:RegistrationName': {'_text': commercial_partner.name},
300 'cbc:CompanyID': {'_text': commercial_partner.vat} if commercial_partner.country_code == 'SA' else None,
301 'cac:RegistrationAddress': self._get_address_node({'partner': commercial_partner}),
302 },
303 'cac:Contact': {
304 'cbc:ID': {'_text': partner.id},
305 'cbc:Name': {'_text': partner.name},
306 'cbc:Telephone': {
307 '_text': re.sub(r"[^+\d]", '', partner.phone) if partner.phone else None
308 },
309 'cbc:ElectronicMail': {'_text': partner.email},
310 }
311 })
312 return party_node
313
314 def _l10n_sa_get_payment_means_code(self, invoice):
315 """ Return payment means code to be used to set the value on the XML file """
316 return 'unknown'
317
318 # -------------------------------------------------------------------------
319 # EXPORT: Templates for document amount nodes
320 # -------------------------------------------------------------------------
321
322 def _add_document_tax_total_nodes(self, document_node, vals):
323 super()._add_document_tax_total_nodes(document_node, vals)
324
325 document_node['cac:TaxTotal'] = [document_node['cac:TaxTotal']]
326
327 self._add_tax_total_node_in_company_currency(document_node, vals)
328 document_node['cac:TaxTotal'][1]['cac:TaxSubtotal'] = None
329
330 def _add_invoice_monetary_total_nodes(self, document_node, vals):
331 super()._add_invoice_monetary_total_nodes(document_node, vals)
332
333 monetary_total_tag = 'cac:LegalMonetaryTotal' if vals['document_type'] in {'invoice', 'credit_note'} else 'cac:RequestedMonetaryTotal'
334 monetary_total_node = document_node[monetary_total_tag]
335
336 # Compute the prepaid amount
337 prepaid_amount = 0.0
338 AccountTax = self.env['account.tax']
339 for prepayment_move_base_lines in vals['prepayment_moves_base_lines'].values():
340 # Compute prepayment moves' totals
341 prepayment_moves_base_lines_aggregated_tax_details = AccountTax._aggregate_base_lines_tax_details(
342 prepayment_move_base_lines,
343 vals['total_grouping_function'],
344 )
345 prepayment_moves_total_aggregated_tax_details = AccountTax._aggregate_base_lines_aggregated_values(prepayment_moves_base_lines_aggregated_tax_details)
346 for grouping_key, values in prepayment_moves_total_aggregated_tax_details.items():
347 if grouping_key:
348 prepaid_amount += values['base_amount_currency'] + values['tax_amount_currency']
349
350 # AllowanceTotalAmount is always present even if 0.0
351 monetary_total_node['cbc:AllowanceTotalAmount'] = {
352 '_text': self.format_float(vals['total_allowance_currency'], vals['currency_dp']),
353 'currencyID': vals['currency_name'],
354 }
355 monetary_total_node['cbc:PrepaidAmount']['_text'] = self.format_float(prepaid_amount, vals['currency_dp'])
356 monetary_total_node['cbc:PayableAmount']['_text'] = self.format_float(vals['tax_inclusive_amount_currency'] - prepaid_amount, vals['currency_dp'])
357
358 # -------------------------------------------------------------------------
359 # EXPORT: Templates for document allowance charge nodes
360 # -------------------------------------------------------------------------
361
362 def _get_document_allowance_charge_node(self, vals):
363 """ Charge Reasons & Codes (As per ZATCA):
364 https://unece.org/fileadmin/DAM/trade/untdid/d16b/tred/tred5189.htm
365 As far as ZATCA is concerned, we calculate Allowance/Charge vals for global discounts as
366 a document level allowance, and we do not include any other charges or allowances.
367 """
368 base_line = vals['base_line']
369 aggregated_tax_details = self.env['account.tax']._aggregate_base_line_tax_details(base_line, vals['tax_grouping_function'])
370
371 base_amount_currency = base_line['tax_details']['total_excluded_currency']
372 if base_line['special_type'] == 'early_payment':
373 return super()._get_document_allowance_charge_node(vals)
374 elif base_amount_currency < 0:
375 return {
376 'cbc:ChargeIndicator': {'_text': 'false'},
377 'cbc:AllowanceChargeReasonCode': {'_text': '95'},
378 'cbc:AllowanceChargeReason': {'_text': 'Discount'},
379 'cbc:Amount': {
380 '_text': self.format_float(abs(base_amount_currency), 2),
381 'currencyID': vals['currency_id'].name,
382 },
383 'cac:TaxCategory': [
384 self._get_tax_category_node({**vals, 'grouping_key': grouping_key})
385 for grouping_key in aggregated_tax_details
386 if grouping_key
387 ]
388 }
389
390 # -------------------------------------------------------------------------
391 # EXPORT: Templates for document line nodes
392 # -------------------------------------------------------------------------
393
394 def _add_invoice_line_nodes(self, document_node, vals):
395 document_line_tag = self._get_tags_for_document_type(vals)['document_line']
396 document_node[document_line_tag] = []
397 line_idx = 1
398
399 # First: the non-prepayment lines from the invoice
400 for base_line in vals['base_lines']:
401 if not self._is_document_allowance_charge(base_line):
402 line_vals = {
403 **vals,
404 'line_idx': line_idx,
405 'base_line': base_line,
406 }
407 self._add_invoice_line_vals(line_vals)
408
409 line_node = {}
410 self._add_invoice_line_id_nodes(line_node, line_vals)
411 self._add_invoice_line_amount_nodes(line_node, line_vals)
412 self._add_invoice_line_period_nodes(line_node, line_vals)
413 self._add_invoice_line_allowance_charge_nodes(line_node, line_vals)
414 self._add_invoice_line_tax_total_nodes(line_node, line_vals)
415 self._add_invoice_line_item_nodes(line_node, line_vals)
416 self._add_invoice_line_tax_category_nodes(line_node, line_vals)
417 self._add_invoice_line_price_nodes(line_node, line_vals)
418 self._add_invoice_line_pricing_reference_nodes(line_node, line_vals)
419
420 document_node[document_line_tag].append(line_node)
421 line_idx += 1
422
423 # Then: all the prepayment adjustments
424 for prepayment_move, prepayment_move_base_lines in vals['prepayment_moves_base_lines'].items():
425 document_node[document_line_tag].append(
426 self._get_prepayment_line_node({
427 **vals,
428 'line_idx': line_idx,
429 'prepayment_move': prepayment_move,
430 'prepayment_move_base_lines': prepayment_move_base_lines,
431 })
432 )
433 line_idx += 1
434
435 def _add_document_line_tax_total_nodes(self, line_node, vals):
436 base_line = vals['base_line']
437 aggregated_tax_details = self.env['account.tax']._aggregate_base_line_tax_details(base_line, vals['tax_grouping_function'])
438
439 total_tax_amount = sum(
440 values['tax_amount_currency']
441 for grouping_key, values in aggregated_tax_details.items()
442 if grouping_key
443 )
444 total_base_amount = sum(
445 values['base_amount_currency']
446 for grouping_key, values in aggregated_tax_details.items()
447 if grouping_key
448 )
449 total_amount = total_base_amount + total_tax_amount
450
451 line_node['cac:TaxTotal'] = {
452 'cbc:TaxAmount': {
453 '_text': self.format_float(total_tax_amount, vals['currency_dp']),
454 'currencyID': vals['currency_name'],
455 },
456 'cbc:RoundingAmount': {
457 # This should simply contain the net (base + tax) amount for the line.
458 '_text': self.format_float(total_amount, vals['currency_dp']),
459 'currencyID': vals['currency_name'],
460 },
461 # No TaxSubtotal: BR-KSA-80: only downpayment lines should have a tax subtotal breakdown.
462 }
463
464 def _add_document_line_item_nodes(self, line_node, vals):
465 super()._add_document_line_item_nodes(line_node, vals)
466 product = vals['base_line']['product_id']
467 line_node['cac:Item']['cac:SellersItemIdentification'] = {
468 'cbc:ID': {'_text': product.code or product.default_code},
469 }
470
471 def _add_document_line_tax_category_nodes(self, line_node, vals):
472 base_line = vals['base_line']
473 aggregated_tax_details = self.env['account.tax']._aggregate_base_line_tax_details(base_line, vals['tax_grouping_function'])
474
475 line_node['cac:Item']['cac:ClassifiedTaxCategory'] = [
476 self._get_tax_category_node({**vals, 'grouping_key': grouping_key})
477 for grouping_key in aggregated_tax_details
478 if grouping_key
479 ]
480
481 def _get_prepayment_line_node(self, vals):
482 prepayment_move = vals['prepayment_move']
483
484 AccountTax = self.env['account.tax']
485 prepayment_moves_base_lines_aggregated_tax_details = AccountTax._aggregate_base_lines_tax_details(
486 vals['prepayment_move_base_lines'],
487 vals['tax_grouping_function'],
488 )
489 aggregated_tax_details = AccountTax._aggregate_base_lines_aggregated_values(prepayment_moves_base_lines_aggregated_tax_details)
490
491 prepayment_move_issue_date = fields.Datetime.context_timestamp(
492 self.with_context(tz='Asia/Riyadh'),
493 prepayment_move.l10n_sa_confirmation_datetime
494 )
495
496 return {
497 'cbc:ID': {'_text': vals['line_idx']},
498 'cbc:InvoicedQuantity': {
499 '_text': '1.0',
500 'unitCode': 'C62',
501 },
502 'cbc:LineExtensionAmount': {
503 '_text': '0.00',
504 'currencyID': vals['currency_name'],
505 },
506 'cac:DocumentReference': {
507 'cbc:ID': {'_text': prepayment_move.name},
508 'cbc:IssueDate': {
509 '_text': prepayment_move_issue_date.strftime('%Y-%m-%d') if prepayment_move_issue_date else None
510 },
511 'cbc:IssueTime': {
512 '_text': prepayment_move_issue_date.strftime('%H:%M:%S') if prepayment_move_issue_date else None
513 },
514 'cbc:DocumentTypeCode': {'_text': '386'},
515 },
516 'cac:TaxTotal': self._get_prepayment_line_tax_total_node({**vals, 'aggregated_tax_details': aggregated_tax_details}),
517 'cac:Item': {
518 'cbc:Description': {'_text': "Down Payment"},
519 'cbc:Name': {'_text': "Down Payment"},
520 'cac:ClassifiedTaxCategory': [
521 self._get_tax_category_node({**vals, 'grouping_key': grouping_key})
522 for grouping_key in aggregated_tax_details
523 ]
524 },
525 'cac:Price': {
526 'cbc:PriceAmount': {
527 '_text': '0',
528 'currencyID': vals['currency_name'],
529 }
530 },
531 }
532
533 def _get_prepayment_line_tax_total_node(self, vals):
534 # Compute prepayment move subtotals by tax category
535 aggregated_tax_details = vals['aggregated_tax_details']
536
537 return {
538 'cbc:TaxAmount': {
539 '_text': '0.00',
540 'currencyID': vals['currency_name'],
541 },
542 'cbc:RoundingAmount': {
543 '_text': '0.00',
544 'currencyID': vals['currency_name'],
545 },
546 'cac:TaxSubtotal': [
547 {
548 'cbc:TaxableAmount': {
549 '_text': self.format_float(values['base_amount_currency'], vals['currency_dp']),
550 'currencyID': vals['currency_name'],
551 },
552 'cbc:TaxAmount': {
553 '_text': self.format_float(values['tax_amount_currency'], vals['currency_dp']),
554 'currencyID': vals['currency_name'],
555 },
556 'cbc:Percent': {'_text': grouping_key['amount']},
557 'cac:TaxCategory': self._get_tax_category_node({**vals, 'grouping_key': grouping_key}),
558 }
559 for grouping_key, values in aggregated_tax_details.items()
560 if grouping_key
561 ],
562 }
563
564 def _add_document_line_price_nodes(self, line_node, vals):
565 """
566 Use 10 decimal places for PriceAmount to satisfy ZATCA validation BR-KSA-EN16931-11
567 """
568 currency_suffix = vals['currency_suffix']
569 line_node['cac:Price'] = {
570 'cbc:PriceAmount': {
571 '_text': round(vals[f'gross_price_unit{currency_suffix}'], 10),
572 'currencyID': vals['currency_name'],
573 },
574 }
575
576 # -------------------------------------------------------------------------
577 # EXPORT: Helpers for hash generation
578 # -------------------------------------------------------------------------
579
580 def _l10n_sa_get_namespaces(self):
581 """
582 Namespaces used in the final UBL declaration, required to canonalize the finalized XML document of the Invoice
583 """
584 return {
585 'cac': 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',
586 'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',
587 'ext': 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2',
588 'sig': 'urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2',
589 'sac': 'urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2',
590 'sbc': 'urn:oasis:names:specification:ubl:schema:xsd:SignatureBasicComponents-2',
591 'ds': 'http://www.w3.org/2000/09/xmldsig#',
592 'xades': 'http://uri.etsi.org/01903/v1.3.2#'
593 }
594
595 def _l10n_sa_generate_invoice_xml_sha(self, xml_content):
596 """
597 Transform, canonicalize then hash the invoice xml content using the SHA256 algorithm,
598 then return the hashed content
599 """
600
601 def _canonicalize_xml(content):
602 """
603 Canonicalize XML content using the c14n method. The specs mention using the c14n11 canonicalization,
604 which is simply calling etree.tostring and setting the method argument to 'c14n'. There are minor
605 differences between c14n11 and c14n canonicalization algorithms, but for the purpose of ZATCA signing,
606 c14n is enough
607 """
608 return etree.tostring(content, method="c14n", exclusive=False, with_comments=False,
609 inclusive_ns_prefixes=self._l10n_sa_get_namespaces())
610
611 def _transform_and_canonicalize_xml(content):
612 """ Transform XML content to remove certain elements and signatures using an XSL template """
613 invoice_xsl = etree.parse(file_path('l10n_sa_edi/data/pre-hash_invoice.xsl'))
614 transform = etree.XSLT(invoice_xsl)
615 return _canonicalize_xml(transform(content))
616
617 root = etree.fromstring(xml_content)
618 # Transform & canonicalize the XML content
619 transformed_xml = _transform_and_canonicalize_xml(root)
620 # Get the SHA256 hashed value of the XML content
621 return sha256(transformed_xml)
622
623 def _l10n_sa_generate_invoice_xml_hash(self, xml_content, mode='hexdigest'):
624 """
625 Generate the b64 encoded sha256 hash of a given xml string:
626 - First: Transform the xml content using a pre-hash_invoice.xsl file
627 - Second: Canonicalize the transformed xml content using the c14n method
628 - Third: hash the canonicalized content using the sha256 algorithm then encode it into b64 format
629 """
630 xml_sha = self._l10n_sa_generate_invoice_xml_sha(xml_content)
631 if mode == 'hexdigest':
632 xml_hash = xml_sha.hexdigest().encode()
633 elif mode == 'digest':
634 xml_hash = xml_sha.digest()
635 return b64encode(xml_hash)