Debian Codegraph @

addons/l10n_sa_edi/models/account_move.py

raw
1 import base64
2 import uuid
3 from markupsafe import Markup
4 from odoo import _, fields, models, api
5 from odoo.exceptions import UserError
6 from odoo.tools import float_repr
7 from datetime import datetime
8 from base64 import b64decode, b64encode
9 from lxml import etree
10
11
12 class AccountMove(models.Model):
13 _inherit = 'account.move'
14
15 l10n_sa_uuid = fields.Char(string='Document UUID (SA)', copy=False, help="Universally unique identifier of the Invoice")
16
17 l10n_sa_invoice_signature = fields.Char("Unsigned XML Signature", copy=False)
18
19 l10n_sa_chain_index = fields.Integer(
20 string="ZATCA chain index", copy=False, readonly=True,
21 help="Invoice index in chain, set if and only if an in-chain XML was submitted and did not error",
22 )
23 l10n_sa_edi_chain_head_id = fields.Many2one(
24 'account.move',
25 string="ZATCA chain stopping move",
26 copy=False,
27 readonly=True,
28 help="Technical field to know if the chain has been stopped by a previous invoice",
29 )
30
31 def _l10n_gcc_get_invoice_title(self):
32 # DEPRECATED - to be removed in master
33 # EXTENDS l10n_gcc_invoice
34 self.ensure_one()
35 if self.company_id.country_code == 'SA' and self._l10n_sa_is_simplified():
36 return self.env._('Simplified Tax Invoice')
37
38 return super()._l10n_gcc_get_invoice_title()
39
40 def _l10n_sa_is_simplified(self):
41 # DEPRECATED - to be removed in master
42 """
43 Returns True if the customer is an individual, i.e: The invoice is B2C
44 :return:
45 """
46 self.ensure_one()
47
48 return (
49 self.partner_id.commercial_partner_id.company_type == "person"
50 if self.partner_id.commercial_partner_id
51 else self.partner_id.company_type == "person"
52 )
53
54 @api.ondelete(at_uninstall=False)
55 def _prevent_zatca_rejected_invoice_deletion(self):
56 # Prevent deletion of ZATCA-rejected invoices in production mode
57 descr = 'Rejected ZATCA Document not to be deleted - ثيقة ZATCA المرفوضة لا يجوز حذفها'
58 for move in self:
59 if move.country_code == "SA" and \
60 move.company_id.l10n_sa_edi_is_production and \
61 move.attachment_ids.filtered(lambda a: a.description == descr and a.res_model == 'account.move'):
62 raise UserError(_("The Invoice(s) are linked to a validated EDI document and cannot be modified according to ZATCA rules"))
63
64 @api.depends('amount_total_signed', 'amount_tax_signed', 'l10n_sa_confirmation_datetime', 'company_id',
65 'company_id.vat', 'journal_id', 'journal_id.l10n_sa_production_csid_json', 'edi_document_ids',
66 'l10n_sa_invoice_signature', 'l10n_sa_chain_index', 'state')
67 def _compute_qr_code_str(self):
68 """ Override to update QR code generation in accordance with ZATCA Phase 2"""
69 phase_one_moves = self.env['account.move']
70 for move in self:
71 zatca_document = move.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'sa_zatca')
72 if move.country_code == 'SA' and move.move_type in ('out_invoice', 'out_refund') and zatca_document and move.state != 'draft':
73 qr_code_str = ''
74 if move._l10n_sa_is_simplified():
75 x509_cert = move.journal_id.l10n_sa_production_csid_certificate_id
76 xml_content = self.env.ref('l10n_sa_edi.edi_sa_zatca')._l10n_sa_generate_zatca_template(move)
77 qr_code_str = move._l10n_sa_get_qr_code(move.company_id, xml_content, x509_cert,
78 move.l10n_sa_invoice_signature, True)
79 qr_code_str = b64encode(qr_code_str).decode()
80 elif zatca_document.state == 'sent' and zatca_document.attachment_id.datas:
81 document_xml = zatca_document.attachment_id.with_context(bin_size=False).datas.decode()
82 root = etree.fromstring(b64decode(document_xml))
83 qr_node = root.xpath('//*[local-name()="ID"][text()="QR"]/following-sibling::*/*')[0]
84 qr_code_str = qr_node.text
85 move.l10n_sa_qr_code_str = qr_code_str
86 else:
87 # In the case where the Invoice is not a ZATCA invoice, or is Phase 1, or is not confirmed,
88 # we call super to trigger the initial QR code generation for Phase 1
89 phase_one_moves |= move
90 super(AccountMove, phase_one_moves)._compute_qr_code_str()
91
92
93 def _l10n_sa_get_qr_code_encoding(self, tag, field, int_length=1):
94 """
95 Helper function to encode strings for the QR code generation according to ZATCA specs
96 """
97 company_name_tag_encoding = tag.to_bytes(length=1, byteorder='big')
98 company_name_length_encoding = len(field).to_bytes(length=int_length, byteorder='big')
99 return company_name_tag_encoding + company_name_length_encoding + field
100
101 def _l10n_sa_check_billing_reference(self):
102 """
103 Make sure credit/debit notes have a either a reveresed move or debited move or a customer reference
104 """
105 self.ensure_one()
106 return self.debit_origin_id or self.reversed_entry_id or self.ref
107
108 @api.model
109 def _l10n_sa_get_qr_code(self, company_id, unsigned_xml, certificate, signature, is_b2c=False):
110 """
111 Generate QR code string based on XML content of the Invoice UBL file, X509 Production Certificate
112 and company info.
113
114 :return b64 encoded QR code string
115 """
116
117 def xpath_ns(expr):
118 return root.xpath(expr, namespaces=edi_format._l10n_sa_get_namespaces())[0].text.strip()
119
120 qr_code_str = b''
121 root = etree.fromstring(unsigned_xml)
122 edi_format = self.env['account.edi.xml.ubl_21.zatca']
123
124 # Indent XML content to avoid indentation mismatches
125 etree.indent(root, space=' ')
126
127 invoice_date = xpath_ns('//cbc:IssueDate')
128 invoice_time = xpath_ns('//cbc:IssueTime')
129 invoice_datetime = datetime.strptime(invoice_date + ' ' + invoice_time, '%Y-%m-%d %H:%M:%S')
130
131 if invoice_datetime and company_id.vat and certificate and signature:
132 prehash_content = etree.tostring(root)
133 invoice_hash = edi_format._l10n_sa_generate_invoice_xml_hash(prehash_content, 'digest')
134
135 amount_total = float(xpath_ns('//cbc:PayableAmount'))
136 amount_tax = float(xpath_ns('//cac:TaxTotal/cbc:TaxAmount'))
137 seller_name_enc = self._l10n_sa_get_qr_code_encoding(1, company_id.display_name.encode())
138 seller_vat_enc = self._l10n_sa_get_qr_code_encoding(2, company_id.vat.encode())
139 timestamp_enc = self._l10n_sa_get_qr_code_encoding(3,
140 invoice_datetime.strftime("%Y-%m-%dT%H:%M:%S").encode())
141 amount_total_enc = self._l10n_sa_get_qr_code_encoding(4, float_repr(abs(amount_total), 2).encode())
142 amount_tax_enc = self._l10n_sa_get_qr_code_encoding(5, float_repr(abs(amount_tax), 2).encode())
143 invoice_hash_enc = self._l10n_sa_get_qr_code_encoding(6, invoice_hash)
144 signature_enc = self._l10n_sa_get_qr_code_encoding(7, signature.encode())
145 public_key_enc = self._l10n_sa_get_qr_code_encoding(8, base64.b64decode(certificate._get_public_key_bytes(formatting='base64')))
146
147 qr_code_str = (seller_name_enc + seller_vat_enc + timestamp_enc + amount_total_enc +
148 amount_tax_enc + invoice_hash_enc + signature_enc + public_key_enc)
149
150 if is_b2c:
151 qr_code_str += self._l10n_sa_get_qr_code_encoding(9, base64.b64decode(certificate._get_signature_bytes(formatting='base64')))
152
153 return qr_code_str
154
155 @api.depends('state', 'edi_document_ids.state')
156 def _compute_edi_show_cancel_button(self):
157 """
158 Override to hide the EDI Cancellation button at all times for ZATCA Invoices
159 """
160 super()._compute_edi_show_cancel_button()
161 for move in self.filtered(lambda m: m.is_invoice() and m.country_code == 'SA'):
162 move.edi_show_cancel_button = False
163
164 @api.depends('state', 'edi_document_ids.state')
165 def _compute_show_reset_to_draft_button(self):
166 """
167 Override to hide the Reset to Draft button for ZATCA Invoices that have been successfully submitted
168 in Production mode.
169 """
170 super()._compute_show_reset_to_draft_button()
171 for move in self:
172 # The "Reset to Draft" button should be hidden in the following cases:
173 # - Invoice has been successfully submitted in Production mode.
174 # - The invoice submission encountered a timed out, regardless of the API mode.
175 if move.l10n_sa_chain_index and (move.company_id.l10n_sa_edi_is_production or not move._l10n_sa_is_in_chain()):
176 move.show_reset_to_draft_button = False
177
178 def button_draft(self):
179 # OVERRIDE
180 for move in self:
181 if move.country_code == "SA" and move.l10n_sa_chain_index and move.company_id.l10n_sa_edi_is_production:
182 raise UserError(_("The Invoice(s) are linked to a validated EDI document and cannot be modified according to ZATCA rules"))
183 return super().button_draft()
184
185 def _l10n_sa_reset_confirmation_datetime(self):
186 """ OVERRIDE: we want rejected phase 2 invoices to keep the original confirmation datetime"""
187 for move in self.filtered(lambda m: m.country_code == 'SA'):
188 zatca_doc = move.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'sa_zatca')
189 if not zatca_doc or zatca_doc[0].blocking_level != 'error': # Error is the rejection case
190 move.l10n_sa_confirmation_datetime = False
191
192 def _l10n_sa_generate_unsigned_data(self):
193 """
194 Generate UUID and digital signature to be used during both Signing and QR code generation.
195 It is necessary to save the signature as it changes everytime it is generated and both the signing and the
196 QR code expect to have the same, identical signature.
197 """
198 self.ensure_one()
199 edi_format = self.env.ref('l10n_sa_edi.edi_sa_zatca')
200 # Build the dict of values to be used for generating the Invoice XML content
201 # Set Invoice field values required for generating the XML content, hash and signature
202 self.l10n_sa_uuid = uuid.uuid4()
203 # We generate the XML content
204 xml_content = edi_format._l10n_sa_generate_zatca_template(self)
205 # Once the required values are generated, we hash the invoice, then use it to generate a Signature
206 invoice_hash_hex = self.env['account.edi.xml.ubl_21.zatca']._l10n_sa_generate_invoice_xml_hash(xml_content).decode()
207 self.l10n_sa_invoice_signature = edi_format._l10n_sa_get_digital_signature(self.journal_id.company_id,
208 invoice_hash_hex).decode()
209 return xml_content
210
211 def _l10n_sa_log_results(self, xml_content, response_data=None, error=False):
212 """
213 Save submitted invoice XML hash in case of either Rejection or Acceptance.
214 """
215 self.ensure_one()
216 bootstrap_cls, title, subtitle, content = ("success", _("Success: Invoice accepted by ZATCA"), "", "" if (not error or not response_data) else response_data)
217 status_code = response_data.get('status_code')
218 attachment = False
219 if error:
220 xml_filename = self.env['account.edi.xml.ubl_21.zatca']._export_invoice_filename(self)
221 xml_filename = xml_filename[:-4] + '-rejected.xml'
222 attachment = self.env['ir.attachment'].create({
223 'raw': xml_content,
224 'name': xml_filename,
225 'description': 'Rejected ZATCA Document not to be deleted - ثيقة ZATCA المرفوضة لا يجوز حذفها',
226 'res_id': self.id,
227 'res_model': self._name,
228 'type': 'binary',
229 'mimetype': 'application/xml',
230 })
231 bootstrap_cls, title = ("danger", _("Error: Invoice rejected by ZATCA"))
232 subtitle = _('Please check the details below and retry after addressing them:')
233 content = response_data['error']
234 if response_data and response_data.get('validationResults', {}).get('warningMessages'):
235 bootstrap_cls, title = ("warning", _("Warning: Invoice accepted by ZATCA with warnings"))
236 subtitle = _('Please check the details below:')
237 content = Markup("""<b>%(status_code)s</b>%(errors)s""") % {
238 "status_code": f"[{status_code}] " if status_code else "",
239 "errors": Markup("<br/>").join([
240 Markup("<b>%(code)s</b> : %(message)s") % {
241 "code": m['code'],
242 "message": m['message'],
243 } for m in response_data['validationResults']['warningMessages']
244 ]),
245 }
246 if response_data.get("error") and response_data.get("excepted"):
247 bootstrap_cls, title = ("warning", _("Warning: Unable to Retrieve a Response from ZATCA"))
248 subtitle = _('Please check the details below:')
249 content = response_data['error']
250 if status_code == 409:
251 bootstrap_cls, title = ("warning", _("Warning: Invoice was already successfully reported to ZATCA"))
252 subtitle = _("Please check the details below:")
253 content = Markup("""<b>%(status_code)s</b>%(errors)s""") % {
254 "status_code": f"[{status_code}] " if status_code else "",
255 "errors": Markup("<br/>").join([
256 Markup("<b>%(code)s</b> : %(message)s") % {
257 "code": m['code'],
258 "message": m['message'],
259 } for m in response_data['validationResults']['errorMessages']
260 ])
261 }
262 if response_data.get("error") and not content:
263 # if there is an error, but no exception or rejection in the response
264 # then it is due to an internal error raised. No need to log a note
265 return
266
267 if not response_data.get("excepted"):
268 self.journal_id.l10n_sa_latest_submission_hash = self.env['account.edi.xml.ubl_21.zatca']._l10n_sa_generate_invoice_xml_hash(xml_content)
269
270 self.message_post(body=Markup("""
271 <div role='alert' class='alert alert-%s'>
272 <h4 class='alert-heading my-0'>%s</h4>
273 <p class='mb-0 mt-1'>
274 %s
275 </p>
276 %s
277 <p class='mb-0'>
278 %s
279 </p>
280 </div>
281 """) % (bootstrap_cls, title, subtitle, Markup("<hr>") if content else "", content),
282 attachment_ids=(attachment and [attachment.id]) or [],
283 )
284
285 def _is_l10n_sa_eligibile_invoice(self):
286 self.ensure_one()
287 return self.is_invoice() and self.l10n_sa_confirmation_datetime and self.country_code == 'SA'
288
289 def _l10n_sa_is_legal(self):
290 # Extends l10n_sa
291 # Accounts for both ZATCA phases
292 # Phase 1: no documents
293 # Phase 2: checks the state of documents
294 self.ensure_one()
295 result = super()._l10n_sa_is_legal()
296 zatca_document = self.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'sa_zatca')
297 return result or (self.company_id.country_id.code == 'SA' and zatca_document and self.edi_state == "sent")
298
299 def _get_report_base_filename(self):
300 """
301 Generate the name of the invoice PDF file according to ZATCA business rules:
302 Seller Vat Number (BT-31), Date (BT-2), Time (KSA-25), Invoice Number (BT-1)
303 """
304 if self._is_l10n_sa_eligibile_invoice():
305 return self.with_context(l10n_sa_file_format=False).env['account.edi.xml.ubl_21.zatca']._export_invoice_filename(self)
306 return super()._get_report_base_filename()
307
308 def _get_invoice_report_filename(self, extension='pdf', report=None):
309 if self._is_l10n_sa_eligibile_invoice():
310 return self.with_context(l10n_sa_file_format=extension).env['account.edi.xml.ubl_21.zatca']._export_invoice_filename(self)
311 return super()._get_invoice_report_filename(extension, report)
312
313 def _l10n_sa_is_in_chain(self):
314 """
315 If the invoice was successfully posted and confirmed by the government, then this would return True.
316 If the invoice timed out, then its edi_document should still be in the 'to_send' state.
317 """
318 zatca_doc_ids = self.edi_document_ids.filtered(lambda d: d.edi_format_id.code == 'sa_zatca')
319 return len(zatca_doc_ids) > 0 and not any(zatca_doc_ids.filtered(lambda d: d.state == 'to_send'))
320
321 def _prepare_tax_lines_for_taxes_computation(self, tax_amls, round_from_tax_lines):
322 """
323 If the final invoice has downpayment lines, we skip the tax correction, as we need to recalculate tax amounts
324 without taking into account those lines
325 """
326 if self.country_code == 'SA' and not self._is_downpayment() and self.line_ids._get_downpayment_lines():
327 return []
328 return super()._prepare_tax_lines_for_taxes_computation(tax_amls, round_from_tax_lines)
329
330 def _get_l10n_sa_totals(self):
331 self.ensure_one()
332 invoice_node = self.env['account.edi.xml.ubl_21.zatca']._get_invoice_node({'invoice': self})
333 return {
334 'total_amount': invoice_node['cac:LegalMonetaryTotal']['cbc:TaxInclusiveAmount']['_text'],
335 'total_tax': invoice_node['cac:TaxTotal'][-1]['cbc:TaxAmount']['_text'],
336 }
337
338 def _retry_edi_documents_error(self):
339 """
340 Hook to reset the chain head error prior to retrying the submission
341 """
342 self.filtered(lambda m: m.country_code == 'SA').write({'l10n_sa_edi_chain_head_id': False})
343 zatca = self.env.ref('l10n_sa_edi.edi_sa_zatca')
344 self.filtered(lambda m: m._get_edi_document(zatca))._detach_attachments()
345 return super()._retry_edi_documents_error()
346
347 def action_show_chain_head(self):
348 """
349 Action to show the chain head of the invoice
350 """
351 self.ensure_one()
352 return self.l10n_sa_edi_chain_head_id._get_records_action(name=_("Chain Head"))
353
354
355 class AccountMoveLine(models.Model):
356 _inherit = 'account.move.line'
357
358 def _apply_retention_tax_filter(self, tax_values):
359 return not tax_values['tax_id'].l10n_sa_is_retention
360
361 def _is_global_discount_line(self):
362 """
363 Any line that has a negative amount and is not linked to a down-payment is considered as a
364 global discount line. These can be created either manually, or through a promotions program.
365 """
366 self.ensure_one()
367 return not self._get_downpayment_lines() and self.price_subtotal < 0
368
369 @api.depends('price_subtotal', 'price_total')
370 def _compute_tax_amount(self):
371 super()._compute_tax_amount()
372 AccountTax = self.env['account.tax']
373 for line in self:
374 if (
375 line.move_id.country_code == 'SA'
376 and line.move_id.is_invoice(include_receipts=True)
377 and line.display_type == 'product'
378 ):
379 base_line = line.move_id._prepare_product_base_line_for_taxes_computation(line)
380 AccountTax._add_tax_details_in_base_line(base_line, line.company_id)
381 AccountTax._round_base_lines_tax_details([base_line], line.company_id)
382 line.l10n_gcc_invoice_tax_amount = sum(
383 tax_data['tax_amount_currency']
384 for tax_data in base_line['tax_details']['taxes_data']
385 if not tax_data['tax'].l10n_sa_is_retention
386 )