Debian Codegraph @

addons/l10n_pl_edi/models/account_move.py

raw symbols SCIP
1 import logging
2 import re
3 from xml.dom.minidom import parseString
4
5 from stdnum.pl.nip import compact
6
7 from odoo import api, fields, models
8 from odoo.exceptions import UserError
9 from odoo.tools import float_compare, float_is_zero, float_repr, OrderedSet
10
11 from odoo.addons.l10n_pl_edi.tools.ksef_api_service import KsefApiService
12
13 _logger = logging.getLogger(__name__)
14
15
16 class AccountMove(models.Model):
17 _inherit = 'account.move'
18
19 l10n_pl_edi_status = fields.Selection([
20 ('sent', 'Sent (In Progress)'),
21 ('accepted', 'Accepted'),
22 ('rejected', 'Rejected'),
23 ], string='KSeF Status', readonly=True, copy=False)
24 l10n_pl_edi_ref = fields.Char(string='KSeF Reference Number', readonly=True, copy=False)
25 l10n_pl_edi_register = fields.Boolean(related='company_id.l10n_pl_edi_register')
26 l10n_pl_edi_header = fields.Html(
27 help='User description of the current state, with hints to make the flow progress',
28 readonly=True,
29 copy=False,
30 )
31 l10n_pl_edi_number = fields.Char(string='KSeF Number', readonly=True, index=True, copy=False)
32 l10n_pl_edi_session_id = fields.Char(string='KSeF Session Number used for sending', copy=False, readonly=True)
33 l10n_pl_edi_attachment_file = fields.Binary(copy=False, attachment=True)
34 l10n_pl_edi_attachment_id = fields.Many2one(
35 comodel_name='ir.attachment',
36 string="KSeF Attachment",
37 compute=lambda self: self._compute_linked_attachment_id('l10n_pl_edi_attachment_id', 'l10n_pl_edi_attachment_file'),
38 depends=['l10n_pl_edi_attachment_file'],
39 )
40 l10n_pl_edi_upo_file = fields.Binary(copy=False, attachment=True)
41 l10n_pl_edi_upo_id = fields.Many2one(
42 comodel_name='ir.attachment',
43 string="UPO Attachment",
44 compute=lambda self: self._compute_linked_attachment_id('l10n_pl_edi_upo_id', 'l10n_pl_edi_upo_file'),
45 depends=['l10n_pl_edi_upo_file'],
46 )
47
48 def _l10n_pl_edi_check_mandatory_fields(self):
49 errors = {}
50 if not self:
51 return errors
52 company = self.company_id
53 if not company.vat:
54 errors['vat_missing'] = {'message': self.env._("You must have a VAT number to be able to issue e-invoices\n")}
55 if not company.country_id or not company.street or not company.city:
56 errors['address_problem'] = {'message': self.env._("Please complete the address of your company\n")}
57 return errors
58
59 def _l10n_pl_edi_get_ksef_invoice_type(self):
60 """
61 Determines the specific TRodzajFaktury for KSeF.
62 """
63 self.ensure_one()
64
65 # 1. Handle Corrections (Credit Notes)
66 if self.move_type == 'out_refund':
67 origin_inv = self.reversed_entry_id
68 if not origin_inv:
69 return 'KOR'
70
71 origin_type = origin_inv._l10n_pl_edi_get_ksef_invoice_type()
72 if origin_type == 'ZAL':
73 return 'KOR_ZAL'
74 elif origin_type == 'ROZ':
75 return 'KOR_ROZ'
76 else:
77 return 'KOR'
78
79 # 2. Handle Sales Invoices
80 elif self.move_type == 'out_invoice':
81 has_dp_lines = any(line._get_downpayment_lines() for line in self.invoice_line_ids)
82
83 if has_dp_lines:
84 # Check for Settlement (ROZ): Contains Regular lines AND Negative Downpayment lines
85 has_regular_lines = any(not line._get_downpayment_lines() for line in self.invoice_line_ids)
86 has_deducted_dp = any(line._get_downpayment_lines() and float_compare(line.price_subtotal, 0.0, precision_rounding=line.currency_id.rounding) == -1 for line in self.invoice_line_ids)
87
88 if has_regular_lines and has_deducted_dp:
89 return 'ROZ'
90
91 # If it's not ROZ but has downpayment lines (and they are positive), it is ZAL
92 return 'ZAL'
93
94 # Default to Standard VAT invoice
95 return 'VAT'
96
97 def _l10n_pl_edi_get_related_invoices(self):
98 """
99 Returns a list of related invoice numbers for ZAL and ROZ types.
100 Safely checks for Sale Order links.
101 """
102 self.ensure_one()
103 ksef_type = self._l10n_pl_edi_get_ksef_invoice_type()
104 related_numbers = OrderedSet()
105
106 if ksef_type in ['ROZ', 'ZAL'] and hasattr(self.line_ids, 'sale_line_ids'):
107 sale_orders = self.line_ids.sale_line_ids.order_id
108
109 for so in sale_orders:
110 previous_invoices = so.invoice_ids.filtered(
111 lambda x: x.id != self.id and x.state == 'posted'
112 )
113
114 for prev in previous_invoices:
115 # Recursively check the type of the previous invoice
116 if prev._l10n_pl_edi_get_ksef_invoice_type() == 'ZAL':
117 related_numbers.add(prev.name)
118
119 return list(related_numbers)
120
121 def _l10n_pl_edi_get_xml_values(self):
122 """
123 Prepares a dictionary of values to be passed to the QWeb template.
124 """
125 self.ensure_one()
126
127 def get_vat_country(vat):
128 if not vat or vat[:2].isdecimal():
129 return False
130 return vat[:2].upper()
131
132 def get_address(partner):
133 return re.sub(r'\n+', r' ', partner._display_address(True))
134
135 def get_tags(code):
136 return self.env['account.account.tag']._get_tax_tags(code, self.env.ref('base.pl').id)
137
138 def get_tag_names(line):
139 return line.tax_tag_ids.with_context(lang='en_US').mapped(lambda x: re.sub(r'^[+-]', r'', x.name or ''))
140
141 def get_amounts_from_tag(tax_tag_string):
142 lines = self.line_ids.filtered(lambda line: line.tax_tag_ids & get_tags(tax_tag_string))
143 if 'OSS' in tax_tag_string:
144 lines = lines.filtered(lambda line: line.tax_ids if 'Base' in tax_tag_string else not line.tax_ids)
145 return -sum(lines.mapped('amount_currency'))
146
147 def get_amounts_from_tag_in_PLN_currency(tax_group_id):
148 conversion_line = self.invoice_line_ids.sorted(lambda line: abs(line.balance), reverse=True)[0] if self.invoice_line_ids else None
149 conversion_rate = abs(conversion_line.balance / conversion_line.amount_currency) if self.currency_id != self.env.ref('base.PLN') and conversion_line else 1
150 return get_amounts_from_tag(tax_group_id) * conversion_rate
151
152 def compute_p_12(tag_names):
153 """
154 Determines the KSeF tax rate code (P_12) based on the line's tax.
155 Prioritizes tax amount for standard rates, and Tags/Names for special 0% cases.
156 Mapping was determined by looking at the Tax Report lines.
157 """
158 # "0 WDT": Intra-Community supply of goods (K_21)
159 if 'K_21' in tag_names:
160 return "0 WDT"
161 # "0 EX": Export of goods in case of 0% rate for export of goods (K_22)
162 if 'K_22' in tag_names:
163 return "0 EX"
164 # "oo": Supply of goods, taxable person acquiring (K_31)
165 if 'K_31' in tag_names:
166 return "oo"
167 # Services included in art. 100.1.4 (K_12)
168 if 'K_12' in tag_names:
169 return "np II"
170 # Supply of goods/services, out of the country (K_11, OSS)
171 if 'K_11' in tag_names or any('OSS' in tag for tag in tag_names):
172 return "np I"
173 # "zw": Supply of goods/services, domestic, exempt (K_10) - must fill P_19
174 if 'K_10' in tag_names:
175 return "zw"
176 # "0 KR": Supply of goods/services, domestic, 0% (K_13)
177 if 'K_13' in tag_names:
178 return "0 KR"
179 # "23": Supply of goods/services, domestic, 23% (K_19)
180 if 'K_19' in tag_names:
181 return "23"
182 # "8": Supply of goods/services, domestic, 8% (K_17)
183 if 'K_17' in tag_names:
184 return "8"
185 # "5": Supply of goods/services, domestic, 5% (K_15)
186 if 'K_17' in tag_names:
187 return "8"
188 # No tax? It's exempt
189 return "zw"
190
191 ksef_type = self._l10n_pl_edi_get_ksef_invoice_type()
192 invoice_lines_vals = []
193 sign = -1 if 'KOR' in ksef_type else 1
194
195 invoice_lines_tag_names = [
196 {tag_name for tag_name in get_tag_names(line) if tag_name}
197 for line in self.invoice_line_ids
198 ]
199 invoice_tag_names = set().union(*invoice_lines_tag_names)
200
201 invoice_lines_vals = [
202 {
203 'NrWierszaFa': index + 1,
204 'UU_ID': f"odoo-line-{line.id}",
205 'P_7': line.name,
206 'P_8A': line.product_uom_id.name or 'szt.',
207 'P_8B': line.quantity * sign,
208 'P_9A': float_repr(line.price_unit, 2),
209 'P_11': float_repr(line.price_subtotal * sign, 2),
210 'P_12': compute_p_12(tag_names),
211 }
212 for index, line in enumerate(self.invoice_line_ids)
213 if (tag_names := invoice_lines_tag_names[index])
214 ]
215
216 tax_summary_vals = {}
217
218 for group in self.tax_totals.get('groups_by_subtotal', {}).values():
219 tax_rate_str = str(int((group['tax_group_amount_type'] == 'percent' and group['tax_group_amount']) or 0))
220 tax_summary_vals[tax_rate_str] = {
221 'net': float_repr(group['tax_group_base_amount'], 2),
222 'tax': float_repr(group['tax_group_amount'], 2),
223 }
224
225 correction_info = {}
226 if 'KOR' in ksef_type:
227 origin = self.reversed_entry_id
228 origin_ksef_id = origin.l10n_pl_edi_ref if origin else False
229
230 correction_info = {
231 'PrzyczynaKorekty': self.ref or 'Korekta',
232 'TypKorekty': '1',
233 'NrFaKorygowanej': origin.name if origin else 'BRAK',
234 'DataWystFaKorygowanej': origin.invoice_date if origin else self.invoice_date,
235 'NrKSeF': origin_ksef_id,
236 'NrKSeFN': '1' if not origin_ksef_id else False,
237 }
238
239 return {
240 'invoice': self,
241 'DataWytworzeniaFa': fields.Datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'),
242 'seller': self.company_id,
243 'seller_address': get_address(self.company_id.partner_id),
244 'buyer': self.commercial_partner_id,
245 'buyer_address': get_address(self.commercial_partner_id),
246 'invoice_lines': invoice_lines_vals,
247 'tax_summary_vals': tax_summary_vals,
248 'float_repr': float_repr,
249 'float_is_zero': float_is_zero,
250 'get_vat_country': get_vat_country,
251 'get_vat_number': compact,
252 'get_amounts_from_tag': get_amounts_from_tag,
253 'get_amounts_from_tag_in_PLN_currency': get_amounts_from_tag_in_PLN_currency,
254 'invoice_type': ksef_type,
255 'related_invoices': self._l10n_pl_edi_get_related_invoices(),
256 'correction_info': correction_info,
257 'special_transactions': {'OSS_Base', 'OSS_Tax', 'Triangular Sale'} & invoice_tag_names,
258 'triangular_transaction': '1' if 'Triangular Sale' in invoice_tag_names else '2',
259 }
260
261 def _l10n_pl_edi_render_xml(self):
262 """
263 Renders the QWeb template, removes empty lines.
264 """
265 self.ensure_one()
266 qweb_template = self.env.ref('l10n_pl_edi.fa3_xml_template')
267 ksef_values = self._l10n_pl_edi_get_xml_values()
268 xml_content = self.env['ir.qweb']._render(qweb_template.id, ksef_values)
269 return "\n".join([line for line in xml_content.splitlines() if line.strip()])
270
271 def _l10n_pl_edi_get_status_mapping(self):
272 """
273 Returns a dictionary mapping KSeF status codes to (odoo_status, message).
274 """
275 return {
276 100: ('sent', self.env._("KSeF Status: Invoice accepted for further processing (Code: 100).")),
277 150: ('sent', self.env._("KSeF Status: Processing in progress (Code: 150).")),
278 200: ('accepted', self.env._("KSeF Status: Success (Code: 200). Invoice accepted.")),
279 405: ('rejected', self.env._("KSeF Status: Rejected (Code: 405). Processing canceled.")),
280 410: ('rejected', self.env._("KSeF Status: Rejected (Code: 410). Incorrect scope of permissions.")),
281 415: ('rejected', self.env._("KSeF Status: Rejected (Code: 415). It is not possible to send an invoice with an attachment.")),
282 430: ('rejected', self.env._("KSeF Status: Rejected (Code: 430). Invoice file verification error.")),
283 435: ('rejected', self.env._("KSeF Status: Rejected (Code: 435). File decryption error.")),
284 440: ('rejected', self.env._("KSeF Status: Rejected (Code: 440). Duplicate invoice.")),
285 450: ('rejected', self.env._("KSeF Status: Rejected (Code: 450). Invoice document semantics verification error.")),
286 500: ('rejected', self.env._("KSeF Status: Error (Code: 500). Unknown error.")),
287 }
288
289 def action_l10n_pl_edi_update_invoice_status(self):
290 self.ensure_one()
291
292 self.env['res.company']._with_locked_records(self)
293
294 def ask_status_api():
295
296 if not self.l10n_pl_edi_ref:
297 return {
298 'l10n_pl_edi_header': self.env._("This invoice does not have a KSeF Invoice Reference Number. It may not have been sent yet."),
299 }
300
301 service = KsefApiService(self.company_id)
302 try:
303 response = service.get_invoice_status(
304 self.l10n_pl_edi_ref,
305 session_id=self.l10n_pl_edi_session_id,
306 )
307 except UserError as e:
308 return {
309 'l10n_pl_edi_header': self.env._("Failed to check KSeF status: %s", e),
310 }
311
312 status_info = response.get('status', {})
313 status_code = status_info.get('code')
314 status_description = status_info.get('description', self.env._("No description provided."))
315
316 if values := self._l10n_pl_edi_get_status_mapping().get(status_code):
317 new_status, message = values
318 if status_code == 500:
319 message = f"{message} {status_description}"
320 else:
321 return {
322 'l10n_pl_edi_header': self.env._(
323 "Unknown status received from KSeF (Code: %(code)s): %(description)s",
324 code=status_code,
325 description=status_description,
326 ),
327 }
328
329 return {
330 'l10n_pl_edi_status': new_status,
331 'l10n_pl_edi_header': message,
332 'l10n_pl_edi_number': response.get('ksefNumber', False),
333 }
334
335 res = ask_status_api()
336
337 message = res.get('l10n_pl_edi_header')
338 new_status = res.get('l10n_pl_edi_status', self.l10n_pl_edi_status)
339 if message and (new_status != self.l10n_pl_edi_status):
340 self.with_context(no_new_invoice=True).sudo().message_post(body=message)
341
342 self.update(res)
343 return {
344 'type': 'ir.actions.client',
345 'tag': 'reload',
346 }
347
348 def action_l10n_pl_edi_get_invoice_UPO(self):
349 self.ensure_one()
350 if not self.l10n_pl_edi_ref:
351 raise UserError(self.env._("This invoice does not have a KSeF Invoice Reference Number. It may not have been sent yet."))
352
353 # It's good practice to only allow UPO download for accepted invoices
354 if self.l10n_pl_edi_status != 'accepted':
355 raise UserError(self.env._("You can only download a UPO for an 'Accepted' invoice. Please update the status first."))
356
357 service = KsefApiService(self.company_id)
358
359 try:
360 upo_xml_content = service.get_invoice_upo(
361 self.l10n_pl_edi_ref,
362 session_id=self.l10n_pl_edi_session_id,
363 )
364 except UserError as e:
365 self.message_post(body=self.env._("Failed to download UPO: %s", str(e)))
366 return None
367
368 if not upo_xml_content:
369 raise UserError(self.env._("The KSeF service returned empty UPO content."))
370
371 dom = parseString(upo_xml_content)
372 pretty_xml_bytes = dom.toprettyxml(indent=" ", encoding="utf-8")
373
374 if self.l10n_pl_edi_upo_id:
375 self.l10n_pl_edi_upo_file.raw = pretty_xml_bytes
376 else:
377 self.l10n_pl_edi_upo_id = self.env['ir.attachment'].create({
378 'name': f"UPO-{self.name.replace('/', '_')}.xml",
379 'description': self.env._('KSeF Official Confirmation of Receipt (UPO)'),
380 'type': 'binary',
381 'mimetype': 'application/xml',
382 'raw': pretty_xml_bytes,
383 'res_id': self.id,
384 'res_model': self._name,
385 'res_field': 'l10n_pl_edi_upo_file',
386 })
387
388 self.sudo().with_context(no_new_invoice=True).message_post(
389 body=self.env._("The KSeF Official Confirmation of Receipt (UPO) has been downloaded and attached."),
390 attachment_ids=self.l10n_pl_edi_upo_id.ids,
391 )
392
393 return {
394 'type': 'ir.actions.act_url',
395 'url': f'/web/content/{self.l10n_pl_edi_upo_id.id}?download=true',
396 'target': '_blank',
397 }
398
399 def _cron_l10n_pl_edi_check_invoice_status(self):
400 """get all moves that are in state sent run action_update_invoice_status on all of them"""
401 to_update_moves = self.env['account.move'].search([*self.env['account.move']._check_company_domain(self.env.company), ('l10n_pl_edi_status', '=', 'sent')])
402 for move in to_update_moves:
403 self.env['res.company']._with_locked_records(move)
404 move.action_l10n_pl_edi_update_invoice_status()
405
406 def button_draft(self):
407 """
408 When going from canceled => draft, we ensure to clear the edi fields
409 so that the invoice can be resent if required.
410 """
411 # EXTEND account
412 res = super().button_draft()
413 moves = self.filtered(lambda move: move.country_code == 'PL' and move.l10n_pl_edi_status == 'rejected')
414 moves.write(dict.fromkeys((
415 'l10n_pl_edi_status',
416 'l10n_pl_edi_number',
417 'l10n_pl_edi_ref',
418 'l10n_pl_edi_session_id',
419 'l10n_pl_edi_header',
420 ), False))
421 return res
422
423 @api.depends('l10n_pl_edi_status')
424 def _compute_show_reset_to_draft_button(self):
425 """
426 Invoices currently or correctly sent to the KSeF cannot be reset to draft.
427 """
428 # EXTENDS 'account'
429 super()._compute_show_reset_to_draft_button()
430 for move in self:
431 move.show_reset_to_draft_button = (
432 move.l10n_pl_edi_status not in ('sent', 'accepted')
433 and move.show_reset_to_draft_button
434 )
435
436 def _get_fields_to_detach(self):
437 # EXTENDS account
438 return super()._get_fields_to_detach() + ['l10n_pl_edi_attachment_file', 'l10n_pl_edi_upo_file']