Debian Codegraph @

addons/l10n_it_edi/models/account_move.py

raw symbols SCIP
1
2 import logging
3 import re
4 import uuid
5 from base64 import b64encode, b64decode
6 from collections import defaultdict
7 from datetime import datetime
8
9 from lxml import etree
10 from odoo.addons.base.models.ir_qweb_fields import Markup, nl2br, nl2br_enclose
11 from odoo.exceptions import LockError, UserError
12 from odoo.tools import cleanup_xml_node, float_compare, float_is_zero, float_repr, float_round, html2plaintext
13 from odoo.tools.sql import column_exists, create_column
14
15 from odoo import _, api, Command, fields, models, modules
16 from odoo.addons.account_edi_proxy_client.models.account_edi_proxy_user import AccountEdiProxyError
17 from odoo.addons.l10n_it_edi.models.account_payment_method_line import L10N_IT_PAYMENT_METHOD_SELECTION
18 from odoo.addons.l10n_it_edi.tools.remove_signature import remove_signature
19
20 _logger = logging.getLogger(__name__)
21
22
23 WAITING_STATES = ('being_sent', 'processing', 'forward_attempt')
24 FATTURAPA_FILENAME_RE = "[A-Z]{2}[A-Za-z0-9]{2,28}_[A-Za-z0-9]{0,5}.((?i:xml.p7m|xml))"
25
26
27 # -------------------------------------------------------------------------
28 # XML tool functions
29 # -------------------------------------------------------------------------
30
31 def get_text(tree, xpath, many=False):
32 texts = [el.text.strip() for el in tree.xpath(xpath) if el.text]
33 return texts if many else texts[0] if texts else ''
34
35 def get_float(tree, xpath):
36 try:
37 return float(get_text(tree, xpath))
38 except ValueError:
39 return 0.0
40
41 def get_date(tree, xpath):
42 """ Dates in FatturaPA are ISO 8601 date format, pattern '[-]CCYY-MM-DD[Z|(+|-)hh:mm]' """
43 dt = get_datetime(tree, xpath)
44 return dt.date() if dt else False
45
46 def get_datetime(tree, xpath):
47 """ Datetimes in FatturaPA are ISO 8601 date format, pattern '[-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]'
48 Python 3.7 -> 3.11 doesn't support 'Z'.
49 """
50 if datetime_str := get_text(tree, xpath):
51 try:
52 return datetime.fromisoformat(datetime_str.replace('Z', '+00:00'))
53 except (ValueError, TypeError):
54 return False
55 return False
56
57
58 class AccountMove(models.Model):
59 _inherit = 'account.move'
60
61 l10n_it_edi_state = fields.Selection(
62 string="SDI State",
63 selection=[
64 ('being_sent', 'Being Sent To SdI'),
65 ('requires_user_signature', 'Requires user signature'), # TODO: remove in master
66 ('processing', 'SdI Processing'),
67 ('rejected', 'SdI Rejected'),
68 ('forwarded', 'SdI Accepted, Forwarded to Partner'),
69 ('forward_failed', 'SdI Accepted, Forward to Partner Failed'),
70 ('forward_attempt', 'SdI Accepted, Forwarding to Partner'),
71 ('accepted_by_pa_partner', 'SdI Accepted, Accepted by the PA Partner'),
72 ('rejected_by_pa_partner', 'SdI Accepted, Rejected by the PA Partner'),
73 ('accepted_by_pa_partner_after_expiry', 'SdI Accepted, PA Partner Expired Terms'),
74 ],
75 copy=False, tracking=True,
76 help="This state is updated by default, but you can force the value. ",
77 )
78 l10n_it_edi_header = fields.Html(
79 help='User description of the current state, with hints to make the flow progress',
80 readonly=True,
81 copy=False,
82 )
83 l10n_it_edi_transaction = fields.Char(copy=False, string="FatturaPA Transaction")
84 l10n_it_edi_attachment_file = fields.Binary(copy=False, attachment=True)
85 l10n_it_edi_attachment_name = fields.Char(string="FatturaPA Attachment")
86 l10n_it_edi_proxy_mode = fields.Selection(related="company_id.l10n_it_edi_proxy_user_id.edi_mode", depends=['company_id'])
87 l10n_it_edi_button_label = fields.Char(compute="_compute_l10n_it_edi_button_label")
88 l10n_it_edi_is_self_invoice = fields.Boolean(compute="_compute_l10n_it_edi_is_self_invoice")
89 l10n_it_stamp_duty = fields.Float(string="Dati Bollo")
90 l10n_it_ddt_id = fields.Many2one('l10n_it.ddt', string='DDT', copy=False)
91
92 l10n_it_origin_document_type = fields.Selection(
93 string="Origin Document Type",
94 selection=[('purchase_order', 'Purchase Order'), ('contract', 'Contract'), ('agreement', 'Agreement')],
95 copy=False)
96 l10n_it_origin_document_name = fields.Char(
97 string="Origin Document Name",
98 copy=False)
99 l10n_it_origin_document_date = fields.Date(
100 string="Origin Document Date",
101 copy=False)
102 l10n_it_cig = fields.Char(
103 string="CIG",
104 copy=False,
105 help="Tender Unique Identifier")
106 l10n_it_cup = fields.Char(
107 string="CUP",
108 copy=False,
109 help="Public Investment Unique Identifier")
110 # Technical field for showing the above fields or not
111 l10n_it_partner_pa = fields.Boolean(compute='_compute_l10n_it_partner_pa')
112
113 l10n_it_payment_method = fields.Selection(
114 selection=L10N_IT_PAYMENT_METHOD_SELECTION,
115 compute='_compute_l10n_it_payment_method',
116 store=True,
117 readonly=False,
118 )
119
120 l10n_it_document_type = fields.Many2one(
121 comodel_name='l10n_it.document.type',
122 compute='_compute_l10n_it_document_type',
123 store=True,
124 readonly=False,
125 copy=False,
126 )
127
128 def _auto_init(self):
129 # Create compute stored field l10n_it_document_type and l10n_it_payment_method
130 # here to avoid timeout error on large databases.
131 if not column_exists(self.env.cr, 'account_move', 'l10n_it_payment_method'):
132 create_column(self.env.cr, 'account_move', 'l10n_it_payment_method', 'varchar')
133 if not column_exists(self.env.cr, 'account_move', 'l10n_it_document_type'):
134 create_column(self.env.cr, 'account_move', 'l10n_it_document_type', 'integer')
135 return super()._auto_init()
136
137
138 # -------------------------------------------------------------------------
139 # Computes
140 # -------------------------------------------------------------------------
141
142 @api.depends('line_ids.matching_number', 'payment_state', 'matched_payment_ids')
143 def _compute_l10n_it_payment_method(self):
144 if self.env.company.account_fiscal_country_id.code != 'IT':
145 return
146
147 move_lines_per_matching_number = self.env['account.move.line'].search([
148 ('matching_number', 'in', self.line_ids.filtered('matching_number').mapped('matching_number')),
149 ('company_id', '=', self.env.company.id),
150 ]).grouped('matching_number')
151
152 for move in self:
153 matching_numbers = move.line_ids.filtered('matching_number').mapped('matching_number')
154 if matching_numbers:
155 # We use matching_numbers[0] directly, assuming there's a valid key in the dictionary.
156 matching_lines = move_lines_per_matching_number.get(matching_numbers[0])
157 if matching_lines and matching_lines.payment_id:
158 payment_method_line = matching_lines.payment_id.payment_method_line_id[0]
159 if payment_method_line:
160 move.l10n_it_payment_method = payment_method_line.l10n_it_payment_method
161 continue # Skip to the next move
162 if linked_payment := move.matched_payment_ids.filtered(lambda p: p.state != 'draft')[:1]:
163 move.l10n_it_payment_method = linked_payment.payment_method_line_id.l10n_it_payment_method
164 continue
165
166 # Default handling if no valid matching lines found or if conditions don't match
167 move.l10n_it_payment_method = move.origin_payment_id.payment_method_line_id.l10n_it_payment_method or move.l10n_it_payment_method or 'MP05'
168
169 @api.depends('state')
170 def _compute_l10n_it_document_type(self):
171 document_type = self.env['l10n_it.document.type'].search([]).grouped('code')
172 for move in self:
173 if move.country_code != 'IT' or move.l10n_it_document_type or move.state != 'posted':
174 continue
175
176 move.l10n_it_document_type = document_type.get(move._l10n_it_edi_get_document_type())
177
178 @api.depends('commercial_partner_id.l10n_it_pa_index', 'company_id')
179 def _compute_l10n_it_partner_pa(self):
180 for move in self:
181 partner = move.commercial_partner_id
182 move.l10n_it_partner_pa = partner and (partner._l10n_it_edi_is_public_administration() or len(partner.l10n_it_pa_index or '') == 7)
183
184 @api.depends('country_code', 'l10n_it_edi_proxy_mode')
185 def _compute_l10n_it_edi_button_label(self):
186 for move in self:
187 if move.country_code == 'IT' and move.l10n_it_edi_proxy_mode in (False, 'demo'):
188 move.l10n_it_edi_button_label = _("Send (Demo)")
189 elif move.country_code == 'IT' and move.l10n_it_edi_proxy_mode == 'test':
190 move.l10n_it_edi_button_label = _("Send (Test)")
191 else:
192 move.l10n_it_edi_button_label = _("Send")
193
194 @api.depends('move_type', 'line_ids.tax_tag_ids')
195 def _compute_l10n_it_edi_is_self_invoice(self):
196 """
197 Italian EDI requires Vendor bills coming from EU countries to be sent as self-invoices.
198 We recognize these cases based on the taxes that target the VJ tax grids, which imply
199 the use of VAT External Reverse Charge.
200 """
201 purchases = self.filtered(lambda m: m.is_purchase_document())
202 others = self - purchases
203 for move in others:
204 move.l10n_it_edi_is_self_invoice = False
205 if purchases:
206 it_tax_report_vj_lines = self.env['account.report.line'].sudo().search([
207 ('report_id.country_id.code', '=', 'IT'),
208 ('code', '=like', 'VJ%')
209 ])
210 vj_lines_tags = it_tax_report_vj_lines.expression_ids._get_matching_tags()
211 for move in purchases:
212 invoice_lines_tags = move.line_ids.tax_tag_ids
213 ids_intersection = set(invoice_lines_tags.ids) & set(vj_lines_tags.ids)
214 move.l10n_it_edi_is_self_invoice = bool(ids_intersection)
215
216 def _l10n_it_edi_exempt_reason_tag_mapping(self):
217 return {
218 "N3.2": "VJ3",
219 "N3.3": "VJ1",
220 "N6.1": "VJ6",
221 "N6.2": "VJ7",
222 "N6.3": "VJ12",
223 "N6.4": "VJ13",
224 "N6.5": "VJ14",
225 "N6.6": "VJ15",
226 "N6.7": "VJ16",
227 "N6.8": "VJ17",
228 }
229
230 # -------------------------------------------------------------------------
231 # Overrides
232 # -------------------------------------------------------------------------
233
234 def _reverse_moves(self, default_values_list=None, cancel=False):
235 """
236 This function is needed because the l10n_it_document_type is set only if no value are set when posting it
237 But when reversing the move, the document type of the original move is copied and so it isn't recomputed.
238 """
239 # EXTENDS account
240 default_values_list = default_values_list or [{}] * len(self)
241 for default_values in default_values_list:
242 default_values.update({'l10n_it_document_type': False})
243 reverse_moves = super()._reverse_moves(default_values_list, cancel)
244 return reverse_moves
245
246 @api.depends('l10n_it_edi_transaction')
247 def _compute_show_reset_to_draft_button(self):
248 # EXTENDS 'account'
249 super()._compute_show_reset_to_draft_button()
250 for move in self:
251 move.show_reset_to_draft_button = not move.l10n_it_edi_transaction and move.show_reset_to_draft_button
252
253 def _get_xml_tree(self, file_data):
254 """ Some FatturaPA XMLs need to be parsed with `recover=True`,
255 and some have signatures that need to be removed prior to parsing.
256 """
257 # EXTENDS 'account'
258 res = super()._get_xml_tree(file_data)
259
260 # If the file was not correctly parsed, retry parsing it.
261 if res is None and self._is_l10n_it_edi_import_file(file_data):
262 def parse_xml(parser, name, content):
263 try:
264 return etree.fromstring(content, parser)
265 except (etree.ParseError, ValueError) as e:
266 _logger.info("XML parsing of %s failed: %s", name, e)
267
268 parser = etree.XMLParser(recover=True, resolve_entities=False)
269 xml_tree = parse_xml(parser, file_data['name'], file_data['raw'])
270 xml_tree = (
271 xml_tree if xml_tree is not None else
272 # The file may have a Cades signature, so we try removing it.
273 parse_xml(parser, file_data['name'], remove_signature(file_data['raw']))
274 )
275 if xml_tree is None:
276 _logger.info("Italian EDI invoice file %s cannot be decoded.", file_data['name'])
277 return xml_tree
278
279 return res
280
281 def _is_l10n_it_edi_import_file(self, file_data):
282 is_xml = (
283 file_data['name'].endswith('.xml')
284 or file_data['mimetype'].endswith('/xml')
285 or 'text/plain' in file_data['mimetype']
286 and file_data['raw']
287 and file_data['raw'].startswith(b'<?xml'))
288 is_p7m = file_data['mimetype'] == 'application/pkcs7-mime'
289 return (is_xml or is_p7m) and re.search(FATTURAPA_FILENAME_RE, file_data['name'])
290
291 def _get_import_file_type(self, file_data):
292 """ Identify FatturaPA XML and P7M files. """
293 # EXTENDS 'account'
294 if self._is_l10n_it_edi_import_file(file_data) and file_data['xml_tree'] is not None:
295 return 'l10n_it.fatturapa'
296 return super()._get_import_file_type(file_data)
297
298 def _unwrap_attachment(self, file_data, recurse=True):
299 """ Divide a FatturaPA file into constituent invoices and create a new attachment for each invoice after the first. """
300 # EXTENDS 'account'
301 if file_data['import_file_type'] != 'l10n_it.fatturapa':
302 return super()._unwrap_attachment(file_data, recurse)
303
304 embedded = self._split_xml_into_new_attachments(file_data, tag='FatturaElettronicaBody')
305 if embedded and recurse:
306 embedded.extend(self._unwrap_attachments(embedded, recurse=True))
307 return embedded
308
309 def _get_edi_decoder(self, file_data, new=False):
310 # EXTENDS 'account'
311 if file_data['import_file_type'] == 'l10n_it.fatturapa':
312 # Italy needs a custom order in prediction, since prediction generally deduces taxes
313 # from products, while in Italian EDI, taxes are generally explicited in the XML file
314 # while the product may not be labelled exactly the same as in the database.
315 def decoder(invoice, file_data, new=False):
316 self.with_context(disable_onchange_name_predictive=True)._l10n_it_edi_import_invoice(invoice, file_data, new)
317 return {
318 'priority': 20,
319 'decoder': decoder,
320 }
321 return super()._get_edi_decoder(file_data, new)
322
323 def _post(self, soft=True):
324 # EXTENDS 'account'
325 self.with_context(skip_is_manually_modified=True).write({'l10n_it_edi_header': False})
326 return super()._post(soft)
327
328 def _get_fields_to_detach(self):
329 # EXTENDS account
330 fields_list = super()._get_fields_to_detach()
331 fields_list.append('l10n_it_edi_attachment_file')
332 return fields_list
333
334 # -------------------------------------------------------------------------
335 # Business actions
336 # -------------------------------------------------------------------------
337
338 def action_l10n_it_edi_send(self):
339 """ Checks that the invoice data is coherent.
340 Attaches the XML file to the invoice.
341 Sends the invoice to the SdI.
342 """
343 self.ensure_one()
344
345 if errors := self._l10n_it_edi_export_data_check():
346 messages = []
347 for error_key, error_data in errors.items():
348 message = error_data['message']
349 split = error_key.split("_")
350 if len(split) > 3 and (model_id := {
351 'partner': 'res.partner',
352 'move': 'account.move',
353 'company': 'res.company'
354 }.get(split[3], None)):
355 if action := error_data.get('action'):
356 if 'res_id' in action:
357 record_ids = [action['res_id']]
358 else:
359 record_ids = action['domain'][0][2]
360 records = self.env[model_id].browse(record_ids)
361 message = f"{message} - {', '.join(records.mapped('display_name'))}"
362 messages.append(nl2br(message))
363
364 # Update the vendor bill's header with the warning messages,
365 # and force reload the view to make sure the header is loaded
366 self.l10n_it_edi_header = Markup('<br/>').join(messages)
367 return {
368 'type': 'ir.actions.client',
369 'tag': 'reload',
370 }
371
372 attachment_vals = self._l10n_it_edi_get_attachment_values(pdf_values=None)
373 self.l10n_it_edi_attachment_file = b64encode(attachment_vals['raw'])
374 self.l10n_it_edi_attachment_name = attachment_vals['name']
375 self.invalidate_recordset(fnames=['l10n_it_edi_attachment_name', 'l10n_it_edi_attachment_file'])
376 self.message_post(attachments=[(self.l10n_it_edi_attachment_name, attachment_vals['raw'])])
377 self._l10n_it_edi_send({self: attachment_vals})
378 self.is_move_sent = True
379
380 def action_check_l10n_it_edi(self):
381 self.ensure_one()
382 if not self.l10n_it_edi_transaction and self.l10n_it_edi_state not in WAITING_STATES:
383 raise UserError(_("This move is not waiting for updates from the SdI."))
384 if self.l10n_it_edi_state == 'being_sent':
385 return {'type': 'ir.actions.client', 'tag': 'reload'}
386 self._l10n_it_edi_update_send_state()
387
388 def button_draft(self):
389 # EXTENDS 'account'
390 for move in self:
391 move.l10n_it_edi_state = False
392 return super().button_draft()
393
394 def _get_invoice_legal_documents(self, filetype, allow_fallback=False):
395 # EXTENDS 'account'
396 self.ensure_one()
397 if filetype == 'fatturapa':
398 if fatturapa_attachment := self.l10n_it_edi_attachment_file:
399 return {
400 'filename': self.l10n_it_edi_attachment_name,
401 'filetype': 'xml',
402 'content': b64decode(fatturapa_attachment),
403 }
404 return super()._get_invoice_legal_documents(filetype, allow_fallback=allow_fallback)
405
406 def get_extra_print_items(self):
407 # EXTENDS 'account' - add possibility to download all FatturaPA XML files
408 print_items = super().get_extra_print_items()
409 if self.filtered('l10n_it_edi_attachment_file'):
410 print_items.append({
411 'key': 'download_xml_fatturapa',
412 'description': _('XML FatturaPA'),
413 **self.action_invoice_download_fatturapa(),
414 })
415 return print_items
416
417 def action_invoice_download_fatturapa(self):
418 if invoices_with_fatturapa := self.filtered('l10n_it_edi_attachment_file'):
419 return {
420 'type': 'ir.actions.act_url',
421 'url': f'/account/download_invoice_documents/{",".join(map(str, invoices_with_fatturapa.ids))}/fatturapa',
422 'target': 'download',
423 }
424 return False
425
426 # -------------------------------------------------------------------------
427 # Helpers
428 # -------------------------------------------------------------------------
429
430 def _l10n_it_edi_ready_for_xml_export(self):
431 self.ensure_one()
432 return (
433 self.state == 'posted'
434 and self.company_id.account_fiscal_country_id.code == 'IT'
435 and self.journal_id.type == 'sale'
436 and self.l10n_it_edi_state in (False, 'rejected')
437 )
438
439 def _l10n_it_edi_add_base_lines_xml_values(self, base_lines_aggregated_values, is_downpayment):
440 self.ensure_one()
441 quantita_pd = min(self.env['account.move.line']._fields['quantity'].get_digits(self.env)[1], 8)
442 for index, (base_line, aggregated_values) in enumerate(base_lines_aggregated_values, start=1):
443 line = base_line['record']
444 tax_details = base_line['tax_details']
445 discount = base_line['discount']
446 quantity = base_line['quantity']
447 price_subtotal = base_line['price_subtotal'] = tax_details['raw_total_excluded_currency']
448 it_values = base_line['it_values'] = {}
449
450 # Description.
451 # Down payment lines:
452 # If there was a down paid amount that has been deducted from this move,
453 # we need to put a reference to the down payment invoice in the DatiFattureCollegate tag
454 description = line.name
455 if not is_downpayment and price_subtotal < 0:
456 downpayment_moves = line._get_downpayment_lines().move_id
457 if downpayment_moves:
458 downpayment_moves_description = ', '.join(downpayment_moves.mapped('name'))
459 sep = ', ' if description else ''
460 description = f"{description}{sep}{downpayment_moves_description}"
461 # Workaround: remove line breaks due to Tax Agency portal bug.
462 # This deviates from Odoo's standard behavior and must be reviewed if the issue gets fixed.
463 description = description and description.replace('\n', ' ').strip() or "NO NAME"
464
465 # Price unit.
466 if quantity:
467 it_values['prezzo_unitario'] = base_line['gross_price_subtotal'] / quantity
468 else:
469 it_values['prezzo_unitario'] = 0.0
470 if base_line['currency_id'] != self.company_currency_id:
471 it_values['prezzo_unitario'] = it_values['prezzo_unitario'] / base_line['rate']
472
473 # Discount.
474 it_values['sconto_maggiorazione_list'] = []
475 if discount:
476 it_values['sconto_maggiorazione_list'] = [{
477 'tipo': 'SC' if discount > 0 else 'MG',
478 'percentuale': abs(discount),
479 'importo': None,
480 }]
481
482 # Tax rates.
483 rates = it_values['aliquota_iva_list'] = []
484 for values in aggregated_values.values():
485 grouping_key = values['grouping_key']
486 if not grouping_key or grouping_key['skip']:
487 continue
488
489 rates.append(grouping_key['tax_amount_field'] if grouping_key['tax_amount_type_field'] == 'percent' else 0.0)
490
491 # Tax exempt reason.
492 vat_tax = base_line['tax_ids'].flatten_taxes_hierarchy().filtered(lambda t: t._l10n_it_filter_kind('vat') and t.amount >= 0)[:1]
493 it_values['natura'] = vat_tax.l10n_it_exempt_reason or None
494
495 # Other data.
496 other_data_list = it_values['altri_dati_gestionali_list'] = []
497 if base_line['currency_id'] != self.company_currency_id:
498 other_data_list.extend([
499 {
500 'tipo_dato': 'DIVISA',
501 'riferimento_testo': base_line['currency_id'].name,
502 'riferimento_numero': tax_details['raw_total_excluded_currency'],
503 'riferimento_data': None,
504 },
505 {
506 'tipo_dato': 'CAMBIO',
507 'riferimento_testo': None,
508 'riferimento_numero': base_line['rate'],
509 'riferimento_data': self.invoice_date,
510 },
511 ])
512
513 it_values.update({
514 'numero_linea': index,
515 'descrizione': description,
516 'prezzo_totale': tax_details['raw_total_excluded'],
517 'quantita': quantity,
518 'quantita_pd': quantita_pd,
519 'ritenuta': None,
520 })
521
522 def _l10n_it_edi_get_tax_lines_xml_values(self, base_lines_aggregated_values, values_per_grouping_key):
523 self.ensure_one()
524 tax_lines = []
525 for values in values_per_grouping_key.values():
526 grouping_key = values['grouping_key']
527 if not grouping_key or grouping_key['skip']:
528 continue
529
530 rounding = values['base_amount']
531 for _base_line, aggregated_values in base_lines_aggregated_values:
532 if grouping_key in aggregated_values:
533 rounding -= aggregated_values[grouping_key]['raw_base_amount']
534 if float_is_zero(rounding, precision_digits=8):
535 rounding = None
536
537 tax_lines.append({
538 'aliquota_iva': grouping_key['tax_amount_field'],
539 'natura': grouping_key['l10n_it_exempt_reason'],
540 'arrotondamento': rounding,
541 'imponibile_importo': values['base_amount'],
542 'imposta': values['tax_amount'],
543 'esigibilita_iva': grouping_key['tax_exigibility_code'],
544 'riferimento_normativo': grouping_key['invoice_legal_notes'],
545 })
546 return tax_lines
547
548 @api.model
549 def _l10n_it_edi_is_neg_split_payment(self, tax_data):
550 tax = tax_data['tax']
551 return (
552 tax.amount < 0.0
553 and tax_data['group']
554 and any(child_tax._l10n_it_is_split_payment() for child_tax in tax_data['group'].children_tax_ids)
555 )
556
557 @api.model
558 def _l10n_it_edi_grouping_function_base_lines(self, base_line, tax_data):
559 if not tax_data:
560 return None
561 tax = tax_data['tax']
562 return {
563 'tax_amount_field': -23.0 if tax.amount in (-11.5, -4.6) else tax.amount,
564 'tax_amount_type_field': tax.amount_type,
565 'skip': (
566 tax_data['is_reverse_charge']
567 or self._l10n_it_edi_is_neg_split_payment(tax_data)
568 or tax._l10n_it_filter_kind('withholding')
569 or tax._l10n_it_filter_kind('pension_fund')
570 ),
571 }
572
573 @api.model
574 def _l10n_it_edi_grouping_function_tax_lines(self, base_line, tax_data):
575 if not tax_data:
576 return None
577 tax = tax_data['tax']
578
579 if tax._l10n_it_is_split_payment():
580 tax_exigibility_code = 'S'
581 elif tax.tax_exigibility == 'on_payment':
582 tax_exigibility_code = 'D'
583 elif tax.tax_exigibility == 'on_invoice':
584 tax_exigibility_code = 'I'
585 else:
586 tax_exigibility_code = None
587
588 return {
589 'tax_amount_field': -23.0 if tax.amount in (-11.5, -4.6) else tax.amount,
590 'l10n_it_exempt_reason': tax.l10n_it_exempt_reason,
591 'invoice_legal_notes': html2plaintext(tax.invoice_legal_notes),
592 'tax_exigibility_code': tax_exigibility_code,
593 'tax_amount_type_field': tax.amount_type,
594 'skip': (
595 tax_data['is_reverse_charge']
596 or self._l10n_it_edi_is_neg_split_payment(tax_data)
597 or tax._l10n_it_filter_kind('withholding')
598 or tax._l10n_it_filter_kind('pension_fund')
599 ),
600 }
601
602 @api.model
603 def _l10n_it_edi_grouping_function_total(self, base_line, tax_data):
604 if not tax_data:
605 return None
606 skip = (
607 tax_data['is_reverse_charge']
608 or self._l10n_it_edi_is_neg_split_payment(tax_data)
609 or tax_data['tax']._l10n_it_filter_kind('withholding')
610 or tax_data['tax']._l10n_it_filter_kind('pension_fund')
611 )
612 return not skip
613
614 def _prepare_product_base_line_for_taxes_computation(self, product_line):
615 """
616 Prepares tax base line. Rounding lines must appear in the XML,
617 so they are converted to regular lines with tax exemption code ('N2.2').
618 """
619 base_line = super()._prepare_product_base_line_for_taxes_computation(product_line)
620
621 if product_line.display_type == 'rounding':
622 base_line.update({
623 'quantity': 1,
624 'price_unit': -product_line.amount_currency,
625 'tax_ids': self._l10n_it_edi_search_tax_for_import(self.company_id, 0.0, l10n_it_exempt_reason='N2.2'),
626 })
627
628 return base_line
629
630 def _l10n_it_edi_get_values(self, pdf_values=None):
631 def grouping_function_withholding(base_line, tax_data):
632 if not tax_data:
633 return None
634 tax = tax_data['tax']
635 return {
636 'tax_amount_field': -23.0 if tax.amount in (-11.5, -4.6) else tax.amount,
637 'l10n_it_withholding_type': tax.l10n_it_withholding_type,
638 'l10n_it_withholding_reason': tax.l10n_it_withholding_reason,
639 'skip': not tax._l10n_it_filter_kind('withholding'),
640 }
641
642 def grouping_function_pension_funds(base_line, tax_data):
643 if not tax_data:
644 return None
645 tax = tax_data['tax']
646 flatten_taxes = base_line['tax_ids'].flatten_taxes_hierarchy()
647 vat_tax = flatten_taxes.filtered(lambda t: t._l10n_it_filter_kind('vat') and t.amount >= 0)[:1]
648 withholding_tax = flatten_taxes.filtered(lambda t: t._l10n_it_filter_kind('withholding') and t.sequence > tax.sequence)[:1]
649 return {
650 'tax_amount_field': -23.0 if tax.amount in (-11.5, -4.6) else tax.amount,
651 'vat_tax_amount_field': -23.0 if vat_tax.amount in (-11.5, -4.6) else vat_tax.amount,
652 'has_withholding': bool(withholding_tax),
653 'l10n_it_pension_fund_type': tax.l10n_it_pension_fund_type,
654 'l10n_it_exempt_reason': vat_tax.l10n_it_exempt_reason,
655 'description': vat_tax.description,
656 'skip': not tax._l10n_it_filter_kind('pension_fund') or tax.l10n_it_pension_fund_type == 'TC07',
657 }
658
659 self.ensure_one()
660
661 # Flags
662 is_self_invoice = self.l10n_it_edi_is_self_invoice
663 document_type = self.l10n_it_document_type.code
664
665 # Represent if the document is a reverse charge refund in a single variable
666 reverse_charge = document_type in ['TD16', 'TD17', 'TD18', 'TD19']
667 is_downpayment = document_type in ['TD02']
668 reverse_charge_refund = self.move_type == 'in_refund' and reverse_charge
669 convert_to_euros = self.currency_id.name != 'EUR'
670
671 # Base lines.
672 base_amls = self.line_ids.filtered(lambda x: x.display_type == 'product' or x.display_type == 'rounding')
673 base_lines = [self._prepare_product_base_line_for_taxes_computation(x) for x in base_amls]
674 tax_amls = self.line_ids.filtered('tax_repartition_line_id')
675 tax_lines = [self._prepare_tax_line_for_taxes_computation(x) for x in tax_amls]
676
677 if reverse_charge_refund:
678 for base_line in base_lines:
679 base_line['price_unit'] *= -1
680
681 AccountTax = self.env['account.tax']
682 AccountTax._add_tax_details_in_base_lines(base_lines, self.company_id)
683
684 downpayment_lines = []
685 for base_line in base_lines:
686 tax_details = base_line['tax_details']
687 discount = base_line['discount']
688 price_unit = base_line['price_unit']
689 quantity = base_line['quantity']
690 price_subtotal = base_line['price_subtotal'] = tax_details['raw_total_excluded_currency']
691
692 if discount == 100.0:
693 gross_price_subtotal_before_discount = price_unit * quantity
694 else:
695 gross_price_subtotal_before_discount = price_subtotal / (1 - discount / 100.0)
696
697 base_line['gross_price_subtotal'] = gross_price_subtotal_before_discount
698 base_line['discount_amount_before_dispatching'] = gross_price_subtotal_before_discount - price_subtotal
699
700 # The tax "23% Ritenuta Agenti e Rappresentanti" is not supported because it's supposed to be a tax of 23% based on
701 # 50% or 20% of the base amount. It's currently implemented as a -11.5% or -4.6% tax respectively. So on 1000, it
702 # gives an amount of -115(for 50%) or -46(for 20%).
703 # We need to fix the base amount from 1000 to 500.0 or 200.0.
704 for tax_data in tax_details['taxes_data']:
705 tax = tax_data['tax']
706 tax_data['_tax_amount'] = tax.amount
707 if tax.amount == -11.5:
708 tax_data['_tax_amount'] = -23.0
709 tax_data['raw_base_amount'] *= 0.5
710 tax_data['raw_base_amount_currency'] *= 0.5
711 elif tax.amount == -4.6:
712 tax_data['_tax_amount'] = -23.0
713 tax_data['raw_base_amount'] *= 0.2
714 tax_data['raw_base_amount_currency'] *= 0.2
715
716 if not is_downpayment:
717 # Negative lines linked to down payment should stay negative
718 line = base_line['record']
719 if line.price_subtotal < 0 and line._get_downpayment_lines():
720 downpayment_lines.append(base_line)
721
722 if float_compare(quantity, 0, 2) < 0:
723 # Negative quantity is refused by SDI, so we invert quantity and price_unit to keep the price_subtotal
724 base_line.update({
725 'quantity': -quantity,
726 'price_unit': -price_unit,
727 })
728
729 AccountTax._round_base_lines_tax_details(base_lines, self.company_id, tax_lines=tax_lines)
730 base_lines_aggregated_values = AccountTax._aggregate_base_lines_tax_details(base_lines, self._l10n_it_edi_grouping_function_base_lines)
731 self._l10n_it_edi_add_base_lines_xml_values(base_lines_aggregated_values, is_downpayment)
732 base_lines = sorted(base_lines, key=lambda base_line: base_line['it_values']['numero_linea'])
733
734 # Tax lines.
735 base_lines_aggregated_values = AccountTax._aggregate_base_lines_tax_details(base_lines, self._l10n_it_edi_grouping_function_tax_lines)
736 values_per_grouping_key = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values)
737 tax_lines = self._l10n_it_edi_get_tax_lines_xml_values(base_lines_aggregated_values, values_per_grouping_key)
738
739 # Total of the document.
740 base_lines_aggregated_values = AccountTax._aggregate_base_lines_tax_details(base_lines, self._l10n_it_edi_grouping_function_total)
741 values_per_grouping_key = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values)
742 importo_totale_documento = 0.0
743 for values in values_per_grouping_key.values():
744 grouping_key = values['grouping_key']
745 if grouping_key is False:
746 continue
747 importo_totale_documento += values['base_amount_currency']
748 importo_totale_documento += values['tax_amount_currency']
749
750 company = self.company_id._l10n_it_get_edi_company()
751 partner = self.commercial_partner_id
752 sender = company
753 buyer = partner if not is_self_invoice else company
754 seller = company if not is_self_invoice else partner
755 sender_info_values = company.partner_id._l10n_it_edi_get_values()
756 buyer_info_values = (partner if not is_self_invoice else company.partner_id)._l10n_it_edi_get_values()
757 seller_info_values = (company.partner_id if not is_self_invoice else partner)._l10n_it_edi_get_values()
758 representative_info_values = company.l10n_it_tax_representative_partner_id._l10n_it_edi_get_values()
759
760 if self._l10n_it_edi_is_simplified_document_type(document_type):
761 formato_trasmissione = "FSM10"
762 elif partner._l10n_it_edi_is_public_administration():
763 formato_trasmissione = "FPA12"
764 else:
765 formato_trasmissione = "FPR12"
766
767 # Reference line for finding the conversion rate used in the document
768 conversion_rate = float_repr(
769 abs(self.amount_total / self.amount_total_signed), precision_digits=5,
770 ) if convert_to_euros and self.invoice_line_ids else None
771
772 # Aggregated linked invoices
773 linked_moves = (self._get_reconciled_invoices() | self.reversed_entry_id).filtered(lambda move: move.date <= self.date)
774
775 # Reduce downpayment views to a single recordset
776 linked_moves |= self.invoice_line_ids._get_downpayment_lines().move_id
777
778 # Withholding tax amounts.
779
780 base_lines_aggregated_values = AccountTax._aggregate_base_lines_tax_details(base_lines, grouping_function_withholding)
781 values_per_grouping_key = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values)
782 withholding_values = []
783 for values in values_per_grouping_key.values():
784 grouping_key = values['grouping_key']
785 if not grouping_key or grouping_key['skip']:
786 continue
787
788 withholding_values.append({
789 'tipo_ritenuta': grouping_key['l10n_it_withholding_type'],
790 'importo_ritenuta': -values['tax_amount'],
791 'aliquota_ritenuta': -grouping_key['tax_amount_field'],
792 'causale_pagamento': grouping_key['l10n_it_withholding_reason'],
793 })
794
795 # Pension fund.
796 base_lines_aggregated_values = AccountTax._aggregate_base_lines_tax_details(base_lines, grouping_function_pension_funds)
797 values_per_grouping_key = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values)
798 pension_fund_values = []
799 for values in values_per_grouping_key.values():
800 grouping_key = values['grouping_key']
801 if not grouping_key or grouping_key['skip']:
802 continue
803
804 pension_fund_values.append({
805 'tipo_cassa': grouping_key['l10n_it_pension_fund_type'],
806 'al_cassa': grouping_key['tax_amount_field'],
807 'importo_contributo_cassa': values['tax_amount'],
808 'imponibile_cassa': values['base_amount'],
809 'aliquota_iva': grouping_key['vat_tax_amount_field'],
810 'ritenuta': 'SI' if grouping_key['has_withholding'] else None,
811 'natura': grouping_key['l10n_it_exempt_reason'],
812 'riferimento_amministrazione': html2plaintext(grouping_key['description']),
813 })
814
815 # Enasarco values.
816 for base_line in base_lines:
817 taxes_data = base_line['tax_details']['taxes_data']
818 it_values = base_line['it_values']
819 other_data_list = it_values['altri_dati_gestionali_list']
820
821 # Withholding
822 if any(x for x in taxes_data if x['tax']._l10n_it_filter_kind('withholding')):
823 it_values['ritenuta'] = 'SI'
824
825 # Enasarco
826 enasarco_taxes_data = [x for x in taxes_data if x['tax'].l10n_it_pension_fund_type == 'TC07']
827 for enasarco_tax_data in enasarco_taxes_data:
828 percentage_str = round(abs(enasarco_tax_data['tax'].amount), 1)
829 other_data_list.append({
830 'tipo_dato': 'CASSA-PREV',
831 'riferimento_testo': f'TC07 - ENASARCO ({percentage_str}%)',
832 'riferimento_numero': -enasarco_tax_data['tax_amount'],
833 'riferimento_data': None,
834 })
835
836 # Pension Fund
837 if not enasarco_taxes_data:
838 pension_fund_taxes_data = [x for x in taxes_data if x['tax']._l10n_it_filter_kind('pension_fund')]
839 for pension_fund_tax_data in pension_fund_taxes_data:
840 pension_type = pension_fund_tax_data['tax'].l10n_it_pension_fund_type
841 percentage_str = round(abs(pension_fund_tax_data['tax'].amount))
842 other_data_list.append({
843 'tipo_dato': 'AswCassPre',
844 'riferimento_testo': f'{pension_type} ({percentage_str}%)',
845 'riferimento_numero': None,
846 'riferimento_data': None,
847 })
848
849 return {
850 'record': self,
851 'base_lines': base_lines,
852 'tax_lines': tax_lines,
853 'importo_totale_documento': importo_totale_documento,
854 'company': company,
855 'partner': partner,
856 'sender': sender,
857 'buyer': buyer,
858 'seller': seller,
859 'representative': company.l10n_it_tax_representative_partner_id,
860 'sender_info': sender_info_values,
861 'buyer_info': buyer_info_values,
862 'seller_info': seller_info_values,
863 'representative_info': representative_info_values,
864 'origin_document_type': self.l10n_it_origin_document_type,
865 'origin_document_name': self.l10n_it_origin_document_name,
866 'origin_document_date': self.l10n_it_origin_document_date,
867 'cig': self.l10n_it_cig,
868 'cup': self.l10n_it_cup,
869 'currency': self.currency_id or self.company_currency_id if not convert_to_euros else self.env.ref('base.EUR'),
870 'regime_fiscale': company.l10n_it_tax_system if not is_self_invoice else 'RF18',
871 'is_self_invoice': is_self_invoice,
872 'partner_bank': self.partner_bank_id,
873 'formato_trasmissione': formato_trasmissione,
874 'document_type': document_type,
875 'payment_method': self.l10n_it_payment_method,
876 'linked_moves': linked_moves,
877 'rc_refund': reverse_charge_refund,
878 'conversion_rate': conversion_rate,
879 'balance_multiplicator': -1 if self.is_inbound() else 1,
880 'abs': abs,
881 'pdf_name': pdf_values['name'] if pdf_values else False,
882 'pdf': b64encode(pdf_values['raw']).decode() if pdf_values else False,
883 'withholding_values': withholding_values,
884 'pension_fund_values': pension_fund_values,
885 }
886
887 def _l10n_it_edi_services_or_goods(self):
888 """
889 Services and goods have different tax grids when VAT is Reverse Charged, and they can't
890 be mixed in the same invoice, because the TipoDocumento depends on which which kind
891 of product is bought and it's unambiguous.
892 """
893 self.ensure_one()
894 scopes = []
895 for line in self.invoice_line_ids.filtered(lambda l: l.display_type not in ('line_section', 'line_subsection', 'line_note')):
896 tax_ids_with_tax_scope = line.tax_ids.filtered(lambda x: x.tax_scope)
897 if tax_ids_with_tax_scope:
898 scopes += tax_ids_with_tax_scope.mapped('tax_scope')
899 else:
900 scopes.append(line.product_id and line.product_id.type == 'service' and 'service' or 'consu')
901
902 if set(scopes) == {'consu', 'service'}:
903 return "both"
904 return scopes and scopes.pop()
905
906 def _l10n_it_edi_goods_in_italy(self):
907 """
908 There is a specific TipoDocumento (Document Type TD19) and tax grid (VJ3) for goods
909 that are phisically in Italy but are in a VAT deposit, meaning that the goods
910 have not passed customs.
911 """
912 self.ensure_one()
913 invoice_lines_tags = self.line_ids.tax_tag_ids
914 it_tax_report_vj3_lines = self.env['account.report.line'].search([
915 ('report_id.country_id.code', '=', 'IT'),
916 ('code', '=', 'VJ3'),
917 ])
918 vj3_lines_tags = it_tax_report_vj3_lines.expression_ids._get_matching_tags()
919 return bool(invoice_lines_tags & vj3_lines_tags)
920
921 def _l10n_it_edi_is_simplified(self):
922 """
923 Simplified Invoices are a way for the invoice issuer to create an invoice with limited data.
924 Example: a consultant goes to the restaurant and wants the invoice instead of the receipt,
925 to be able to deduct the expense from his Taxes. The Italian State allows the restaurant
926 to issue a Simplified Invoice with the VAT number only, to speed up times, instead of
927 requiring the address and other informations about the buyer.
928 Only invoices under the threshold of 400 Euroes are allowed, to avoid this tool
929 be abused for bigger transactions, that would enable less transparency to tax institutions.
930 """
931 self.ensure_one()
932 template_reference = self.env.ref('l10n_it_edi.account_invoice_it_simplified_FatturaPA_export', raise_if_not_found=False)
933 buyer = self.commercial_partner_id
934 checks = ['partner_address_missing', 'partner_vat_codice_fiscale_missing']
935 return bool(
936 template_reference
937 and not self.l10n_it_edi_is_self_invoice
938 and list(buyer._l10n_it_edi_export_check(checks).keys()) == ['l10n_it_edi_partner_address_missing']
939 and (not buyer.country_id or buyer.country_id.code == 'IT')
940 and (buyer.l10n_it_codice_fiscale or (buyer.vat and (buyer.vat[:2].upper() == 'IT' or buyer.vat[:2].isdecimal())))
941 and self.amount_total <= 400
942 )
943
944 def _l10n_it_edi_is_professional_fees(self):
945 """
946 This function returns a boolean value based on the comparison of the lines values with a product.
947 If one line has the tag for professional fee then we return True
948 """
949 self.ensure_one()
950 professional_fee_tag = self.env.ref('l10n_it_edi.l10n_it_edi_professional_fees_tag', raise_if_not_found=False)
951 if not professional_fee_tag:
952 return False
953
954 return any(
955 professional_fee_tag.id in line.account_id.tag_ids.ids
956 for line in self.invoice_line_ids
957 if line.display_type not in ('line_section', 'line_subsection', 'line_note')
958 )
959
960 def _l10n_it_edi_features_for_document_type_selection(self):
961 """ Returns a dictionary of features to be compared with the TDxx FatturaPA
962 document type requirements. """
963 partner_values = self.commercial_partner_id._l10n_it_edi_get_values()
964 services_or_goods = self._l10n_it_edi_services_or_goods()
965 return {
966 'move_types': self.move_type,
967 'partner_in_eu': partner_values.get('in_eu', False),
968 'partner_country_code': partner_values.get('country_code', False),
969 'simplified': self._l10n_it_edi_is_simplified(),
970 'self_invoice': self.l10n_it_edi_is_self_invoice,
971 'tax_tags': {tag for tag in self.line_ids.tax_tag_ids.mapped(lambda x: (x.name or '').upper()) if tag},
972 'downpayment': self._is_downpayment(),
973 'services_or_goods': services_or_goods,
974 'goods_in_italy': services_or_goods == 'consu' and self._l10n_it_edi_goods_in_italy(),
975 'professional_fees': self._l10n_it_edi_is_professional_fees(),
976 **({'debit_note': True} if self.debit_origin_id else {}),
977 }
978
979 def _l10n_it_edi_document_type_mapping(self):
980 """ Returns a dictionary with the required features for every TDxx FatturaPA document type """
981 return {
982 'TD01': {'move_types': ['in_invoice', 'out_invoice'],
983 'import_type': 'in_invoice',
984 'self_invoice': False,
985 'simplified': False,
986 'downpayment': False,
987 'professional_fees': False,
988 'debit_note': False},
989 'TD02': {'move_types': ['out_invoice'],
990 'import_type': 'in_invoice',
991 'self_invoice': False,
992 'simplified': False,
993 'downpayment': True,
994 'professional_fees': False},
995 'TD03': {'move_types': ['out_invoice'],
996 'import_type': 'in_invoice',
997 'self_invoice': False,
998 'simplified': False,
999 'downpayment': True,
1000 'professional_fees': True},
1001 'TD04': {'move_types': ['out_refund'],
1002 'import_type': 'in_refund',
1003 'self_invoice': False,
1004 'simplified': False},
1005 'TD05': {'move_types': ['in_invoice', 'out_invoice'],
1006 'import_type': 'in_invoice',
1007 'self_invoice': False,
1008 'simplified': False,
1009 'debit_note': True},
1010 'TD06': {'move_types': ['out_invoice'],
1011 'import_type': 'in_invoice',
1012 'self_invoice': False,
1013 'simplified': False,
1014 'downpayment': False,
1015 'professional_fees': True},
1016 'TD07': {'move_types': ['out_invoice'],
1017 'import_type': 'in_invoice',
1018 'self_invoice': False,
1019 'simplified': True},
1020 'TD08': {'move_types': ['out_refund'],
1021 'import_type': 'in_refund',
1022 'self_invoice': False,
1023 'simplified': True},
1024 'TD09': {'move_types': ['out_invoice'],
1025 'import_type': 'in_invoice',
1026 'self_invoice': False,
1027 'simplified': True},
1028 'TD28': {'move_types': ['in_invoice', 'in_refund'],
1029 'import_type': 'in_invoice',
1030 'simplified': False,
1031 'self_invoice': True,
1032 'partner_country_code': "SM"},
1033 'TD16': {'move_types': ['in_invoice', 'in_refund'],
1034 'import_type': 'in_invoice',
1035 'simplified': False,
1036 'self_invoice': True,
1037 'tax_tags': {'VJ6', 'VJ7', 'VJ8', 'VJ12', 'VJ13', 'VJ14', 'VJ15', 'VJ16', 'VJ17'}},
1038 'TD17': {'move_types': ['in_invoice', 'in_refund'],
1039 'import_type': 'in_invoice',
1040 'simplified': False,
1041 'self_invoice': True,
1042 'services_or_goods': "service",
1043 'tax_tags': {'VJ3'}},
1044 'TD18': {'move_types': ['in_invoice', 'in_refund'],
1045 'import_type': 'in_invoice',
1046 'simplified': False,
1047 'self_invoice': True,
1048 'services_or_goods': "consu",
1049 'goods_in_italy': False,
1050 'partner_in_eu': True,
1051 'tax_tags': {'VJ9'}},
1052 'TD19': {'move_types': ['in_invoice', 'in_refund'],
1053 'import_type': 'in_invoice',
1054 'simplified': False,
1055 'self_invoice': True,
1056 'services_or_goods': "consu",
1057 'goods_in_italy': True,
1058 'tax_tags': {'VJ3'}},
1059 }
1060
1061 def _l10n_it_edi_get_document_type(self):
1062 """ Retrieve document type from the move. If not set, compare the features
1063 of the invoice to the requirements of each Document Type (TDxx)
1064 FatturaPA until you find a valid one. """
1065
1066 def compare(actual_values, expected_values):
1067 """ Compare a single entry from the invoice features with the one of the document_type """
1068 if isinstance(expected_values, set | list | tuple):
1069 # i.e. When we compare actual tax_tags from the invoice with expected tags, we see if there is at least one in common
1070 if isinstance(actual_values, set):
1071 return actual_values & set(expected_values)
1072 # i.e. When we compare the move_type with the available ones, these can be more than one
1073 return actual_values in expected_values
1074 # We compare other features directly, one on one
1075 return actual_values == expected_values
1076
1077 if self.l10n_it_document_type:
1078 return self.l10n_it_document_type.code
1079
1080 invoice_features = self._l10n_it_edi_features_for_document_type_selection()
1081 for document_type_code, document_type_features in self._l10n_it_edi_document_type_mapping().items():
1082 # By using a generator instead of a list, we can avoid some comparisons
1083 if all(compare(invoice_values, document_type_features[k]) for k, invoice_values in invoice_features.items() if k in document_type_features):
1084 return document_type_code
1085 return False
1086
1087 def _l10n_it_edi_is_simplified_document_type(self, document_type):
1088 mapping = self._l10n_it_edi_document_type_mapping()
1089 return mapping.get(document_type, {}).get('simplified', False)
1090
1091 @api.model
1092 def _l10n_it_buyer_seller_info(self):
1093 return {
1094 'buyer': {
1095 'role': 'buyer',
1096 'section_xpath': '//CessionarioCommittente',
1097 'vat_xpath': '//CessionarioCommittente//IdCodice',
1098 'codice_fiscale_xpath': '//CessionarioCommittente//CodiceFiscale',
1099 'type_tax_use_domain': [('type_tax_use', '=', 'purchase')],
1100 },
1101 'seller': {
1102 'role': 'seller',
1103 'section_xpath': '//CedentePrestatore',
1104 'vat_xpath': '//CedentePrestatore//IdCodice',
1105 'codice_fiscale_xpath': '//CedentePrestatore//CodiceFiscale',
1106 'type_tax_use_domain': [('type_tax_use', '=', 'sale')],
1107 },
1108 }
1109
1110 # -------------------------------------------------------------------------
1111 # EDI: Import
1112 # -------------------------------------------------------------------------
1113
1114 def cron_l10n_it_edi_download_and_update(self):
1115 """ Crons run with sudo(), with empty recordset. Remember that. """
1116 retrigger = False
1117 for proxy_user in self.env['account_edi_proxy_client.user'].search([('proxy_type', '=', 'l10n_it_edi')]):
1118 proxy_user = proxy_user.with_company(proxy_user.company_id)
1119 if proxy_user.edi_mode != 'demo':
1120 moves_to_check = self.search([
1121 ('company_id', '=', proxy_user.company_id.id),
1122 ('l10n_it_edi_transaction', '!=', False),
1123 ('l10n_it_edi_state', 'in', WAITING_STATES)
1124 ])
1125 if moves_to_check:
1126 moves_to_check._l10n_it_edi_update_send_state()
1127 retrigger = retrigger or self._l10n_it_edi_download_invoices(proxy_user)
1128
1129 # Retrigger download if there are still some on the server
1130 if retrigger:
1131 _logger.info('Retriggering "Receive invoices from the SdI"...')
1132 self.env.ref('l10n_it_edi.ir_cron_l10n_it_edi_download_and_update')._trigger()
1133
1134 def _l10n_it_edi_download_invoices(self, proxy_user):
1135 """ Check the proxy for incoming invoices for a specified proxy user.
1136 :return: True if there remain some invoices on the server to be downloaded, False otherwise.
1137 """
1138 server_url = proxy_user._get_server_url()
1139
1140 # Download invoices
1141 invoices_data = {}
1142 try:
1143 invoices_data = proxy_user._make_request(f'{server_url}/api/l10n_it_edi/1/in/RicezioneInvoice',
1144 params={'recipient_codice_fiscale': proxy_user.company_id.l10n_it_codice_fiscale})
1145 except AccountEdiProxyError as e:
1146 _logger.error('Error while receiving invoices from the SdI: %s', e)
1147 return False
1148
1149 # Process the downloaded invoices
1150 processed = self._l10n_it_edi_process_downloads(invoices_data, proxy_user)
1151 if processed['proxy_acks']:
1152 try:
1153 proxy_user._make_request(
1154 f'{server_url}/api/l10n_it_edi/1/ack',
1155 params={'transaction_ids': processed['proxy_acks']})
1156 except AccountEdiProxyError as e:
1157 _logger.error('Error while receiving file from the SdI: %s', e)
1158
1159 return processed['retrigger']
1160
1161 def _l10n_it_edi_process_downloads(self, invoices_data, proxy_user):
1162 """ Every attachment will be committed if stored succesfully.
1163 Also moves will be committed one by one, even if imported incorrectly.
1164 """
1165 proxy_acks = []
1166 retrigger = False
1167
1168 attachment_vals = []
1169 for id_transaction, invoice_data in invoices_data.items():
1170
1171 # The IAP server has a maximum number of documents it can send.
1172 # If that maximum is reached, then we search for more
1173 # by re-triggering the download cron, avoiding the timeout.
1174 current_num = invoice_data.get('current_num', 0)
1175 max_num = invoice_data.get('max_num', 0)
1176 retrigger = retrigger or current_num == max_num > 0
1177
1178 # `_l10n_it_edi_create_move_from_attachment` will create an empty move
1179 # then try and fill it with the content imported from the attachment.
1180 # Should the import fail, thanks to try..except and rollback,
1181 # we will anyway end up with an empty `in_invoice` with the attachment posted on it.
1182 if filename_and_decrypted_content := self._l10n_it_edi_check_and_decrypt_content(
1183 invoice_data['filename'],
1184 invoice_data['file'],
1185 invoice_data['key'],
1186 proxy_user,
1187 ):
1188 attachment_vals.append({
1189 'name': filename_and_decrypted_content[0],
1190 'raw': filename_and_decrypted_content[1],
1191 'type': 'binary',
1192 })
1193
1194 proxy_acks.append(id_transaction)
1195
1196 if attachment_vals:
1197 attachments = self.env['ir.attachment'].with_company(proxy_user.company_id).create(attachment_vals)
1198
1199 # Unwrap the attachments. Potentially each FatturaPA file can get unwrapped into several sub-attachments that
1200 # should each create one invoice.
1201 files_data = self._to_files_data(attachments)
1202 files_data.extend(self._unwrap_attachments(files_data))
1203
1204 moves = self.with_company(proxy_user.company_id).create([{}] * len(files_data))
1205
1206 for move, file_data in zip(moves, files_data):
1207 attachment = file_data['attachment']
1208 attachment.write({'res_model': 'account.move', 'res_id': move.id, 'res_field': 'l10n_it_edi_attachment_file'})
1209
1210 # Post the attachment in the chatter
1211 move.message_post(
1212 body=_("This invoice was retrieved from the SdI."),
1213 attachment_ids=attachment.ids
1214 )
1215
1216 # Extend created moves with the related attachments.
1217 for move, file_data in zip(moves, files_data):
1218 move._extend_with_attachments([file_data], new=True)
1219
1220 return {"retrigger": retrigger, "proxy_acks": proxy_acks}
1221
1222 def _l10n_it_edi_check_and_decrypt_content(self, filename, content, key, proxy_user):
1223 """ Check whether an incoming file from the SdI should be created as a new attachment,
1224 and try to decrypt it.
1225
1226 :param filename: name of the file to be saved.
1227 :param content: encrypted content of the file to be saved.
1228 :param key: key to decrypt the file.
1229 :param proxy_user: the AccountEdiProxyClientUser to use for decrypting the file
1230 """
1231
1232 # Name should be unique per company, the invoice already exists
1233 Attachment = self.env['ir.attachment'].sudo().with_company(proxy_user.company_id)
1234 if Attachment.search_count([
1235 ('name', '=', filename),
1236 ('res_model', '=', 'account.move'),
1237 ('res_field', '=', 'l10n_it_edi_attachment_file'),
1238 ('company_id', '=', proxy_user.company_id.id),
1239 ], limit=1):
1240 _logger.warning('E-invoice already exists: %s', filename)
1241 return False
1242
1243 # Decrypt with the server key
1244 try:
1245 decrypted_content = proxy_user._decrypt_data(content, key)
1246 except Exception as e: # noqa: BLE001
1247 _logger.warning("Cannot decrypt e-invoice: %s, %s", filename, e)
1248 return False
1249
1250 return filename, decrypted_content
1251
1252 def _l10n_it_edi_search_partner(self, company, vat, codice_fiscale, email, destination_code=None):
1253 base_domain = self.env['res.partner']._check_company_domain(company)
1254 for domain in [vat and destination_code
1255 and [('vat', 'ilike', vat), ('l10n_it_pa_index', 'ilike', destination_code)],
1256 vat and [('vat', 'ilike', vat)],
1257 codice_fiscale and [('l10n_it_codice_fiscale', 'in', ('IT' + codice_fiscale, codice_fiscale))],
1258 email and ['|', ('email', '=', email), ('l10n_it_pec_email', '=', email)]]:
1259 if domain and (partner := self.env['res.partner'].search(domain + base_domain, limit=1)):
1260 return partner
1261 return self.env['res.partner']
1262
1263 def _l10n_it_edi_search_tax_for_import(self, company, percentage, extra_domain=None, l10n_it_exempt_reason=None):
1264 """ Returns the VAT, Withholding or Pension Fund tax that suits the conditions given
1265 and matches the percentage found in the XML for the company. """
1266
1267 domain = [
1268 *self.env['account.tax']._check_company_domain(company),
1269 ('amount_type', '=', 'percent'),
1270 ] + (extra_domain or [])
1271
1272 # We suppose we're importing a file that comes in as a customer invoice where the sale tax will be 0%.
1273 # To retrieve the correct purchase tax, we examine the sale tax's l10n_it_exempt_reason.
1274 # We determine whether the l10n_it_exempt_reason is specific to reverse charge.
1275 reversed_tax_tag = self._l10n_it_edi_exempt_reason_tag_mapping().get(l10n_it_exempt_reason, '')
1276 if not reversed_tax_tag:
1277 # Normal VAT taxes have a known percentage and generally have all positive repartition lines
1278 domain += [('amount', '=', percentage), ('l10n_it_exempt_reason', '=', l10n_it_exempt_reason)]
1279 taxes = self.env['account.tax'].search(domain).filtered(
1280 lambda tax: all(rep_line.factor_percent >= 0 for rep_line in tax.invoice_repartition_line_ids))
1281 else:
1282 # In case of reverse charge, the purchase tax has a negative repartition line.
1283 domain += [('invoice_repartition_line_ids.tag_ids.name', '=', reversed_tax_tag.lower())]
1284 taxes = self.env['account.tax'].search(domain, order="amount desc").filtered(
1285 lambda tax: any(rep_line.factor_percent < 0 for rep_line in tax.invoice_repartition_line_ids))
1286
1287 return taxes[0] if taxes else taxes
1288
1289 def _l10n_it_edi_get_extra_info(self, company, document_type, body_tree, incoming=True):
1290 """ This function is meant to collect other information that has to be inserted on the invoice lines by submodules.
1291 :return: extra_info, messages_to_log
1292 """
1293 extra_info = {
1294 'simplified': self.env['account.move']._l10n_it_edi_is_simplified_document_type(document_type),
1295 'type_tax_use_domain': [('type_tax_use', '=', 'purchase' if incoming else 'sale')],
1296 }
1297 message_to_log = []
1298 type_tax_use_domain = extra_info['type_tax_use_domain']
1299 withholding_elements = body_tree.xpath('.//DatiGeneraliDocumento/DatiRitenuta')
1300 withholding_taxes = []
1301 for withholding in (withholding_elements or []):
1302 tipo_ritenuta = withholding.find("TipoRitenuta")
1303 reason = withholding.find("CausalePagamento")
1304 percentage = withholding.find('AliquotaRitenuta')
1305 withholding_type = tipo_ritenuta.text if tipo_ritenuta is not None else "RT02"
1306 withholding_reason = reason.text if reason is not None else "A"
1307 withholding_percentage = -float(percentage.text if percentage is not None else "0.0")
1308
1309 if withholding_percentage == -23.0:
1310 prezzo_totale = 0.0
1311 for line in body_tree.xpath('.//DettaglioLinee'):
1312 prezzo_totale += get_float(line, './/PrezzoTotale')
1313 importo_ritenuta = get_float(withholding, './/ImportoRitenuta')
1314 withholding_percentage = -float_round((importo_ritenuta / prezzo_totale) * 100, 1)
1315
1316 withholding_tax = self._l10n_it_edi_search_tax_for_import(
1317 company,
1318 withholding_percentage,
1319 ([('l10n_it_withholding_type', '=', withholding_type),
1320 ('l10n_it_withholding_reason', '=', withholding_reason)]
1321 + type_tax_use_domain))
1322 if withholding_tax:
1323 withholding_taxes.append(withholding_tax)
1324 else:
1325 message_to_log.append(Markup("%s<br/>%s") % (
1326 _("Withholding tax not found"),
1327 self.env['account.move']._compose_info_message(body_tree, '.'),
1328 ))
1329 extra_info["withholding_taxes"] = withholding_taxes
1330
1331 pension_fund_elements = body_tree.xpath('.//DatiGeneraliDocumento/DatiCassaPrevidenziale')
1332 pension_fund_taxes = {}
1333 for pension_fund in (pension_fund_elements or []):
1334 pension_fund_type = pension_fund.find("TipoCassa")
1335 tax_factor_percent = pension_fund.find("AlCassa")
1336 vat_tax_factor_percent = pension_fund.find("AliquotaIVA")
1337 pension_fund_type = pension_fund_type.text if pension_fund_type is not None else ""
1338 tax_factor_percent = float(tax_factor_percent.text or "0.0")
1339 vat_tax_factor_percent = float(vat_tax_factor_percent.text or "0.0")
1340 pension_fund_tax = self._l10n_it_edi_search_tax_for_import(
1341 company,
1342 tax_factor_percent,
1343 ([('l10n_it_pension_fund_type', '=', pension_fund_type)]
1344 + type_tax_use_domain))
1345 if pension_fund_tax:
1346 pension_fund_taxes[vat_tax_factor_percent] = pension_fund_tax
1347 else:
1348 message_to_log.append(Markup("%s<br/>%s") % (
1349 _("Pension Fund tax not found"),
1350 self.env['account.move']._compose_info_message(body_tree, '.'),
1351 ))
1352 extra_info["pension_fund_taxes"] = pension_fund_taxes
1353
1354 # If the AssoSoftware specs are used on the invoice, then only apply
1355 # the Pension Fund tax to the lines that show an AswCassPre
1356 # additional tag (AltriDatiGestionali)
1357 selector = ".//AltriDatiGestionali/TipoDato[contains(text(), 'AswCassPre')]"
1358 if get_text(body_tree, selector):
1359 extra_info["pension_fund_assosoftware_tags"] = True
1360 return extra_info, message_to_log
1361
1362 def _l10n_it_edi_import_invoice(self, invoice, data, is_new):
1363 """ Decode a FatturaPA attachment into an Odoo move.
1364
1365 :param data: the dictionary with the content to be imported
1366 keys: 'name', 'raw', 'xml_tree', 'import_file_type'
1367 :param is_new: whether the move is newly created or to be updated
1368 :returns: the imported move
1369 """
1370 with self._get_edi_creation() as self:
1371 buyer_seller_info = self._l10n_it_buyer_seller_info()
1372
1373 tree = data['xml_tree']
1374 # Identify the first invoice if there are several in the file.
1375 tree = tree.find('.//FatturaElettronicaBody')
1376 company = self.company_id
1377
1378 # There are 2 cases:
1379 # - cron:
1380 # * Move direction (incoming / outgoing) flexible (no 'default_move_type')
1381 # * I.e. used for import from tax agency
1382 # - "Upload" button (invoices / bills view)
1383 # * Fixed move direction; the button sets the 'default_move_type'
1384 default_move_type = self.env.context.get('default_move_type')
1385 if default_move_type is None:
1386 incoming_possibilities = [True, False]
1387 elif default_move_type in invoice.get_purchase_types(include_receipts=True):
1388 incoming_possibilities = [True]
1389 elif default_move_type in invoice.get_sale_types(include_receipts=True):
1390 incoming_possibilities = [False]
1391 else:
1392 _logger.warning("Cannot handle default_move_type '%s'.", default_move_type)
1393 return
1394
1395 for incoming in incoming_possibilities:
1396 company_role, partner_role = ('buyer', 'seller') if incoming else ('seller', 'buyer')
1397 company_info = buyer_seller_info[company_role]
1398 vat = get_text(tree, company_info['vat_xpath'])
1399 if vat and vat .casefold() in (company.vat or '').casefold():
1400 break
1401 codice_fiscale = get_text(tree, company_info['codice_fiscale_xpath'])
1402 if codice_fiscale and codice_fiscale.casefold() in (company.l10n_it_codice_fiscale or '').casefold():
1403 break
1404 else:
1405 invoice.message_post(body=_("Your company's VAT number and Fiscal Code haven't been found in the buyer and/or seller sections inside the document."))
1406 return
1407
1408 # For unsupported document types, just assume in_invoice, and log that the type is unsupported
1409 document_type = get_text(tree, '//DatiGeneraliDocumento/TipoDocumento')
1410 if l10n_it_document_type := self.env['l10n_it.document.type'].search([('code', '=', document_type)]):
1411 self.l10n_it_document_type = l10n_it_document_type
1412
1413 move_type = self._l10n_it_edi_document_type_mapping().get(document_type, {}).get('import_type')
1414 if not move_type:
1415 move_type = "in_invoice"
1416 _logger.info('Document type not managed: %s. Invoice type is set by default.', document_type)
1417 if not incoming and move_type.startswith('in_'):
1418 move_type = 'out' + move_type[2:]
1419
1420 self.move_type = move_type
1421
1422 # Set the move journal to the preferred/default purchase journal set from the italian EDI settings
1423 if self.move_type in self.get_purchase_types(include_receipts=True) and self.company_id.l10n_it_edi_purchase_journal_id:
1424 self.journal_id = self.company_id.l10n_it_edi_purchase_journal_id
1425
1426 if self.name and self.name != '/':
1427 # the journal might've changed, so we need to recompute the name in case it was set (first entry in journal)
1428 self.name = False
1429 self._compute_name()
1430
1431 # Collect extra info from the XML that may be used by submodules to further put information on the invoice lines
1432 extra_info, message_to_log = self._l10n_it_edi_get_extra_info(company, document_type, tree, incoming=incoming)
1433
1434 # Partner
1435 partner_info = buyer_seller_info[partner_role]
1436 vat = get_text(tree, partner_info['vat_xpath'])
1437 codice_fiscale = get_text(tree, partner_info['codice_fiscale_xpath'])
1438 email = get_text(tree, '//DatiTrasmissione//Email') if partner_info['role'] == 'seller' else ''
1439 destination_code = get_text(tree, "//CodiceDestinatario") if partner_info['role'] == 'buyer' else ''
1440 if partner := self._l10n_it_edi_search_partner(company, vat, codice_fiscale, email, destination_code):
1441 self.partner_id = partner
1442 else:
1443 message = Markup("<br/>").join((
1444 _("Partner not found, useful informations from XML file:"),
1445 self._compose_info_message(tree, partner_info['section_xpath'])
1446 ))
1447 message_to_log.append(message)
1448
1449 # Payment code
1450 if payment_code := get_text(tree, './/DettaglioPagamento[1]/CodicePagamento'):
1451 self.payment_reference = payment_code
1452
1453 # Document Number
1454 if number := get_text(tree, './/DatiGeneraliDocumento//Numero'):
1455 self.ref = number
1456
1457 # Currency
1458 if currency_str := get_text(tree, './/DatiGeneraliDocumento/Divisa'):
1459 currency = self.env.ref('base.%s' % currency_str.upper(), raise_if_not_found=False)
1460 if currency != self.env.company.currency_id and currency.active:
1461 self.currency_id = currency
1462
1463 # Date
1464 if document_date := get_date(tree, './/DatiGeneraliDocumento/Data'):
1465 self.invoice_date = document_date
1466 else:
1467 message_to_log.append(_("Document date invalid in XML file: %s", document_date))
1468
1469 # Stamp Duty
1470 if stamp_duty := get_text(tree, './/DatiGeneraliDocumento/DatiBollo/ImportoBollo'):
1471 self.l10n_it_stamp_duty = float(stamp_duty)
1472
1473 # Comment
1474 for narration in get_text(tree, './/DatiGeneraliDocumento//Causale', many=True):
1475 self.narration = '%s%s<br/>' % (self.narration or '', narration)
1476
1477 # Informations relative to the purchase order, the contract, the agreement,
1478 # the reception phase or invoices previously transmitted
1479 # <2.1.2> - <2.1.6>
1480 for document_type in ['DatiOrdineAcquisto', 'DatiContratto', 'DatiConvenzione', 'DatiRicezione', 'DatiFattureCollegate']:
1481 for element in tree.xpath('.//DatiGenerali/' + document_type):
1482 message = Markup("{} {}<br/>{}").format(document_type, _("from XML file:"), self._compose_info_message(element, '.'))
1483 message_to_log.append(message)
1484
1485 # Dati DDT. <2.1.8>
1486 if elements := tree.xpath('.//DatiGenerali/DatiDDT'):
1487 message = Markup("<br/>").join((
1488 _("Transport informations from XML file:"),
1489 self._compose_info_message(tree, './/DatiGenerali/DatiDDT')
1490 ))
1491 message_to_log.append(message)
1492
1493 # Due date. <2.4.2.5>
1494 if due_date := get_date(tree, './/DatiPagamento/DettaglioPagamento/DataScadenzaPagamento'):
1495 self.invoice_date_due = fields.Date.to_string(due_date)
1496 else:
1497 message_to_log.append(_("Payment due date invalid in XML file: %s", str(due_date)))
1498
1499 # Information related to the purchase order <2.1.2>
1500 if (po_refs := get_text(tree, '//DatiGenerali/DatiOrdineAcquisto/IdDocumento', many=True)):
1501 self.invoice_origin = ", ".join(po_refs)
1502
1503 # Total amount. <2.4.2.6>
1504 if amount_total := sum(float(x) for x in get_text(tree, './/ImportoPagamento', many=True) if x):
1505 message_to_log.append(_("Total amount from the XML File: %s", amount_total))
1506
1507 # l10n_it_payment_method
1508 if payment_method := get_text(data['xml_tree'], '//DatiPagamento/DettaglioPagamento/ModalitaPagamento'):
1509 if payment_method in self.env['account.payment.method.line']._get_l10n_it_payment_method_selection_code():
1510 self.l10n_it_payment_method = payment_method
1511
1512 # Bank account. <2.4.2.13>
1513 if self.move_type not in ('out_invoice', 'in_refund'):
1514 if acc_number := get_text(tree, './/DatiPagamento/DettaglioPagamento/IBAN'):
1515 if self.partner_id and self.partner_id.commercial_partner_id:
1516 bank = self.env['res.partner.bank'].search([
1517 ('acc_number', '=', acc_number),
1518 ('partner_id', '=', self.partner_id.commercial_partner_id.id),
1519 ('company_id', 'in', [self.company_id.id, False])
1520 ], order='company_id', limit=1)
1521 else:
1522 bank = self.env['res.partner.bank'].search([
1523 ('acc_number', '=', acc_number),
1524 ('company_id', 'in', [self.company_id.id, False])
1525 ], order='company_id', limit=1)
1526 if bank:
1527 self.partner_bank_id = bank
1528 else:
1529 message = Markup("<br/>").join((
1530 _("Bank account not found, useful informations from XML file:"),
1531 self._compose_info_message(tree, [
1532 './/DatiPagamento//Beneficiario',
1533 './/DatiPagamento//IstitutoFinanziario',
1534 './/DatiPagamento//IBAN',
1535 './/DatiPagamento//ABI',
1536 './/DatiPagamento//CAB',
1537 './/DatiPagamento//BIC',
1538 './/DatiPagamento//ModalitaPagamento'
1539 ])
1540 ))
1541 message_to_log.append(message)
1542 elif elements := tree.xpath('.//DatiPagamento/DettaglioPagamento'):
1543 message = Markup("<br/>").join((
1544 _("Bank account not found, useful informations from XML file:"),
1545 self._compose_info_message(tree, './/DatiPagamento')
1546 ))
1547 message_to_log.append(message)
1548
1549 # Invoice lines. <2.2.1>
1550 tag_name = './/DettaglioLinee' if not extra_info['simplified'] else './/DatiBeniServizi'
1551 for element in tree.xpath(tag_name):
1552 move_line = self.invoice_line_ids.create({
1553 'move_id': self.id,
1554 'tax_ids': [fields.Command.clear()]})
1555 if move_line:
1556 message_to_log += self._l10n_it_edi_import_line(element, move_line, extra_info)
1557
1558 for element in tree.xpath('.//Allegati'):
1559 raw_name = get_text(element, './/NomeAttachment') or ''
1560 raw_ext = get_text(element, './/FormatoAttachment') or ''
1561 self.l10n_it_edi_attachment_name = f"{raw_name}.{raw_ext}" if raw_ext else raw_name
1562 self.l10n_it_edi_attachment_file = get_text(element, './/Attachment')
1563 self.sudo().message_post(
1564 body=(_("Attachment from XML")),
1565 attachments=[(self.l10n_it_edi_attachment_name, b64decode(self.l10n_it_edi_attachment_file))],
1566 )
1567
1568 global_enasarco_lines = []
1569 for additional_data_element in tree.xpath('//AltriDatiGestionali'):
1570 data_kind = additional_data_element.xpath('./TipoDato')[0].text.lower()
1571 if data_kind == 'cassa-prev':
1572 data_text = additional_data_element.xpath('./RiferimentoTesto')[0].text.lower()
1573 if 'enasarco' in data_text or 'tc07' in data_text:
1574 parent_element = additional_data_element.xpath('..')[0]
1575 price_unit = get_float(parent_element, './PrezzoUnitario')
1576 if price_unit == 0.0:
1577 global_enasarco_lines.append(parent_element)
1578
1579 if len(global_enasarco_lines) == 1:
1580 parent_element = global_enasarco_lines[0]
1581 enasarco_amount = get_float(parent_element, './AltriDatiGestionali/RiferimentoNumero')
1582 price_unit = get_float(parent_element, './PrezzoUnitario')
1583 base_amount = self._get_l10_it_edi_get_taxable_amount_from_summary_data(parent_element.xpath('..')[0])
1584 enasarco_percentage = -self.currency_id.round(enasarco_amount / base_amount * 100) if base_amount else 0.0
1585 type_tax_use_domain = [('type_tax_use', '=', 'purchase' if self.is_outbound(include_receipts=True) else 'sale')]
1586 domain = [('l10n_it_pension_fund_type', '=', 'TC07')] + type_tax_use_domain
1587 if enasarco_tax := self._l10n_it_edi_search_tax_for_import(self.company_id, enasarco_percentage, domain):
1588 to_remove_index = int(get_float(parent_element, './NumeroLinea')) - 1
1589 self.invoice_line_ids[to_remove_index].unlink()
1590 self.invoice_line_ids.tax_ids |= enasarco_tax
1591
1592 for message in message_to_log:
1593 self.sudo().message_post(body=message)
1594 return self
1595
1596 @api.model
1597 def _is_prediction_enabled(self):
1598 return self.env['ir.module.module'].search([('name', '=', 'account_accountant'), ('state', '=', 'installed')])
1599
1600 def _l10n_it_edi_import_line(self, element, move_line, extra_info=None):
1601 extra_info = extra_info or {}
1602 company = move_line.company_id
1603 partner = move_line.partner_id
1604 message_to_log = []
1605 predict_enabled = self._is_prediction_enabled()
1606
1607 # Sequence.
1608 line_elements = element.xpath('.//NumeroLinea')
1609 if line_elements:
1610 move_line.sequence = int(line_elements[0].text)
1611
1612 # Name.
1613 move_line.name = " ".join(get_text(element, './/Descrizione').split())
1614
1615 # Product.
1616 if elements_code := element.xpath('.//CodiceArticolo'):
1617 for element_code in elements_code:
1618 type_code = element_code.xpath('.//CodiceTipo')[0]
1619 code = element_code.xpath('.//CodiceValore')[0]
1620 product = self.env['product.product'].search([('barcode', '=', code.text)])
1621 if (product and type_code.text == 'EAN'):
1622 move_line.product_id = product
1623 break
1624 if partner:
1625 product_supplier = self.env['product.supplierinfo'].search([('partner_id', '=', partner.id), ('product_code', '=', code.text)], limit=2)
1626 if product_supplier and len(product_supplier) == 1 and product_supplier.product_id:
1627 move_line.product_id = product_supplier.product_id
1628 break
1629 if not move_line.product_id:
1630 for element_code in elements_code:
1631 code = element_code.xpath('.//CodiceValore')[0]
1632 product = self.env['product.product'].search([('default_code', '=', code.text)], limit=2)
1633 if product and len(product) == 1:
1634 move_line.product_id = product
1635 break
1636
1637 # If no product is found, try to find a product that may be fitting
1638 if predict_enabled and not move_line.product_id:
1639 fitting_product = move_line._predict_product()
1640 if fitting_product:
1641 name = move_line.name
1642 move_line.product_id = fitting_product
1643 move_line.name = name
1644
1645 if predict_enabled:
1646 # Fitting account for the line
1647 fitting_account = move_line._predict_account()
1648 if fitting_account:
1649 move_line.account_id = fitting_account
1650
1651 # Quantity.
1652 move_line.quantity = float(get_text(element, './/Quantita') or '1')
1653
1654 # Taxes
1655 percentage = None
1656 if not extra_info['simplified']:
1657 percentage = get_float(element, './/AliquotaIVA')
1658 move_line.price_unit = get_float(element, './/PrezzoUnitario')
1659
1660 # This tax is supposed to be 23% but applied to only a portion (50% or 20%) of the base amount
1661 # It's implemented as -11.5% (for 50% base) or -4.6% (for 20% base) instead of -23%
1662 # We need to calculate the actual effective percentage based on the ImponibileImporto/PrezzoTotale ratio
1663 # Example:
1664 # - If base is 50% of total: -23% * 0.5 = -11.5% (actual tax rate)
1665 # - If base is 20% of total: -23% * 0.2 = -4.6% (actual tax rate)
1666 if percentage == -23.0 and (prezzo_totale := get_float(element, './/PrezzoTotale')):
1667 body_tree = element.xpath('//FatturaElettronicaBody')[0]
1668 for riepilogo in body_tree.xpath('.//DatiRiepilogo'):
1669 if get_float(riepilogo, './/AliquotaIVA') == percentage and (imponibile := get_float(riepilogo, './/ImponibileImporto')):
1670 percentage = -float_round(23.0 * (imponibile / prezzo_totale), 1)
1671 break
1672 elif amount := get_float(element, './/Importo'):
1673 percentage = get_float(element, './/Aliquota')
1674 if not percentage and (tax_amount := get_float(element, './/Imposta')):
1675 percentage = round(tax_amount / (amount - tax_amount) * 100)
1676 move_line.price_unit = amount / (1 + percentage / 100)
1677
1678 move_line.tax_ids = [Command.clear()]
1679 if percentage is not None:
1680 l10n_it_exempt_reason = get_text(element, './/Natura').upper() or False
1681 extra_domain = extra_info.get('type_tax_use_domain', [('type_tax_use', '=', 'purchase')])
1682 if move_line.product_id:
1683 extra_domain = list(extra_domain)
1684 tax_scope = 'service' if move_line.product_id.type == 'service' else 'consu'
1685 extra_domain += [('tax_scope', 'in', [tax_scope, False])]
1686 if tax := self._l10n_it_edi_search_tax_for_import(company, percentage, extra_domain, l10n_it_exempt_reason=l10n_it_exempt_reason):
1687 move_line.tax_ids |= tax
1688 else:
1689 message = Markup("<br/>").join((
1690 _("Tax not found for line with description '%s'", move_line.name),
1691 self._compose_info_message(element, '.')
1692 ))
1693 message_to_log.append(message)
1694
1695 # If no taxes were found, try to find taxes that may be fitting
1696 if predict_enabled and not move_line.tax_ids:
1697 fitting_taxes = move_line._predict_taxes()
1698 if fitting_taxes:
1699 move_line.tax_ids = [Command.set(fitting_taxes)]
1700
1701 # Discounts
1702 if (discounts := element.xpath('.//ScontoMaggiorazione')) and not float_is_zero(move_line.price_unit, precision_rounding=move_line.currency_id.rounding):
1703 current_unit_price = move_line.price_unit
1704 # We apply the discounts in the order they are found in the XML.
1705 # The first discount is applied to the unit price, the second to the result of the first, etc.
1706 # If the discount is a percentage, it is applied to the unit price.
1707 # If the discount is an amount, it is subtracted from the unit price.
1708 # If the computed amount is different than the expected one, we log a message.
1709 for discount in discounts:
1710 discount_type = get_text(discount, './/Tipo')
1711 discount_sign = -1 if discount_type == 'MG' else 1
1712 if (discount_percentage := get_float(discount, './/Percentuale')) and not float_is_zero(discount_percentage, precision_rounding=move_line.currency_id.rounding):
1713 current_unit_price *= (100 - discount_sign * discount_percentage) / 100
1714 elif discount_amount := get_float(discount, './/Importo'):
1715 current_unit_price -= discount_sign * discount_amount
1716 expected_total = get_float(element, './/PrezzoTotale')
1717 current_total = current_unit_price * move_line.quantity
1718 if float_compare(expected_total, current_total, precision_rounding=move_line.currency_id.rounding) != 0:
1719 message = Markup("<br/>").join((
1720 _("The amount_total %(current_total)s is different than PrezzoTotale %(expected_total)s for '%(move_name)s'", current_total=current_total, expected_total=expected_total, move_name=move_line.name),
1721 self._compose_info_message(element, '.')
1722 ))
1723 message_to_log.append(message)
1724 discount = 100 - (100 * current_unit_price) / move_line.price_unit
1725 move_line.discount = discount
1726
1727 type_tax_use_domain = extra_info['type_tax_use_domain']
1728
1729 # Eventually apply withholding
1730 for withholding_tax in extra_info.get('withholding_taxes', []):
1731 withholding_tags = element.xpath("Ritenuta")
1732 if withholding_tags and withholding_tags[0].text == 'SI':
1733 move_line.tax_ids |= withholding_tax
1734
1735 if extra_info['simplified']:
1736 return message_to_log
1737
1738 price_subtotal = move_line.price_unit
1739 company = move_line.company_id
1740
1741 # Eventually apply pension_fund
1742 if pension_fund_tax := self._get_pension_fund_tax_for_line(element, extra_info):
1743 move_line.tax_ids |= pension_fund_tax
1744
1745 # Eventually apply ENASARCO
1746 for other_data_element in element.xpath('.//AltriDatiGestionali'):
1747 data_kind_element = other_data_element.xpath("./TipoDato")
1748 text_element = other_data_element.xpath("./RiferimentoTesto")
1749 if not data_kind_element or not text_element:
1750 continue
1751 data_kind, data_text = data_kind_element[0].text.lower(), text_element[0].text.lower()
1752 if data_kind == 'cassa-prev' and ('enasarco' in data_text or 'tc07' in data_text):
1753 number_element = other_data_element.xpath("./RiferimentoNumero")
1754 if not number_element or not price_subtotal:
1755 continue
1756 enasarco_amount = float(number_element[0].text)
1757 enasarco_percentage = -self.env.company.currency_id.round(enasarco_amount / price_subtotal * 100)
1758 enasarco_tax = self._l10n_it_edi_search_tax_for_import(
1759 company,
1760 enasarco_percentage,
1761 [('l10n_it_pension_fund_type', '=', 'TC07')] + type_tax_use_domain)
1762 if enasarco_tax:
1763 move_line.tax_ids |= enasarco_tax
1764 else:
1765 message_to_log.append(Markup("%s<br/>%s") % (
1766 _("Enasarco tax not found for line with description '%s'", move_line.name),
1767 self.env['account.move']._compose_info_message(other_data_element, '.'),
1768 ))
1769
1770 return message_to_log
1771
1772 def _l10n_it_edi_format_errors(self, header, errors):
1773 return Markup('{}<ul class="mb-0">{}</ul>').format(
1774 nl2br_enclose(header, 'span') if header else '',
1775 Markup().join(nl2br_enclose(' '.join(error.split()), 'li') for error in errors)
1776 )
1777
1778 def _compose_info_message(self, tree, tags):
1779 result = ""
1780 for tag in tags if isinstance(tags, list) else [tags]:
1781 for el in tree.xpath(tag):
1782 result += self._l10n_it_edi_format_errors("", [f'{subel.tag}: {subel.text}' for subel in el.iter()])
1783 return result
1784
1785 # -------------------------------------------------------------------------
1786 # EDI: Export
1787 # -------------------------------------------------------------------------
1788
1789 def _l10n_it_edi_export_data_check(self):
1790 """ This function checks the Settings, Company, Partners, Moves involved in the
1791 sending activity and returns an errors dictionary ready for the
1792 actionable_errors widget to display. """
1793
1794 companies = self.mapped("company_id")
1795 companies_partners = companies.mapped("partner_id")
1796 moves_full = self.filtered(lambda m: not m._l10n_it_edi_is_simplified())
1797 moves_simplified = self.filtered(lambda m: m._l10n_it_edi_is_simplified())
1798
1799 full = moves_full.mapped("commercial_partner_id").filtered(lambda p: p not in companies_partners)
1800 simplified = moves_simplified.mapped("commercial_partner_id").filtered(lambda p: p not in companies_partners | full)
1801 representatives = companies.mapped("l10n_it_tax_representative_partner_id").filtered(lambda p: p not in companies_partners | simplified | full)
1802
1803 return {
1804 **companies._l10n_it_edi_export_check(),
1805 **full._l10n_it_edi_export_check(['partner_address_missing']),
1806 **simplified._l10n_it_edi_export_check(['partner_country_missing']),
1807 **(simplified | full)._l10n_it_edi_export_check(['partner_vat_codice_fiscale_missing']),
1808 **representatives._l10n_it_edi_export_check(['partner_vat_missing']),
1809 **self._l10n_it_edi_base_export_check(),
1810 **self._l10n_it_edi_export_taxes_check(),
1811 }
1812
1813 def _l10n_it_edi_base_export_check(self):
1814 def build_error(message, records):
1815 return {
1816 'message': message,
1817 **({
1818 'action_text': _("View invoice(s)"),
1819 'action': records._get_records_action(name=_("Invoice(s) to check")),
1820 } if len(self) > 1 else {})
1821 }
1822
1823 errors = {}
1824 if moves := self.filtered(lambda move: move.l10n_it_edi_is_self_invoice and move._l10n_it_edi_services_or_goods() == 'both'):
1825 errors['l10n_it_edi_move_rc_mixed_product_types'] = build_error(
1826 message=_("Cannot apply Reverse Charge to bills which contains both services and goods."),
1827 records=moves)
1828
1829 if pa_moves := self.filtered(lambda move: move.commercial_partner_id._l10n_it_edi_is_public_administration()):
1830 if moves := pa_moves.filtered(lambda move: not move.l10n_it_origin_document_type):
1831 message = _("Partner(s) belongs to the Public Administration, please fill out Origin Document Type field in the Electronic Invoicing tab.")
1832 errors['move_missing_origin_document'] = build_error(message=message, records=moves)
1833 if moves := pa_moves.filtered(lambda move: move.l10n_it_origin_document_date and move.l10n_it_origin_document_date > fields.Date.today()):
1834 message = _("The Origin Document Date cannot be in the future.")
1835 errors['l10n_it_edi_move_future_origin_document_date'] = build_error(message=message, records=moves)
1836 if pa_moves := self.filtered(lambda move: len(move.commercial_partner_id.l10n_it_pa_index or '') == 7):
1837 if moves := pa_moves.filtered(lambda move: not move.l10n_it_origin_document_type and (move.l10n_it_cig or move.l10n_it_cup)):
1838 message = _("CIG/CUP fields of partner(s) are present, please fill out Origin Document Type field in the Electronic Invoicing tab.")
1839 errors['move_missing_origin_document_field'] = build_error(message=message, records=moves)
1840 return errors
1841
1842 def _l10n_it_edi_export_taxes_check(self):
1843 errors = {}
1844 for kind_code, kind_desc, min_len in (
1845 ('vat', _('VAT'), 1),
1846 ('withholding_no_enasarco', _('Withholding'), 0),
1847 ('pension_fund', _('Pension Fund'), 0),
1848 ):
1849 errors.update(self._l10n_it_edi_check_lines_for_tax_kind(kind_code, kind_desc, min_len))
1850 return errors
1851
1852 def _l10n_it_edi_check_lines_for_tax_kind(self, kind_code, kind_desc, min_len=1):
1853 assert min_len in (0, 1)
1854 if self.invoice_line_ids.filtered(lambda line:
1855 line.display_type == 'product'
1856 and not (min_len <= len(line.tax_ids._l10n_it_filter_kind(kind_code)) <= 1),
1857 ):
1858 return {
1859 f'l10n_it_edi_move_{kind_code}_tax_per_line': {
1860 'message': _(
1861 "Invoices must have %(number)s one %(kind)s tax set per line.",
1862 number=_("exactly") if min_len == 1 else _("at most"),
1863 kind=kind_desc,
1864 ),
1865 **({
1866 'action_text': _("View invoice(s)"),
1867 'action': self._get_records_action(name=_("Check taxes on invoice lines")),
1868 } if len(self) > 1 else {}),
1869 },
1870 }
1871 return {}
1872
1873 def _l10n_it_edi_get_formatters(self):
1874 def format_alphanumeric(text, maxlen=None):
1875 if not text:
1876 return False
1877 text = text.encode('latin-1', 'replace').decode('latin-1')
1878 if maxlen and maxlen > 0:
1879 text = text[:maxlen]
1880 elif maxlen and maxlen < 0:
1881 text = text[maxlen:]
1882 return text
1883
1884 def format_date(dt):
1885 # Format the date in the italian standard.
1886 dt = dt or datetime.now()
1887 return dt.strftime('%Y-%m-%d')
1888
1889 def format_monetary(number, currency):
1890 # Format the monetary values to avoid trailing decimals (e.g. 90.85000000000001).
1891 return float_repr(number, min(2, currency.decimal_places))
1892
1893 def format_float(amount, precision):
1894 if amount is None or amount is False:
1895 return None
1896 # Avoid things like -0.0, see: https://stackoverflow.com/a/11010869
1897 return '%.*f' % (precision, amount if not float_is_zero(amount, precision_digits=precision) else 0.0)
1898
1899 def format_numbers(number):
1900 #format number to str with between 2 and 8 decimals (event if it's .00)
1901 number_splited = str(number).split('.')
1902 if len(number_splited) == 1:
1903 return "%.02f" % number
1904
1905 cents = number_splited[1]
1906 if len(cents) > 8:
1907 return "%.08f" % number
1908 return float_repr(number, max(2, len(cents)))
1909
1910 def format_numbers_two(number):
1911 #format number to str with 2 (event if it's .00)
1912 return "%.02f" % number
1913
1914 def format_phone(number):
1915 if not number:
1916 return False
1917 number = number.replace(' ', '').replace('/', '').replace('.', '')
1918 if len(number) > 4 and len(number) < 13:
1919 return format_alphanumeric(number)
1920 return False
1921
1922 def format_address(street, street2, maxlen=60):
1923 street, street2 = street or '', street2 or ''
1924 if street and len(street) >= maxlen:
1925 street2 = ''
1926 sep = ' ' if street and street2 else ''
1927 return format_alphanumeric(f"{street}{sep}{street2}", maxlen)
1928
1929 return {
1930 'format_date': format_date,
1931 'format_float': format_float,
1932 'format_monetary': format_monetary,
1933 'format_numbers': format_numbers,
1934 'format_numbers_two': format_numbers_two,
1935 'format_phone': format_phone,
1936 'format_alphanumeric': format_alphanumeric,
1937 'format_address': format_address,
1938 }
1939
1940 def _l10n_it_edi_render_xml(self, pdf_values=None):
1941 ''' Create the xml file content.
1942 :return: The XML content as bytestring.
1943 '''
1944 qweb_template_name = (
1945 'l10n_it_edi.account_invoice_it_FatturaPA_export' if not self._l10n_it_edi_is_simplified()
1946 else 'l10n_it_edi.account_invoice_it_simplified_FatturaPA_export')
1947 xml_content = self.env['ir.qweb']._render(qweb_template_name, {
1948 **self._l10n_it_edi_get_values(pdf_values),
1949 **self._l10n_it_edi_get_formatters()})
1950 xml_node = cleanup_xml_node(xml_content, remove_blank_nodes=False)
1951 return etree.tostring(xml_node, xml_declaration=True, encoding='UTF-8')
1952
1953 def _l10n_it_edi_get_attachment_values(self, pdf_values=None):
1954 self.ensure_one()
1955 return {
1956 'name': self._l10n_it_edi_generate_filename(),
1957 'type': 'binary',
1958 'mimetype': 'application/xml',
1959 'description': _('IT EDI e-move: %s', self.move_type),
1960 'company_id': self.company_id.id,
1961 'res_id': self.id,
1962 'res_model': self._name,
1963 'res_field': 'l10n_it_edi_attachment_file',
1964 'raw': self._l10n_it_edi_render_xml(pdf_values=pdf_values),
1965 }
1966
1967 def _l10n_it_edi_generate_filename(self):
1968 '''Returns a name conform to the Fattura pa Specifications:
1969 See ES documentation 2.2
1970 '''
1971 a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
1972 company = self.company_id._l10n_it_get_edi_company()
1973 n = self.env['ir.sequence'].with_company(company).next_by_code('l10n_it_edi.fattura_filename')
1974 if not n:
1975 # The offset is used to avoid conflicts with existing filenames
1976 offset = 62 ** 4
1977 sequence = self.env['ir.sequence'].sudo().create({
1978 'name': 'FatturaPA Filename Sequence',
1979 'code': 'l10n_it_edi.fattura_filename',
1980 'company_id': company.id,
1981 'number_next': offset,
1982 })
1983 n = sequence._next()
1984 # The n is returned as a string, but we require an int
1985 n = int(''.join(filter(lambda c: c.isdecimal(), n)))
1986
1987 progressive_number = ""
1988 while n:
1989 (n, m) = divmod(n, len(a))
1990 progressive_number = a[m] + progressive_number
1991
1992 return '%(country_code)s%(codice)s_%(progressive_number)s.xml' % {
1993 'country_code': company.country_id.code,
1994 'codice': company.partner_id._l10n_it_edi_normalized_codice_fiscale(),
1995 'progressive_number': progressive_number.zfill(5),
1996 }
1997
1998 def _l10n_it_edi_send(self, attachments_vals):
1999 try:
2000 self.lock_for_update()
2001 except LockError:
2002 raise UserError(_('This document is being sent by another process already.')) from None
2003 results = {}
2004
2005 for move in self:
2006 move.l10n_it_edi_header = False
2007 attachment = attachments_vals[move]
2008 filename = attachment['name']
2009 content = b64encode(attachment['raw']).decode()
2010
2011 try:
2012 response = move._l10n_it_edi_upload([{
2013 'filename': filename,
2014 'xml': content,
2015 'destination_code': move.commercial_partner_id.l10n_it_pa_index,
2016 }])[filename]
2017
2018 if 'error' in response:
2019 move.l10n_it_edi_transaction = False
2020 move.l10n_it_edi_state = False
2021
2022 error_code, error_description = response.get('error'), response.get('error_description')
2023 error_message = self._l10n_it_edi_upload_error_message(error_code, error_description)
2024 response['error_message'] = error_message
2025 header = nl2br(_("Error uploading the e-invoice file %(file)s.\n%(error)s", file=filename, error=error_message))
2026 else:
2027 move.l10n_it_edi_state = "processing"
2028 move.l10n_it_edi_transaction = response.get('id_transaction')
2029
2030 if response.get('id_transaction') == 'demo':
2031 message = _("We are simulating the sending of the e-invoice file %s, as we are in demo mode.", filename)
2032 elif response.get('signed'):
2033 message = _("The e-invoice file %s was signed and sent to the SdI for processing.", filename)
2034 else:
2035 message = _("The e-invoice file %s was sent to the SdI for processing.", filename)
2036
2037 header = nl2br(message)
2038 move.sudo().message_post(body=header)
2039
2040 results[filename] = response
2041 move.l10n_it_edi_header = header
2042
2043 except AccountEdiProxyError as e:
2044 move.l10n_it_edi_state = False
2045 error_message = _("Error uploading the e-invoice file %(file)s.\n%(error)s", file=filename, error=e.message)
2046 header = nl2br(error_message)
2047 move.sudo().message_post(body=header)
2048 move.l10n_it_edi_header = header
2049 results[filename] = {'error_message': error_message}
2050
2051 return results
2052
2053 def _l10n_it_edi_upload_error_message(self, error_code, error_description):
2054 """ Translate server errors with the client user's language. """
2055 errors_map = {
2056 'EI01': _('Attached file is empty'),
2057 'EI02': _('Service momentarily unavailable'),
2058 'EI03': _('Unauthorized user'),
2059 'OOGE': _('Error sending file from the Proxy Server to SdI'),
2060 'OOSE': _('Error signing the XML'),
2061 'OOCE': _('Proxy Server configuration error'),
2062 }
2063 error_message = errors_map.get(error_code, _("Unknown error"))
2064 if error_description:
2065 error_message = f'{error_message}: {error_description}'
2066 return error_message
2067
2068 def _l10n_it_edi_upload_single(self, file):
2069 """Upload file to the SdI.
2070 :param file: A dictionary {filename, base64_xml}.
2071 :returns: A dictionary.
2072 * message: Message from fatturapa.
2073 * transactionId: The fatturapa ID of this request.
2074 * error: An eventual error.
2075 """
2076 proxy_user = self.company_id.l10n_it_edi_proxy_user_id
2077 proxy_user.ensure_one()
2078 if proxy_user.edi_mode == 'demo':
2079 return {'id_transaction': 'demo'}
2080 server_url = proxy_user._get_server_url()
2081 return proxy_user._make_request(f'{server_url}/api/l10n_it_edi/2/out/SdiRiceviFile', params={'file': file})
2082
2083 def _l10n_it_edi_upload(self, files):
2084 """Upload files to the SdI.
2085 :param files: A list of dictionary {filename, base64_xml}.
2086 :returns: A dict mapping each input filename to the result returned by _l10n_it_edi_upload_single
2087 """
2088 # This method must be kept as-is — changing its signature would break backward compatibility
2089 # with existing extensions or overrides that depend on it.
2090 return {file['filename']: self._l10n_it_edi_upload_single(file) for file in files or []}
2091
2092 # -------------------------------------------------------------------------
2093 # EDI: Update notifications
2094 # -------------------------------------------------------------------------
2095
2096 def _l10n_it_edi_update_send_state(self):
2097 ''' Check if the current invoices have been processed by the SdI. '''
2098 proxy_user = self.company_id.l10n_it_edi_proxy_user_id
2099 if proxy_user.edi_mode == 'demo':
2100 for move in self:
2101 filename = move.l10n_it_edi_attachment_name or '???'
2102 self._l10n_it_edi_write_send_state(
2103 transformed_notification={
2104 'l10n_it_edi_state': 'forwarded',
2105 'l10n_it_edi_transaction': f'demo_{uuid.uuid4()}',
2106 'send_ack_to_edi_proxy': False,
2107 'date': fields.Date.today(),
2108 'filename': filename},
2109 message=_("The e-invoice file %s has been sent in Demo EDI mode.", filename))
2110 return
2111
2112 server_url = proxy_user._get_server_url()
2113 try:
2114 notifications = proxy_user._make_request(
2115 f'{server_url}/api/l10n_it_edi/1/in/TrasmissioneFatture',
2116 params={'ids_transaction': self.mapped("l10n_it_edi_transaction")})
2117 except AccountEdiProxyError as pe:
2118 raise UserError(_("An error occurred while downloading updates from the Proxy Server: (%(code)s) %(message)s", code=pe.code, message=pe.message)) from pe
2119
2120 for notification in notifications.values():
2121 encrypted_update_content = notification.get('file')
2122 encryption_key = notification.get('key')
2123 if (encrypted_update_content and encryption_key):
2124 notification['xml_content'] = proxy_user._decrypt_data(encrypted_update_content, encryption_key)
2125
2126 acks = {'transaction_ids': [], 'states': []}
2127 for move in self:
2128 notification = notifications[move.l10n_it_edi_transaction]
2129 parsed_notification = move._l10n_it_edi_parse_notification(notification)
2130 transformed_notification = move._l10n_it_edi_transform_notification(parsed_notification)
2131 message = move._l10n_it_edi_get_message(transformed_notification)
2132 move._l10n_it_edi_write_send_state(transformed_notification, message)
2133 if (
2134 transformed_notification.get('send_ack_to_edi_proxy')
2135 and (id_transaction_to_ack := transformed_notification.get('l10n_it_edi_transaction'))
2136 and (ack_state := transformed_notification.get('l10n_it_edi_state'))
2137 ):
2138 acks['transaction_ids'].append(id_transaction_to_ack)
2139 acks['states'].append(ack_state)
2140
2141 if acks:
2142 transaction_ids = acks['transaction_ids']
2143 states = acks['states']
2144 try:
2145 proxy_user._make_request(
2146 f'{server_url}/api/l10n_it_edi/1/ack',
2147 params={'transaction_ids': transaction_ids, 'states': states})
2148 except AccountEdiProxyError as pe:
2149 raise UserError(_("An error occurred while downloading updates from the Proxy Server: (%(code)s) %(message)s", code=pe.code, message=pe.message)) from pe
2150
2151 def _l10n_it_edi_parse_notification(self, notification):
2152 sdi_state = notification.get('state', '')
2153 if not (xml_content := notification.get('xml_content')):
2154 return {'sdi_state': sdi_state}
2155
2156 decrypted_update_content = etree.fromstring(xml_content)
2157 outcome = get_text(decrypted_update_content, './/Esito')
2158 date_arrival = get_datetime(decrypted_update_content, './/DataOraRicezione') or fields.Date.today()
2159 errors = [(
2160 get_text(error_element, '//Codice'),
2161 get_text(error_element, '//Descrizione'),
2162 ) for error_element in decrypted_update_content.xpath('//Errore')]
2163 filename = get_text(decrypted_update_content, './/NomeFile')
2164
2165 return {
2166 'sdi_state': sdi_state,
2167 'errors': errors,
2168 'outcome': outcome,
2169 'date': date_arrival,
2170 'filename': filename,
2171 }
2172
2173 def _l10n_it_edi_transform_notification(self, parsed_notification):
2174 """ Reads the notification XML coming from the EDI Proxy Server
2175 Recovers information about the new state.
2176 Computes whether the EDI Proxy Server is to be acked,
2177 and whether the id_transaction has to be reset.
2178 """
2179 self.ensure_one()
2180 state_map = {
2181 'not_found': False,
2182 'awaiting_outcome': 'processing',
2183 'notificaScarto': 'rejected',
2184 'ricevutaConsegna': 'forwarded',
2185 'forward_attempt': 'forward_attempt',
2186 'notificaMancataConsegna': 'forward_failed',
2187 ('notificaEsito', 'EC01'): 'accepted_by_pa_partner',
2188 ('notificaEsito', 'EC02'): 'rejected_by_pa_partner',
2189 'notificaDecorrenzaTermini': 'accepted_by_pa_partner_after_expiry',
2190 }
2191 sdi_state = parsed_notification['sdi_state']
2192 filename = parsed_notification.get('filename')
2193 errors = parsed_notification.get('errors', [])
2194 date = parsed_notification.get('date', fields.Date.today())
2195 if not filename and self.l10n_it_edi_attachment_name:
2196 filename = self.l10n_it_edi_attachment_name
2197 outcome = parsed_notification.get('outcome', False)
2198 if not outcome:
2199 new_state = state_map.get(sdi_state, False)
2200 else:
2201 new_state = state_map.get((sdi_state, outcome), False)
2202
2203 parsed_notification.update({
2204 'l10n_it_edi_state': new_state,
2205 'l10n_it_edi_transaction': False if new_state in (False, 'rejected') else self.l10n_it_edi_transaction,
2206 'send_ack_to_edi_proxy': bool(new_state),
2207 'date': date,
2208 'errors': errors,
2209 'filename': filename,
2210 })
2211 return parsed_notification
2212
2213 def _l10n_it_edi_write_send_state(self, transformed_notification, message):
2214 """ Update the record with the data coming from the IAP server.
2215 Eventually post the message.
2216 Commit the transaction.
2217 """
2218 self.ensure_one()
2219 old_state = self.l10n_it_edi_state
2220 new_state = transformed_notification['l10n_it_edi_state']
2221 self.write({
2222 'l10n_it_edi_state': new_state,
2223 'l10n_it_edi_transaction': transformed_notification['l10n_it_edi_transaction'],
2224 'l10n_it_edi_header': message or False,
2225 })
2226
2227 if message and old_state != new_state:
2228 self.sudo().message_post(body=message)
2229
2230 if new_state == 'rejected':
2231 self.l10n_it_edi_attachment_file = False
2232
2233 self.env.cr.commit()
2234
2235 def _l10n_it_edi_get_message(self, transformed_notification):
2236 """ The status change will be notified in the chatter of the move.
2237 Compute the message from the notification information coming from the EDI Proxy Server
2238 """
2239 self.ensure_one()
2240 partner = self.commercial_partner_id
2241 partner_name = partner.display_name
2242 filename = transformed_notification['filename']
2243 new_state = transformed_notification['l10n_it_edi_state']
2244 if new_state == 'rejected':
2245 DUPLICATE_MOVE = '00404'
2246 DUPLICATE_FILENAME = '00002'
2247 error_descriptions = []
2248 for error_code, error_description in transformed_notification['errors']:
2249 error_description_copy = error_description
2250 if error_code == DUPLICATE_MOVE:
2251 error_description_copy = _(
2252 "The e-invoice file %(file)s is duplicated.\n"
2253 "Original message from the SdI: %(message)s",
2254 file=filename, message=error_description_copy)
2255 elif error_code == DUPLICATE_FILENAME:
2256 error_description_copy = _(
2257 "The e-invoice filename %(file)s is duplicated. Please check the FatturaPA Filename sequence.\n"
2258 "Original message from the SdI: %(message)s",
2259 file=filename, message=error_description_copy)
2260 error_descriptions.append(error_description_copy)
2261
2262 return self._l10n_it_edi_format_errors(_('The e-invoice has been refused by the SdI.'), error_descriptions)
2263
2264 elif partner._l10n_it_edi_is_public_administration():
2265 pa_specific_map = {
2266 'forwarded': nl2br(_(
2267 "The e-invoice file %(file)s was succesfully sent to the SdI.\n"
2268 "%(partner)s has 15 days to accept or reject it.",
2269 file=filename, partner=partner_name)),
2270 'forward_attempt': nl2br(_(
2271 "The e-invoice file %(file)s can't be forward to %(partner)s (Public Administration) by the SdI at the moment.\n"
2272 "It will try again for 10 days, after which it will be considered accepted, but "
2273 "you will still have to send it by post or e-mail.",
2274 file=filename, partner=partner_name)),
2275 'accepted_by_pa_partner_after_expiry': nl2br(_(
2276 "The e-invoice file %(file)s is succesfully sent to the SdI. The invoice is now considered fiscally relevant.\n"
2277 "The %(partner)s (Public Administration) had 15 days to either accept or refused this document,"
2278 "but since they did not reply, it's now considered accepted.",
2279 file=filename, partner=partner_name)),
2280 'rejected_by_pa_partner': nl2br(_(
2281 "The e-invoice file %(file)s has been refused by %(partner)s (Public Administration).\n"
2282 "You have 5 days from now to issue a full refund for this invoice, "
2283 "then contact the PA partner to create a new one according to their "
2284 "requests and submit it.",
2285 file=filename, partner=partner_name)),
2286 'accepted_by_pa_partner': _(
2287 "The e-invoice file %(file)s has been accepted by %(partner)s (Public Administration), a payment will be issued soon",
2288 file=filename, partner=partner_name),
2289 }
2290 if pa_specific_message := pa_specific_map.get(new_state):
2291 return pa_specific_message
2292
2293 new_state_messages_map = {
2294 False: _(
2295 "The e-invoice file %s has not been found on the EDI Proxy server.", filename),
2296 'processing': nl2br(_(
2297 "The e-invoice file %s was sent to the SdI for validation.\n"
2298 "It is not yet considered accepted, please wait further notifications.",
2299 filename)),
2300 'forwarded': _(
2301 "The e-invoice file %(file)s was accepted and succesfully forwarded it to %(partner)s by the SdI.",
2302 file=filename, partner=partner_name),
2303 'forward_attempt': nl2br(_(
2304 "The e-invoice file %(file)s has been accepted by the SdI.\n"
2305 "The SdI is trying to forward it to %(partner)s.\n"
2306 "It will try for up to 2 days, after which you'll eventually "
2307 "need to send it the invoice to the partner by post or e-mail.",
2308 file=filename, partner=partner_name)),
2309 'forward_failed': nl2br(_(
2310 "The e-invoice file %(file)s couldn't be forwarded to %(partner)s.\n"
2311 "Please remember to send it via post or e-mail.",
2312 file=filename, partner=partner_name))
2313 }
2314 return new_state_messages_map.get(new_state)
2315
2316 # -------------------------------------------------------------------------
2317 # Import
2318 # -------------------------------------------------------------------------
2319
2320 @api.model
2321 def _get_pension_fund_tax_for_line(self, element, extra_info):
2322 """ Apply the pension fund on all lines that have the related AliquotaIVA
2323 If there are AssoSoftware specific AltriDatiGestionale 'AswCassPre'
2324 tags that specify which lines have pension funds, only apply to them.
2325 """
2326 pension_fund_map = extra_info.get('pension_fund_taxes', {})
2327 tax_rate = get_float(element, './/AliquotaIVA')
2328 if not tax_rate:
2329 return None
2330
2331 pension_fund_tax = pension_fund_map.get(tax_rate)
2332 if not pension_fund_tax:
2333 return None
2334
2335 if not extra_info.get('pension_fund_assosoftware_tags'):
2336 return pension_fund_tax
2337
2338 selector = ".//AltriDatiGestionali[TipoDato[contains(text(),'AswCassPre')]]/RiferimentoTesto"
2339 reference_text = get_text(element, selector)
2340 if not reference_text:
2341 return None
2342
2343 if match := re.match(r"(?P<kind>TC\d{2}) \((?P<tax_rate>\d+)%\)", reference_text):
2344 rate = float(match.group("tax_rate"))
2345 match_kind = (match.group("kind") == pension_fund_tax.l10n_it_pension_fund_type)
2346 match_rate = (float_compare(rate, pension_fund_tax.amount, precision_digits=2) == 0)
2347 if match_kind and match_rate:
2348 return pension_fund_tax
2349
2350 return None
2351
2352 @api.model
2353 def _get_l10_it_edi_get_taxable_amount_from_summary_data(self, element):
2354 taxable_amount = 0.0
2355 for summary_data_element in element.xpath('.//DatiRiepilogo'):
2356 taxable_amount += get_float(summary_data_element, './/ImponibileImporto')
2357 return taxable_amount