| 1 |
from odoo import _, api, models |
| 2 |
from odoo.exceptions import UserError |
| 3 |
|
| 4 |
|
| 5 |
class IrAttachment(models.Model): |
| 6 |
_inherit = 'ir.attachment' |
| 7 |
|
| 8 |
@api.ondelete(at_uninstall=False) |
| 9 |
def _unlink_except_rejected_zatca_document(self): |
| 10 |
''' |
| 11 |
Prevents unlinking of rejected XML documents |
| 12 |
''' |
| 13 |
descr = 'Rejected ZATCA Document not to be deleted - ثيقة ZATCA المرفوضة لا يجوز حذفها' |
| 14 |
for attach in self.filtered(lambda a: a.description == descr and a.res_model == 'account.move'): |
| 15 |
move = self.env['account.move'].browse(attach.res_id).exists() |
| 16 |
if move and move.country_code == "SA": |
| 17 |
raise UserError(_("You can't unlink an attachment being an EDI document refused by the government.")) |
| 18 |
|
| 19 |
@api.ondelete(at_uninstall=False) |
| 20 |
def _unlink_except_validated_pdf_invoices(self): |
| 21 |
''' |
| 22 |
Prevents unlinking of invoice pdfs linked to an invoice |
| 23 |
where the pdf attachment was created after or at the same time as the edi_documents last write date. |
| 24 |
''' |
| 25 |
attachments_to_check = self.filtered( |
| 26 |
lambda attachment: attachment.res_model == "account.move" |
| 27 |
and attachment.res_field == "invoice_pdf_report_file" |
| 28 |
) |
| 29 |
res = self.env["account.edi.document"]._read_group( |
| 30 |
domain=[("move_id", "in", attachments_to_check.mapped("res_id")), ("state", "=", "sent"), ("edi_format_id.code", "=", "sa_zatca")], |
| 31 |
aggregates=["write_date:min"], |
| 32 |
groupby=["move_id"], |
| 33 |
) |
| 34 |
edi_documents = {doc[0].id: doc[1] for doc in res} |
| 35 |
restricted_attachments = self.env["ir.attachment"] |
| 36 |
for attachment in attachments_to_check: |
| 37 |
if (document_date := edi_documents.get(attachment.res_id)) and attachment.create_date >= document_date: |
| 38 |
restricted_attachments += attachment |
| 39 |
if restricted_attachments: |
| 40 |
raise UserError(_( |
| 41 |
"Oops! The invoice PDF(s) are linked to a validated EDI document and cannot be deleted according to ZATCA rules: %s", |
| 42 |
", ".join(restricted_attachments.mapped("name")))) |
| 43 |
|
| 44 |
def _get_posted_pdf_moves_to_check(self): |
| 45 |
# Extends l10n_sa: to bypass the unlink check in l10n_sa for posted moves |
| 46 |
return super()._get_posted_pdf_moves_to_check().filtered(lambda rec: not rec.edi_state) |