Debian Codegraph @

addons/l10n_pl_edi/models/account_move_send.py

raw symbols SCIP
1 import logging
2
3 from odoo import fields, models
4
5 from odoo.addons.l10n_pl_edi.tools.ksef_api_service import KsefApiService
6
7 _logger = logging.getLogger(__name__)
8
9
10 class AccountMoveSend(models.AbstractModel):
11 _inherit = 'account.move.send'
12
13 def _get_all_extra_edis(self):
14 res = super()._get_all_extra_edis()
15 res.update({
16 'pl_ksef': {
17 'label': self.env._("by KSeF (e-Faktura)"),
18 'is_applicable': lambda move: (
19 move.company_id.country_code == 'PL'
20 and move.company_id.l10n_pl_edi_register
21 ),
22 'help': self.env._('Send the electronic invoice to the Polish National e-Invoicing System (KSeF).'),
23 }
24 })
25 return res
26
27 def _get_alerts(self, moves, moves_data):
28 # EXTENDS 'account'
29 alerts = super()._get_alerts(moves, moves_data)
30
31 if it_alerts := moves.filtered(lambda move:
32 'pl_ksef' in moves_data[move]['extra_edis']
33 or moves_data[move]['invoice_edi_format'] == 'fa3_pl'
34 )._l10n_pl_edi_check_mandatory_fields():
35 alerts.update(**it_alerts)
36
37 return alerts
38
39 def _call_web_service_before_invoice_pdf_render(self, invoices_data):
40 super()._call_web_service_before_invoice_pdf_render(invoices_data)
41
42 def set_error(moves, error_message):
43 for move in moves:
44 invoices_data[move]['error'] = {
45 'error_title': self.env._("Error when sending invoices to the KSeF"),
46 'errors': [error_message],
47 }
48
49 def is_ksef(move):
50 return 'pl_ksef' in invoices_data[move].get('extra_edis', []) and not move.l10n_pl_edi_status
51
52 moves_by_company = self.env['account.move'].union(*invoices_data).filtered(is_ksef).grouped('company_id')
53 for company, moves in moves_by_company.items():
54
55 service = KsefApiService(company)
56 try:
57 service.open_ksef_session()
58 except Exception as errors: # noqa: BLE001
59 set_error(moves, str(errors))
60 continue
61
62 for move in moves:
63
64 if move.invoice_date > fields.Date.context_today(self):
65 set_error(move, self.env._("The move was skipped because it is future-dated"))
66 continue
67
68 try:
69 self.env['res.company']._with_locked_records(move)
70 xml_content = move._l10n_pl_edi_render_xml()
71 xml_content = xml_content.encode('utf-8')
72 response_data = service.send_invoice(xml_content)
73 l10n_pl_edi_ref = response_data.get('referenceNumber')
74
75 move.write({
76 'l10n_pl_edi_status': 'sent',
77 'l10n_pl_edi_ref': l10n_pl_edi_ref,
78 'l10n_pl_edi_session_id': move.company_id.l10n_pl_edi_session_id,
79 'l10n_pl_edi_header': False,
80 })
81 # Will be linked in _link_invoice_documents
82 invoices_data[move]['l10n_pl_edi_attachment_file'] = xml_content
83
84 except Exception as errors: # noqa: BLE001
85 set_error(move, str(errors))
86
87 if self._can_commit():
88 self.env.cr.commit()
89
90 # Check the status already
91 if moves_by_company:
92 self.env.ref('l10n_pl_edi.cron_auto_checks_the_polish_invoice_status')._trigger()
93
94 def _link_invoice_documents(self, invoices_data):
95 # EXTENDS 'account'
96 super()._link_invoice_documents(invoices_data)
97
98 for move, invoice_data in invoices_data.items():
99 if 'l10n_pl_edi_attachment_file' in invoice_data:
100 move.l10n_pl_edi_attachment_id = self.env['ir.attachment'].sudo().create({
101 'description': self.env._('KSeF Sent Invoice XML'),
102 'name': f"FA3-{move.name.replace('/', '_')}.xml",
103 'type': 'binary',
104 'mimetype': 'application/xml',
105 'raw': invoice_data['l10n_pl_edi_attachment_file'],
106 'res_id': move.id,
107 'res_model': move._name,
108 'res_field': 'l10n_pl_edi_attachment_file',
109 })
110 move.sudo().with_context(no_new_invoice=True).message_post(
111 body=self.env._("The KSeF XML has been attached."),
112 attachment_ids=move.l10n_pl_edi_attachment_id.ids,
113 )
114
115 self.env['account.move'].union(*invoices_data).invalidate_recordset(fnames=[
116 'l10n_pl_edi_attachment_id',
117 'l10n_pl_edi_attachment_file',
118 ])