Debian Codegraph @

addons/l10n_es_edi_verifactu/models/verifactu_document.py

raw symbols SCIP
1 from datetime import datetime, timedelta
2 from psycopg2 import OperationalError
3 from pytz import timezone
4 from werkzeug.urls import url_quote_plus, url_encode
5
6 import hashlib
7 import logging
8 import math
9 import requests.exceptions
10 import json
11
12 from odoo import _, api, fields, models
13 from odoo.addons.certificate.tools import CertificateAdapter
14 from odoo.exceptions import UserError
15 from odoo.tools import float_repr, float_round, frozendict, zeep
16
17 import odoo.release
18
19 _logger = logging.getLogger(__name__)
20
21 # Custom patches to perform the WSDL requests.
22 # Avoid failure on servers where the DH key is too small
23 EUSKADI_CIPHERS = "DEFAULT:!DH"
24
25 VERIFACTU_VERSION = "1.0"
26
27 BATCH_LIMIT = 1000
28
29
30 def _sha256(string):
31 hash_string = hashlib.sha256(string.encode('utf-8'))
32 return hash_string.hexdigest().upper()
33
34
35 def _get_zeep_operation(company, operation):
36 """The creation of the zeep client may raise (in case of networking issues)."""
37 if operation not in ('registration', 'registration_xml'):
38 raise NotImplementedError(_("Unsupported `operation` '%s'", operation))
39
40 session = requests.Session()
41
42 info = {}
43
44 def response_hook(resp, *args, **kwargs):
45 info['raw_response'] = resp.text
46
47 session.hooks['response'] = response_hook
48
49 settings = zeep.Settings(forbid_entities=False, strict=False)
50 wsdl = company._l10n_es_edi_verifactu_get_endpoints()['wsdl']
51 client = zeep.Client(
52 wsdl['url'], session=session, settings=settings,
53 operation_timeout=20, timeout=20,
54 )
55
56 if operation == 'registration':
57 # Note: using the "certificate" before creating `client` causes an error during the `client` creation
58 session.cert = company.sudo()._l10n_es_edi_verifactu_get_certificate()
59 session.mount('https://', CertificateAdapter(ciphers=EUSKADI_CIPHERS))
60
61 service = client.bind(wsdl['service'], wsdl['port'])
62 function = service[wsdl[operation]]
63 else:
64 # operation == 'registration_xml'
65 zeep_client = client._Client__obj # get the "real" zeep client from the odoo specific wrapper
66 service = zeep_client.bind(wsdl['service'], wsdl['port'])
67
68 def function(*args, **kwargs):
69 return zeep_client.create_message(service, wsdl['registration'], *args, **kwargs)
70
71 return function, info
72
73
74 class L10nEsEdiVerifactuDocument(models.Model):
75 """Veri*Factu Document
76 It represents a billing record with the necessary data specified by the AEAT.
77 It i.e. ...
78 * stores the data as JSON
79 * handles the sending of the data as XML to the AEAT
80 * stores information extracted from the received response
81
82 The main functions are
83 1. `_create_for_record` to generate Veri*Factu Documents (submission or cancellation):
84 * The documents form a chain in generation order by including a reference to the preceding document.
85 * The function handles the correct chaining.
86 2. `trigger_next_batch` to send all waiting documents (now if possible or via a cron as soon as possible)
87
88 We can not necessarily send the documents directly after generation.
89 This is because the AEAT requires a waiting time between shipments (or reaching 1000 new records to send).
90 The waiting time is usually 60 seconds.
91 In case we cannot send the records directly a cron will be triggered at the next possible time.
92
93 Note that (succesfully generated) Documents can not be deleted.
94 This is since the Documents form a chain (in generation order) by including a reference to the preceding document.
95 The chain also includes documents that are (/ possibly will be) rejected by the AEAT.
96 """
97 _name = 'l10n_es_edi_verifactu.document'
98 _description = "Veri*Factu Document"
99 _order = 'create_date DESC, id DESC'
100
101 company_id = fields.Many2one(
102 string="Company",
103 comodel_name='res.company',
104 required=True,
105 readonly=True,
106 )
107 move_id = fields.Many2one(
108 string="Journal Entry",
109 comodel_name='account.move',
110 readonly=True,
111 )
112 chain_index = fields.Integer(
113 string="Chain Index",
114 copy=False,
115 readonly=True,
116 help="Index in the chain of Veri*Factu Documents. It is only set if the generation was succesful.",
117 )
118 document_type = fields.Selection(
119 string="Document Type",
120 selection=[
121 ('submission', "Submission"),
122 ('cancellation', "Cancellation"),
123 ],
124 readonly=True,
125 required=True,
126 )
127 # Note: Noone has write access of any kind to the model 'verifactu.document' (see ir.model.access.csv)
128 json_attachment_id = fields.Many2one(
129 string="JSON Attachment",
130 comodel_name='ir.attachment',
131 readonly=True,
132 copy=False,
133 )
134 # To use the binary widget in the form view to download the attachment
135 json_attachment_base64 = fields.Binary(
136 string="JSON",
137 related='json_attachment_id.datas',
138 )
139 json_attachment_filename = fields.Char(
140 string="JSON Filename",
141 compute='_compute_json_attachment_filename',
142 )
143 errors = fields.Html(
144 string="Errors",
145 copy=False,
146 readonly=True,
147 )
148 response_csv = fields.Char(
149 string="Response CSV",
150 copy=False,
151 readonly=True,
152 help="The CSV of the response from the tax agency. There may not be one in case all documents of the batch were rejected.",
153 )
154 state = fields.Selection(
155 string="Status",
156 selection=[
157 ('rejected', "Rejected"),
158 ('registered_with_errors', "Registered with Errors"),
159 ('accepted', "Accepted"),
160 ],
161 copy=False,
162 readonly=True,
163 help="""- Rejected: Successfully sent to the AEAT, but it was rejected during validation
164 - Registered with Errors: Registered at the AEAT, but the AEAT has some issues with the sent record
165 - Accepted: Registered by the AEAT without errors""",
166 )
167
168 @api.depends('document_type')
169 def _compute_display_name(self):
170 for document in self:
171 document.display_name = _("Veri*Factu Document %s", document.id)
172
173 @api.depends('chain_index', 'document_type')
174 def _compute_json_attachment_filename(self):
175 for document in self:
176 document_type = 'anulacion' if document.document_type == 'cancellation' else 'alta'
177 name = f"verifactu_registro_{document.chain_index}_{document_type}.json"
178 document.json_attachment_filename = name
179
180 @api.ondelete(at_uninstall=False)
181 def _never_unlink_chained_documents(self):
182 for document in self:
183 if document.chain_index:
184 raise UserError(_("You cannot delete Veri*Factu Documents that are part of the chain of all Veri*Factu Documents."))
185
186 def _get_document_dict(self):
187 self.ensure_one()
188 if not self.json_attachment_id:
189 return {}
190 json_data = self.json_attachment_id.raw
191 return json.loads(json_data)
192
193 def _get_record_identifier(self):
194 if not self:
195 return False
196 return self._extract_record_identifiers(self._get_document_dict())
197
198 @api.model
199 def _extract_record_identifiers(self, document_dict):
200 """Return a dictionary that includes:
201 * the IDFactura fields
202 * the fields used for the fingerprint generation of this document and the next one
203 (The fingerprint of this record is part of the fingerprint generation of the next record)
204 * the fields used for QR code generation
205 * the fields used for ImporteRectificacion (in case of rectification by substitutuion)
206 """
207 cancellation = 'RegistroAnulacion' in document_dict
208 record_type = 'RegistroAnulacion' if cancellation else 'RegistroAlta'
209 record_type_vals = document_dict[record_type]
210 id_factura = record_type_vals['IDFactura']
211
212 identifiers = {
213 'FechaHoraHusoGenRegistro': record_type_vals['FechaHoraHusoGenRegistro'],
214 'Huella': record_type_vals['Huella'],
215 }
216 if cancellation:
217 identifiers.update({
218 'IDEmisorFactura': id_factura['IDEmisorFacturaAnulada'],
219 'NumSerieFactura': id_factura['NumSerieFacturaAnulada'],
220 'FechaExpedicionFactura': id_factura['FechaExpedicionFacturaAnulada'],
221 })
222 else:
223 identifiers.update({
224 **{key: id_factura[key] for key in ['IDEmisorFactura', 'NumSerieFactura', 'FechaExpedicionFactura']},
225 **{key: record_type_vals[key] for key in ['TipoFactura', 'CuotaTotal', 'ImporteTotal']},
226 'FechaOperacion': record_type_vals.get('FechaOperacion'), # optional
227 })
228 return identifiers
229
230 @api.model
231 def _format_errors(self, title, errors):
232 error = {
233 'error_title': title,
234 'errors': errors,
235 }
236 return self.env['account.move.send']._format_error_html(error)
237
238 ####################################################################
239 # Helpers to be used on the records ('account.move' / 'pos.order') #
240 ####################################################################
241
242 @api.model
243 def _get_tax_details(self, base_lines, company, tax_lines=None):
244 AccountTax = self.env['account.tax']
245 tax_details_functions = AccountTax._l10n_es_edi_verifactu_get_tax_details_functions(company)
246 base_line_filter = tax_details_functions['base_line_filter']
247 total_grouping_function = tax_details_functions['total_grouping_function']
248 tax_details_grouping_function = tax_details_functions['tax_details_grouping_function']
249
250 base_lines = [base_line for base_line in base_lines if base_line_filter(base_line)]
251
252 AccountTax._add_tax_details_in_base_lines(base_lines, company)
253 AccountTax._round_base_lines_tax_details(base_lines, company, tax_lines=tax_lines)
254
255 # Totals
256 base_lines_aggregated_values_for_totals = AccountTax._aggregate_base_lines_tax_details(base_lines, total_grouping_function)
257 totals = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values_for_totals)[True]
258
259 # Tax details
260 base_lines_aggregated_values_for_tax_details = AccountTax._aggregate_base_lines_tax_details(base_lines, tax_details_grouping_function)
261 tax_details = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values_for_tax_details)
262
263 return {
264 'base_amount': totals['base_amount'],
265 'tax_amount': totals['tax_amount'],
266 'tax_details': {key: tax_detail for key, tax_detail in tax_details.items() if key},
267 'tax_details_per_record': {
268 frozendict(base_line): {key: tax_detail for key, tax_detail in tax_details.items() if key}
269 for base_line, tax_details in base_lines_aggregated_values_for_tax_details
270 },
271 }
272
273 def _filter_waiting(self):
274 return self.filtered(lambda doc: not doc.state and doc.json_attachment_id)
275
276 def _get_last(self, document_type):
277 return self.filtered(lambda doc: doc.document_type == document_type and doc.json_attachment_id).sorted()[:1]
278
279 def _get_state(self):
280 # Helper method to get the most recent state from a set of documents.
281 # It should only be used on all the documents associated with a move or pos order.
282 last_registered_document = self.filtered(lambda doc: doc.state in ('registered_with_errors', 'accepted')).sorted()[:1]
283 if last_registered_document:
284 cancellation = last_registered_document.document_type == 'cancellation'
285 return 'cancelled' if cancellation else last_registered_document.state
286
287 rejected_document = self.filtered(lambda doc: doc.state == 'rejected')[:1]
288 if rejected_document:
289 return 'rejected'
290
291 return False
292
293 def _get_qr_code_img_url(self):
294 self.ensure_one()
295 record_identifier = self._get_record_identifier()
296 if not record_identifier or self.document_type != 'submission':
297 # We take the values from the record identifier.
298 # And only the 'submission' has all the necessary values ('ImporteTotal').
299 return False
300 # Documentation: "Detalle de las especificaciones técnicas del código «QR» de la factura y de la «URL» del
301 # servicio de cotejo o remisión de información por parte del receptor de la factura"
302 # https://www.agenciatributaria.es/static_files/AEAT_Desarrolladores/EEDD/IVA/VERI-FACTU/DetalleEspecificacTecnCodigoQRfactura.pdf
303 endpoint_url = self.company_id._l10n_es_edi_verifactu_get_endpoints()['QR']
304 url_params = url_encode({
305 'nif': record_identifier['IDEmisorFactura'],
306 'numserie': record_identifier['NumSerieFactura'],
307 'fecha': record_identifier['FechaExpedicionFactura'],
308 'importe': record_identifier['ImporteTotal'],
309 })
310 url = url_quote_plus(f"{endpoint_url}?{url_params}")
311 return f'/report/barcode/?barcode_type=QR&value={url}&barLevel=M&width=180&height=180'
312
313 @api.model
314 def _check_record_values(self, vals):
315 errors = []
316
317 company_NIF = vals['company'].partner_id._l10n_es_edi_verifactu_get_values().get('NIF')
318 if not company_NIF or len(company_NIF) != 9: # NIFType
319 errors.append(_("The NIF '%(company_NIF)s' of the company is not exactly 9 characters long.",
320 company_NIF=company_NIF))
321
322 if not vals['name'] or len(vals['name']) > 60:
323 errors.append(_("The name of the record is not between 1 and 60 characters long: %(name)s.",
324 name=vals['name']))
325
326 if vals['documents'] and vals['documents']._filter_waiting():
327 errors.append(_("We are waiting to send a Veri*Factu record to the AEAT already."))
328
329 verifactu_registered = vals['verifactu_state'] in ('registered_with_errors', 'accepted')
330 # We currently do not support updating registered records (resending).
331 if not vals['cancellation'] and verifactu_registered:
332 errors.append(_("The record is Veri*Factu registered already."))
333 # We currently do not support cancelling records that are not registered or were registered outside odoo.
334 if vals['cancellation'] and not verifactu_registered:
335 errors.append(_("The cancelled record is not Veri*Factu registered (inside Odoo)."))
336
337 certificate = vals['company'].sudo()._l10n_es_edi_verifactu_get_certificate()
338 if not certificate:
339 errors.append(_("There is no certificate configured for Veri*Factu on the company."))
340
341 if not vals['invoice_date']:
342 errors.append(_("The invoice date is missing."))
343
344 if vals['verifactu_move_type'] == 'correction_substitution' and not vals['substituted_document']:
345 errors.append(_("There is no Veri*Factu document for the substituted record."))
346
347 if vals['verifactu_move_type'] == 'correction_substitution' and not vals['substituted_document_reversal_document']:
348 errors.append(_("There is no Veri*Factu document for the reversal of the substituted record."))
349
350 if vals['verifactu_move_type'] in ('correction_incremental', 'reversal_for_substitution') and not vals['refunded_document']:
351 errors.append(_("There is no Veri*Factu document for the refunded record."))
352
353 need_refund_reason = vals['verifactu_move_type'] in ('correction_incremental', 'correction_substitution')
354 if need_refund_reason and not vals['refund_reason']:
355 errors.append(_("The refund reason is not specified."))
356
357 simplified_partner = self.env.ref('l10n_es.partner_simplified', raise_if_not_found=False)
358 partner_specified = vals['partner'] and vals['partner'] != simplified_partner
359 if need_refund_reason and vals['refund_reason'] != 'R5' and vals['is_simplified']:
360 errors.append(_("A refund with Refund Reason %(refund_reason)s is not simplified (it needs a partner).",
361 refund_reason=vals['refund_reason']))
362
363 if vals['verifactu_move_type'] == 'invoice' and not partner_specified and not vals['is_simplified']:
364 errors.append(_("A non-simplified invoice needs a partner."))
365
366 if not vals['l10n_es_applicability']:
367 errors.append(_("Missing Veri*Factu Tax Applicability (Impuesto)."))
368
369 if vals['l10n_es_applicability'] in ('01', '03') and not vals['clave_regimen']:
370 errors.append(_("Missing Veri*Factu Regime Key (ClaveRegimen)."))
371
372 sujeto_tax_types = self.env['account.tax']._l10n_es_get_sujeto_tax_types()
373 ignored_tax_types = ['ignore', 'retencion']
374 supported_tax_types = sujeto_tax_types + ignored_tax_types + ['no_sujeto', 'no_sujeto_loc', 'recargo', 'exento']
375 tax_type_description = self.env['account.tax']._fields['l10n_es_type'].get_description(self.env)
376 if not vals['tax_details']['tax_details']:
377 errors.append(_("There are no taxes set on the invoice"))
378 for key, tax_detail in vals['tax_details']['tax_details'].items():
379 tax_type = key['l10n_es_type']
380 if tax_type not in supported_tax_types:
381 # tax_type in ('no_deducible', 'dua')
382 # The remaining tax types are purchase taxes (for vendor bills).
383 errors.append(_("A tax with value '%(tax_type)s' as %(field)s is not supported.",
384 field=tax_type_description['string'],
385 tax_type=dict(tax_type_description['selection'])[tax_type]))
386 elif tax_type in ('no_sujeto', 'no_sujeto_loc'):
387 tax_percentage = key['amount']
388 tax_amount = tax_detail['tax_amount']
389 if float_round(tax_percentage, precision_digits=2) or float_round(tax_amount, precision_digits=2):
390 errors.append(_("No Sujeto VAT taxes must have 0 amount."))
391 if len(key['recargo_taxes']) > 1:
392 errors.append(_("Only a single recargo tax may be used per \"main\" tax."))
393
394 main_tax_types = self.env['account.tax']._l10n_es_get_main_tax_types()
395 tax_applicabilities = {
396 grouping_key['l10n_es_applicability']
397 for grouping_key in vals['tax_details']['tax_details']
398 if grouping_key['l10n_es_type'] in main_tax_types
399 }
400 if len(tax_applicabilities) > 1:
401 name_map = self.env['account.tax']._l10n_es_edi_verifactu_get_applicability_name_map()
402 errors.append(_("We only allow a single Veri*Factu Tax Applicability (Impuesto) per document: %(applicabilities)s.",
403 applicabilities=', '.join([name_map[t] for t in tax_applicabilities])))
404
405 for record_detail in vals['tax_details']['tax_details_per_record'].values():
406 main_tax_details = [
407 tax_detail for key, tax_detail in record_detail.items()
408 if key['l10n_es_type'] in main_tax_types
409 ]
410 if len(main_tax_details) > 1:
411 errors.append(_("We only allow a single \"main\" tax per line."))
412 break # Giving the errors once should be enough
413
414 return errors
415
416 #####################
417 # Document Creation #
418 #####################
419
420 def _create_for_record(self, record_values):
421 """Create Veri*Factu documents for input `record_values`.
422 Return the created document.
423 The documents are also created in case the JSON generation fails; to inspect the errors.
424 Such documents are deleted in case the JSON generation succeeds for a record at a later time.
425 (In case we succesfully create a JSON we delete all linked documents that failed the JSON creation.)
426 :param list record_values: record values dictionary
427 """
428 document_vals = record_values['document_vals']
429 error_title = _("The Veri*Factu document could not be created")
430
431 if not record_values['errors']:
432 record_values['errors'] = self._check_record_values(record_values)
433
434 if record_values['errors']:
435 document_vals['errors'] = self._format_errors(error_title, record_values['errors'])
436 else:
437 previous_document = record_values['company']._l10n_es_edi_verifactu_get_last_document()
438 render_vals = self._render_vals(
439 record_values, previous_record_identifier=previous_document._get_record_identifier(),
440 )
441 document_dict = {render_vals['record_type']: render_vals[render_vals['record_type']]}
442
443 # We check whether zeep can generate a valid XML (according to the information from the WSDL / XSD)
444 # from the `document_dict`.
445 # Otherwise this may happen at sending. But then the issue may be hard to resolve:
446 # - Each generated document should also be sent to the AEAT.
447 # - Documents must not be altered after generation.
448 # The created XML (`create_message`) is just discarded.
449 create_message = None
450 try:
451 # We only generate the XML; nothing is sent at this point.
452 create_message, _zeep_info = _get_zeep_operation(record_values['company'], 'registration_xml')
453 except (zeep.exceptions.Error, requests.exceptions.RequestException) as error:
454 # The zeep client creation may cause a networking error
455 errors = [_("Networking error: %s", error)]
456 document_vals['errors'] = self._format_errors(error_title, errors)
457 _logger.error("%s\n%s\n%s", error_title, errors[0], json.dumps(document_dict, indent=4))
458
459 if create_message:
460 batch_dict = self.with_company(record_values['company'])._get_batch_dict([document_dict])
461 try:
462 _xml_node = create_message(batch_dict['Cabecera'], batch_dict['RegistroFactura'])
463 except zeep.exceptions.ValidationError as error:
464 errors = [_("Validation error: %s", error)]
465 document_vals['errors'] = self._format_errors(error_title, errors)
466 _logger.error("%s\n%s\n%s", error_title, errors[0], json.dumps(batch_dict, indent=4))
467 except zeep.exceptions.Error as error:
468 errors = [error]
469 document_vals['errors'] = self._format_errors(error_title, errors)
470 _logger.error("%s\n%s\n%s", error_title, errors[0], json.dumps(batch_dict, indent=4))
471
472 if not document_vals.get('errors'):
473 chain_sequence = record_values['company'].sudo()._l10n_es_edi_verifactu_get_chain_sequence()
474 try:
475 document_vals['chain_index'] = chain_sequence.next_by_id()
476 except OperationalError as e:
477 # We chain all the created documents per company in generation order.
478 # (indexed by `chain_index`).
479 # Thus we can not generate multiple documents for the same company at the same time.
480 # Function `next_by_id` effectively locks `company.l10n_es_edi_verifactu_chain_sequence_id`
481 # to prevent different transactions from chaining documents at the same time.
482 errors = [_("Error while chaining the document: %s", e)]
483 document_vals['errors'] = self._format_errors(error_title, errors)
484 _logger.error("%s\n%s\n%s", error_title, errors[0], json.dumps(batch_dict, indent=4))
485
486 document = self.sudo().create(document_vals)
487
488 if document.chain_index:
489 attachment = self.env['ir.attachment'].sudo().create({
490 'raw': json.dumps(document_dict, indent=4).encode(),
491 'name': document.json_attachment_filename,
492 'res_id': document.id,
493 'res_model': document._name,
494 'mimetype': 'application/json',
495 })
496 document.sudo().json_attachment_id = attachment
497 # Remove (previously generated) documents that failed to generate a (valid) JSON
498 record_values['documents'].filtered(lambda rd: not rd.json_attachment_id).sudo().unlink()
499
500 return document
501
502 #################
503 # JSON Creation #
504 #################
505
506 @api.model
507 def _format_date_type(self, date):
508 if not date:
509 return None
510 # Format as 'fecha' type from xsd
511 return date.strftime('%d-%m-%Y')
512
513 @api.model
514 def _round_format_number_2(self, number):
515 # Round and format as number with 2 precision digits
516 # I.e. used for 'ImporteSgn12.2Type' and 'Tipo2.2Type' XSD types.
517 # We do not check / fix the number of digits in front of the decimal separator
518 if number is None:
519 return None
520 rounded = float_round(number, precision_digits=2)
521 return float_repr(rounded, precision_digits=2)
522
523 @api.model
524 def _render_vals(self, vals, previous_record_identifier=None):
525 def remove_None_and_False(value):
526 # Remove `None` and `False` from dictionaries
527 if isinstance(value, dict):
528 return {
529 key: remove_None_and_False(value)
530 for key, value in value.items()
531 if value is not None and value is not False
532 }
533 elif isinstance(value, list):
534 return [remove_None_and_False(v) for v in value]
535 else:
536 return value
537
538 record_type = 'RegistroAnulacion' if vals['cancellation'] else 'RegistroAlta'
539 render_vals = {
540 'company': vals['company'],
541 'record_type': record_type,
542 'record': vals['record'],
543 'cancellation': vals['cancellation'],
544 'vals': vals,
545 'previous_record_identifier': previous_record_identifier,
546 }
547
548 generation_time_string = fields.Datetime.now(timezone('Europe/Madrid')).astimezone(timezone('Europe/Madrid')).isoformat()
549
550 record_type_vals = {
551 'IDVersion': VERIFACTU_VERSION,
552 'FechaHoraHusoGenRegistro': generation_time_string,
553 **self._render_vals_operation(vals),
554 **self._render_vals_previous_submissions(vals),
555 **self._render_vals_monetary_amounts(vals),
556 **self._render_vals_SistemaInformatico(vals),
557 }
558 render_vals[record_type] = remove_None_and_False(record_type_vals)
559
560 self._update_render_vals_with_chaining_info(render_vals)
561
562 return render_vals
563
564 @api.model
565 def _render_vals_operation(self, vals):
566 company_values = vals['company'].partner_id._l10n_es_edi_verifactu_get_values()
567 invoice_date = self._format_date_type(vals['invoice_date'])
568
569 if vals['cancellation']:
570 render_vals = {
571 'IDFactura': {
572 'IDEmisorFacturaAnulada': company_values['NIF'],
573 'NumSerieFacturaAnulada': vals['name'],
574 'FechaExpedicionFacturaAnulada': invoice_date,
575 }
576 }
577 return render_vals
578
579 render_vals = {
580 'NombreRazonEmisor': company_values['NombreRazon'],
581 'IDFactura': {
582 'IDEmisorFactura': company_values['NIF'],
583 'NumSerieFactura': vals['name'],
584 'FechaExpedicionFactura': invoice_date,
585 }
586 }
587
588 rectified_document = vals['refunded_document'] or vals['substituted_document']
589 if vals['verifactu_move_type'] == 'invoice':
590 tipo_rectificativa = None
591 tipo_factura = 'F2' if vals['is_simplified'] else 'F1'
592 delivery_date = self._format_date_type(vals['delivery_date'])
593 fecha_operacion = delivery_date if delivery_date and delivery_date != invoice_date else None
594 elif vals['verifactu_move_type'] == 'reversal_for_substitution':
595 tipo_rectificativa = None
596 tipo_factura = 'F2' if vals['is_simplified'] else 'F1'
597 fecha_operacion = None
598 elif vals['verifactu_move_type'] == 'correction_substitution':
599 tipo_rectificativa = 'S'
600 tipo_factura = vals['refund_reason']
601 rectified = rectified_document._get_record_identifier()
602 fecha_operacion = rectified['FechaOperacion'] or rectified['FechaExpedicionFactura']
603 else:
604 # vals['verifactu_move_type'] == 'correction_incremental':
605 tipo_rectificativa = 'I'
606 tipo_factura = vals['refund_reason']
607 rectified = rectified_document._get_record_identifier()
608 fecha_operacion = rectified['FechaOperacion'] or rectified['FechaExpedicionFactura']
609
610 # Note: Error [1189]
611 # Si TipoFactura es F1 o F3 o R1 o R2 o R3 o R4 el bloque Destinatarios tiene que estar cumplimentado.
612
613 if not vals['is_simplified']:
614 render_vals['Destinatarios'] = {
615 'IDDestinatario': [vals['partner']._l10n_es_edi_verifactu_get_values()]
616 }
617
618 render_vals.update({
619 'TipoFactura': tipo_factura,
620 'TipoRectificativa': tipo_rectificativa, # may be None
621 'FechaOperacion': fecha_operacion,
622 'DescripcionOperacion': vals['description'] or 'manual',
623 })
624
625 if vals['verifactu_move_type'] in ('correction_incremental', 'correction_substitution'):
626 rectified_record_identifier = rectified_document._get_record_identifier()
627 render_vals.update({
628 'FacturasRectificadas': [{
629 'IDFacturaRectificada': {
630 key: rectified_record_identifier[key]
631 for key in ['IDEmisorFactura', 'NumSerieFactura', 'FechaExpedicionFactura']
632 }
633 }],
634 })
635 # [1118] Si la factura es de tipo rectificativa por sustitución el bloque ImporteRectificacion es obligatorio.
636 if vals['verifactu_move_type'] == 'correction_substitution':
637 # We only support substitution if we also send an invoice that cancels out the amounts of the original invoice.
638 # ('Opción 2' in the FAQ under 'ĀæCómo registra el emisor una factura rectificativa por sustitución ā€œSā€?')
639 render_vals.update({
640 'ImporteRectificacion': {
641 'BaseRectificada': self._round_format_number_2(0),
642 'CuotaRectificada': self._round_format_number_2(0),
643 },
644 })
645
646 return render_vals
647
648 @api.model
649 def _render_vals_previous_submissions(self, vals):
650 """
651 See "Sistemas InformÔticos de Facturación y Sistemas VERI*FACTU" Version 1.1.1 - "Validaciones" p. 22 f.
652 https://www.agenciatributaria.es/static_files/AEAT_Desarrolladores/EEDD/IVA/VERI-FACTU/Validaciones_Errores_Veri-Factu.pdf
653 For submissions (ALTA) we do not support any subsanación cases (update of a previously sent invoice).
654 (Instead the user can issue a credit note and possibly a new substituting invoice).
655 With the nomenclature from the Validations document above the following cases are supported (āœ“) / unsupported (āœ—):
656 āœ“ ALTA (new record)
657 āœ“ ALTA POR RECHAZO (new record, previously rejected)
658 āœ— ALTA DE SUBSANACIƓN (update, previously rejected)
659 āœ— ALTA POR RECHAZO DE SUBSANACIƓN (update, previously rejected)
660 āœ— ALTA DE SUBSANACIƓN SIN REGISTRO PREVIO (update, record not known to the AEAT)
661 āœ— ALTA POR RECHAZO DE SUBSANACIƓN SIN REGISTRO PREVIO (update, record not known to the AEAT, previously rejected)
662 āœ“ ANULACIƓN (cancellation)
663 āœ“ ANULACIƓN POR RECHAZO (cancellation, previously rejected)
664 āœ“ ANULACIƓN SIN REGISTRO PREVIO (cancellation, record not known to the AEAT)
665 āœ“ ANULACIƓN POR RECHAZO SIN REGISTRO PREVIO (cancellation, record not known to the AEAT, previously rejected)
666 """
667 render_vals = {}
668 verifactu_registered = vals['verifactu_state'] in ('registered_with_errors', 'accepted')
669
670 if vals['cancellation']:
671 render_vals = {
672 # A cancelled record can e.g. not exist at the AEAT when we switch to Veri*Factu after the original invoice was created
673 'SinRegistroPrevio': 'S' if not verifactu_registered else 'N',
674 'RechazoPrevio': 'S' if vals['rejected_before'] else 'N',
675 }
676 else:
677 render_vals = {
678 'Subsanacion': 'S' if vals['rejected_before'] else 'N',
679 'RechazoPrevio': 'X' if vals['rejected_before'] else None,
680 }
681
682 return render_vals
683
684 @api.model
685 def _render_vals_monetary_amounts(self, vals):
686 # Note: We only support a single verifactu tax applicabilty, clave regimen pair per record.
687 # For moves the clave regime is stored on each move in field `l10n_es_edi_verifactu_clave_regimen`
688 if vals['cancellation']:
689 return {}
690
691 sign = vals['sign']
692 sujeto_tax_types = self.env['account.tax']._l10n_es_get_sujeto_tax_types()
693
694 recargo_tax_details_key = {} # dict (tax_key -> recargo_tax_key)
695 for record_tax_details in vals['tax_details']['tax_details_per_record'].values():
696 main_key = None
697 recargo_key = None
698 # Note: There is only a single (main tax, recargo tax) pair on a single invoice line
699 # (if any; see `_check_record_values`)
700 for key in record_tax_details:
701 if key['recargo_taxes']:
702 main_key = key
703 if key['l10n_es_type'] == 'recargo':
704 recargo_key = key
705 if main_key and recargo_key:
706 break
707 recargo_tax_details_key[main_key] = recargo_key
708
709 detalles = []
710 for key, tax_detail in vals['tax_details']['tax_details'].items():
711 tax_type = key['l10n_es_type']
712 # Tax types 'ignore' and 'retencion' are ignored when generating the `tax_details`
713 # See `filter_to_apply` in function `_l10n_es_edi_verifactu_get_tax_details_functions` on 'account.tax'
714 if tax_type == 'recargo':
715 # Recargo taxes are only used in combination with another tax (a sujeto tax)
716 # They will be handled when processing the remaining taxes
717 continue
718
719 exempt_reason = key['l10n_es_exempt_reason'] # only set if exempt
720
721 tax_percentage = key['amount']
722 base_amount = sign * tax_detail['base_amount']
723 tax_amount = math.copysign(tax_detail['tax_amount'], base_amount)
724
725 calificacion_operacion = None # Reported if not tax-exempt;
726 recargo_equivalencia = {}
727 if tax_type in sujeto_tax_types:
728 calificacion_operacion = 'S2' if tax_type == 'sujeto_isp' else 'S1'
729 if key['recargo_taxes']:
730 recargo_key = recargo_tax_details_key.get(key)
731 recargo_tax_detail = vals['tax_details']['tax_details'][recargo_key]
732 recargo_tax_percentage = recargo_key['amount']
733 recargo_tax_amount = math.copysign(recargo_tax_detail['tax_amount'], base_amount)
734 recargo_equivalencia.update({
735 'tax_percentage': recargo_tax_percentage,
736 'tax_amount': recargo_tax_amount,
737 })
738 elif tax_type in ('no_sujeto', 'no_sujeto_loc'):
739 calificacion_operacion = 'N2' if tax_type == 'no_sujeto_loc' else 'N1'
740 else:
741 # tax_type == 'exento' (see `_check_record_values`)
742 # exempt_reason set already
743 # [1238]
744 # Si la operacion es exenta no se puede informar ninguno de los campos
745 # TipoImpositivo, CuotaRepercutida, TipoRecargoEquivalencia y CuotaRecargoEquivalencia.
746 tax_percentage = None
747 tax_amount = None
748 recargo_percentage = None
749 recargo_amount = None
750
751 recargo_percentage = recargo_equivalencia.get('tax_percentage')
752 recargo_amount = recargo_equivalencia.get('tax_amount')
753
754 # Note on the TipoImpositivo and CuotaRepercutida tags.
755 # In some cases it makes a difference for the validation whether the tags are output with 0
756 # or not at all:
757 # - In the no sujeto cases (calification_operacion in ('N1', 'N2')) we may not include them.
758 # - In the (calification_operacion == S2) case the tags have to be included with value 0.
759 #
760 # See the following errors:
761 # [1198]
762 # Si CalificacionOperacion es S2 TipoImpositivo y CuotaRepercutida deberan tener valor 0.
763 # [1237]
764 # El valor del campo CalificacionOperacion estĆ” informado como N1 o N2 y el impuesto es IVA.
765 # No se puede informar de los campos TipoImpositivo, CuotaRepercutida, TipoRecargoEquivalencia y CuotaRecargoEquivalencia.
766 if calificacion_operacion in ('N1', 'N2') and vals['l10n_es_applicability'] == '01':
767 tax_percentage = None
768 tax_amount = None
769
770 detalle = {
771 'Impuesto': vals['l10n_es_applicability'],
772 'ClaveRegimen': vals['clave_regimen'],
773 'CalificacionOperacion': calificacion_operacion,
774 'OperacionExenta': exempt_reason,
775 'TipoImpositivo': self._round_format_number_2(tax_percentage),
776 'BaseImponibleOimporteNoSujeto': self._round_format_number_2(base_amount),
777 'CuotaRepercutida': self._round_format_number_2(tax_amount),
778 'TipoRecargoEquivalencia': self._round_format_number_2(recargo_percentage),
779 'CuotaRecargoEquivalencia': self._round_format_number_2(recargo_amount),
780 }
781
782 detalles.append(detalle)
783
784 total_amount = sign * (vals['tax_details']['base_amount'] + vals['tax_details']['tax_amount'])
785 tax_amount = sign * (vals['tax_details']['tax_amount'])
786
787 render_vals = {
788 'Macrodato': 'S' if abs(total_amount) >= 100000000 else None,
789 'Desglose': {
790 'DetalleDesglose': detalles
791 },
792 'CuotaTotal': self._round_format_number_2(tax_amount),
793 'ImporteTotal': self._round_format_number_2(total_amount),
794 }
795
796 return render_vals
797
798 @api.model
799 def _get_db_identifier(self):
800 database_uuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
801 return _sha256(database_uuid)
802
803 @api.model
804 def _render_vals_SistemaInformatico(self, vals):
805 spanish_companies_on_db_count = self.env['res.company'].sudo().search_count([
806 ('account_fiscal_country_id.code', '=', 'ES'),
807 ], limit=2)
808
809 # Note: We have to declare (self-certify) that we meet the Veri*Factu spec.
810 # (DECLARACIƓN RESPONSABLE DE SISTEMAS INFORMƁTICOS DE FACTURACIƓN)
811 # The values should match the values given in the declaration.
812 render_vals = {
813 'SistemaInformatico': {
814 'NombreRazon': 'Odoo SA',
815 'IDOtro': {
816 'CodigoPais': 'BE',
817 'IDType': '02', # NIF-IVA
818 'ID': 'BE0477472701',
819 },
820 'NombreSistemaInformatico': 'Odoo',
821 'IdSistemaInformatico': '00', # identifies Odoo the software as product of Odoo the company
822 'Version': odoo.release.version,
823 'NumeroInstalacion': self._get_db_identifier(),
824 'TipoUsoPosibleSoloVerifactu': 'S',
825 'TipoUsoPosibleMultiOT': 'S',
826 'IndicadorMultiplesOT': 'S' if spanish_companies_on_db_count > 1 else 'N',
827 },
828 }
829
830 return render_vals
831
832 @api.model
833 def _update_render_vals_with_chaining_info(self, render_vals):
834 record_type_vals = render_vals[render_vals['record_type']]
835 predecessor = (render_vals['previous_record_identifier'] or {})
836 first_registration = not bool(predecessor)
837
838 if first_registration:
839 encadenamiento = {
840 'PrimerRegistro': 'S',
841 }
842 else:
843 encadenamiento = {
844 'RegistroAnterior': {
845 'IDEmisorFactura': predecessor['IDEmisorFactura'],
846 'NumSerieFactura': predecessor['NumSerieFactura'],
847 'FechaExpedicionFactura': predecessor['FechaExpedicionFactura'],
848 'Huella': predecessor['Huella'],
849 }
850 }
851 # The 'Encadenamiento' info needs to be set already during the `_fingerprint` computation
852 record_type_vals['Encadenamiento'] = encadenamiento
853
854 record_type_vals.update({
855 'TipoHuella': "01", # "01" means SHA-256
856 'Huella': self._fingerprint(render_vals),
857 })
858
859 return render_vals
860
861 @api.model
862 def _fingerprint(self, render_vals):
863 """
864 Documentation: "Detalle de las especificaciones técnicas para generación de la huella o hash de los registros de facturación"
865 https://www.agenciatributaria.es/static_files/AEAT_Desarrolladores/EEDD/IVA/VERI-FACTU/Veri-Factu_especificaciones_huella_hash_registros.pdf
866 """
867 record_type_vals = render_vals[render_vals['record_type']]
868 id_factura = record_type_vals['IDFactura']
869 registro_anterior = record_type_vals['Encadenamiento'].get('RegistroAnterior') # does not exist for the first document
870 record_type_vals_keys = [] if render_vals['cancellation'] else ['TipoFactura', 'CuotaTotal', 'ImporteTotal']
871 fingerprint_values = [
872 *list(id_factura.items()),
873 *[(key, record_type_vals[key]) for key in record_type_vals_keys],
874 ('Huella', registro_anterior['Huella'] if registro_anterior else ''),
875 ('FechaHoraHusoGenRegistro', record_type_vals['FechaHoraHusoGenRegistro']),
876 ]
877 string = "&".join([f"{field}={value.strip()}" for (field, value) in fingerprint_values])
878 return _sha256(string)
879
880 ###########
881 # Sending #
882 ###########
883
884 @api.model
885 def trigger_next_batch(self):
886 """
887 1. Send all waiting documents that we can send
888 2. Trigger the cron again at a later date to send the documents we could not send
889 """
890 unsent_domain = [
891 ('json_attachment_id', '!=', False),
892 ('state', '=', False),
893 ]
894 documents_per_company = self.sudo()._read_group(
895 unsent_domain,
896 groupby=['company_id'],
897 aggregates=['id:recordset'],
898 )
899
900 if not documents_per_company:
901 return
902
903 next_trigger_time = None
904 for company, documents in documents_per_company:
905 # Avoid sending a document twice due to concurrent calls to `trigger_next_batch`.
906 # This should also avoid concurrently sending in general since the set of documents
907 # in both calls should overlap. (Since we always include all previously unsent documents.)
908 try:
909 self.env['res.company']._with_locked_records(documents)
910 except UserError:
911 # We will later make sure that we trigger the cron again
912 continue
913
914 # We sort the `documents` to batch them in the order they were chained
915 documents = documents.sorted('chain_index')
916
917 # Send batches with size BATCH_LIMIT; they are not restricted by the waiting time
918 next_batch = documents[:BATCH_LIMIT]
919 start_index = 0
920 while len(next_batch) == BATCH_LIMIT:
921 next_batch.with_company(company)._send_as_batch()
922 start_index += BATCH_LIMIT
923 next_batch = documents[start_index:start_index + BATCH_LIMIT]
924 # Now: len(next_batch) < BATCH_LIMIT ; we need to respect the waiting time
925
926 if not next_batch:
927 continue
928
929 next_batch_time = company.l10n_es_edi_verifactu_next_batch_time
930 if not next_batch_time or fields.Datetime.now() >= next_batch_time:
931 next_batch.with_company(company)._send_as_batch()
932 else:
933 # Since we have a `next_batch_time` the `next_trigger_time` will be set to a datetime
934 # We set it to the minimum of all the already encountered `next_batch_time`
935 next_trigger_time = min(next_trigger_time or datetime.max, next_batch_time)
936
937 # In case any of the documents were not successfully sent we trigger the cron again in 60s
938 # (or at the next batch time if the 60s is earlier)
939 for company, documents in documents_per_company:
940 unsent_documents = documents.filtered_domain(unsent_domain)
941 next_batch_time = company.l10n_es_edi_verifactu_next_batch_time
942 if unsent_documents:
943 # Trigger in 60s or at the next batch time (except if there is an earlier trigger already)
944 in_60_seconds = fields.Datetime.now() + timedelta(seconds=60)
945 company_next_trigger_time = max(in_60_seconds, next_batch_time or datetime.min)
946 # Set `next_trigger_time` to the minimum of all the already encountered trigger times
947 next_trigger_time = min(next_trigger_time or datetime.max, company_next_trigger_time)
948
949 if next_trigger_time:
950 cron = self.env.ref('l10n_es_edi_verifactu.cron_verifactu_batch', raise_if_not_found=False)
951 if cron:
952 cron._trigger(at=next_trigger_time)
953
954 @api.model
955 def _send_batch(self, batch_dict):
956 info = {
957 'errors': [],
958 'record_info': {},
959 'soap_fault': False,
960 }
961 errors = info['errors']
962 record_info = info['record_info']
963
964 try:
965 register, zeep_info = _get_zeep_operation(self.env.company, 'registration')
966 except (zeep.exceptions.Error, requests.exceptions.RequestException) as error:
967 errors.append(_("Networking error:\n%s", error))
968 return info
969
970 try:
971 res = register(batch_dict['Cabecera'], batch_dict['RegistroFactura'])
972 # `res` is of type 'zeep.client.SerialProxy'
973 except requests.exceptions.SSLError:
974 errors.append(_("The SSL certificate could not be validated."))
975 except zeep.exceptions.TransportError as error:
976 certificate_error = "No autorizado. Se ha producido un error al verificar el certificado presentado"
977 if certificate_error in error.message:
978 errors.append(_("The document could not be sent; the access was denied due to a problem with the certificate."))
979 else:
980 errors.append(_("Networking error while sending the document:\n%s", error))
981 except requests.exceptions.ReadTimeout as error:
982 # The error is only partially translated since we check for this message for the timeout duplicate handling.
983 # (See `_send_as_batch`)
984 error_description = _("Timeout while waiting for the response from the server:\n%s", error)
985 errors.append(f"[Read-Timeout] {error_description}")
986 except requests.exceptions.RequestException as error:
987 errors.append(_("Networking error while sending the document:\n%s", error))
988 except zeep.exceptions.Fault as soapfault:
989 info['soap_fault'] = True
990 errors.append(f"[{soapfault.code}] {soapfault.message}")
991 except zeep.exceptions.XMLSyntaxError as error:
992 _logger.error("raw zeep response:\n%s", zeep_info.get('raw_response'))
993 certificate_error = "The root element found is html"
994 if certificate_error in error.message:
995 errors.append(_("The response of the server had the wrong format (HTML instead of XML). It is most likely a problem with the certificate."))
996 else:
997 errors.append(_("Error while sending the batch document:\n%s", error))
998 except zeep.exceptions.Error as error:
999 _logger.error("raw zeep response:\n%s", zeep_info.get('raw_response'))
1000 errors.append(_("Error while sending the batch document:\n%s", error))
1001
1002 if errors:
1003 return info
1004
1005 info.update({
1006 'response_csv': res['CSV'] if 'CSV' in res else None, # noqa: SIM401 - `res` is of type 'zeep.client.SerialProxy'
1007 'waiting_time_seconds': int(res['TiempoEsperaEnvio']),
1008 })
1009
1010 # EstadoRegistroType
1011 state_map = {
1012 'Incorrecto': 'rejected',
1013 'AceptadoConErrores': 'registered_with_errors',
1014 'Correcto': 'accepted',
1015 }
1016 # EstadoRegistroSFType
1017 duplicate_state_map = {
1018 'AceptadaConErrores': 'registered_with_errors',
1019 'Correcta': 'accepted',
1020 'Anulada': 'cancelled',
1021 }
1022
1023 for response_line in res['RespuestaLinea']:
1024 record_id = response_line['IDFactura']
1025 invoice_issuer = record_id['IDEmisorFactura'].strip()
1026 invoice_name = record_id['NumSerieFactura'].strip()
1027 record_key = str((invoice_issuer, invoice_name))
1028
1029 operation_type = response_line['Operacion']['TipoOperacion']
1030 received_state = response_line['EstadoRegistro']
1031 # In case of a duplicate the response supplies information about the original invoice.
1032 duplicate_info = response_line['RegistroDuplicado']
1033 duplicate = {}
1034 if duplicate_info:
1035 duplicate_state = duplicate_state_map[duplicate_info['EstadoRegistroDuplicado']]
1036 duplicate = {
1037 'state': duplicate_state,
1038 'errors': [],
1039 }
1040 if duplicate_state in ('rejected', 'registered_with_errors'):
1041 error_code = duplicate_info['CodigoErrorRegistro']
1042 error_description = duplicate_info['DescripcionErrorRegistro']
1043 duplicate['errors'].append(f"[{error_code}] {error_description}")
1044
1045 state = state_map[received_state]
1046 errors = []
1047 if state in ('rejected', 'registered_with_errors'):
1048 error_code = response_line['CodigoErrorRegistro']
1049 error_description = response_line['DescripcionErrorRegistro']
1050 errors.append(f"[{error_code}] {error_description}")
1051
1052 record_info[record_key] = {
1053 'state': state,
1054 'cancellation': operation_type == 'Anulacion',
1055 'errors': errors,
1056 'duplicate': duplicate,
1057 }
1058
1059 return info
1060
1061 def _send_as_batch(self):
1062 # Documents in `self` should all belong to `self.env.company`.
1063 # For the cron we specifically set the `self.env.company` on some functions we call.
1064 sender_company = self.env.company
1065
1066 batch_errors = self.with_company(sender_company)._send_as_batch_check()
1067 if batch_errors:
1068 error_title = _("The batch document could not be created")
1069 self.errors = self._format_errors(error_title, batch_errors)
1070 info = {'errors': batch_errors}
1071 return None, info
1072
1073 # When the document is sent more than 240s after its creation the AEAT registers the document only with an error
1074 # See error with code 2004:
1075 # El valor del campo FechaHoraHusoGenRegistro debe ser la fecha actual del sistema de la AEAT,
1076 # admitiƩndose un margen de error de: 240 segundos.
1077 incident = any(document.create_date > fields.Datetime.now() + timedelta(seconds=240) for document in self)
1078
1079 document_dict_list = [document._get_document_dict() for document in self]
1080 batch_dict = self.with_company(sender_company)._get_batch_dict(document_dict_list, incident=incident)
1081
1082 info = self.with_company(sender_company)._send_batch(batch_dict)
1083
1084 batch_failure_info = {}
1085 if info['soap_fault'] or info['errors']:
1086 # Handle SOAP fault or the case that something went wrong while sending or parsing the respone.
1087 batch_failure_info = {
1088 'errors': info['errors'],
1089 'state': 'rejected' if info['soap_fault'] else False
1090 }
1091
1092 # Store the information from the response split over the individual documents
1093 for document, document_dict in zip(self, document_dict_list):
1094 response_info = (
1095 batch_failure_info
1096 or info['record_info'].get(self._extract_record_key(document_dict), None)
1097 or {'errors': [_("We could not find any information about the record in the linked batch document.")]}
1098 )
1099
1100 # In case of a timeout the document may have reached the AEAT but
1101 # we have not received the response. That is why we take the
1102 # duplicate information in case of timeout.
1103 duplicate_info = response_info.get('duplicate', {})
1104 if (not document.state
1105 and duplicate_info
1106 and document.errors
1107 and "[Read-Timeout] " in document.errors):
1108 if document.document_type == 'submission' and duplicate_info['state'] in ('accepted', 'registered_with_errors'):
1109 response_info.update({
1110 'state': duplicate_info['state'],
1111 'errors': duplicate_info['errors'],
1112 })
1113 elif document.document_type == 'cancellation' and duplicate_info['state'] == 'cancelled':
1114 response_info.update({
1115 'state': 'accepted',
1116 'errors': duplicate_info['errors'],
1117 })
1118
1119 # Add some information from the batch level in any case.
1120 response_info.update({
1121 'waiting_time_seconds': info.get('waiting_time_seconds', False),
1122 'response_csv': info.get('response_csv', False),
1123 })
1124
1125 # The errors have to be formatted (as HTML) before storing them on the document
1126 errors_html = False
1127 error_list = response_info.get('errors', [])
1128 if error_list:
1129 error_title = _("Error")
1130 if response_info.get('state', False):
1131 error_title = _("The Veri*Factu document contains the following errors according to the AEAT")
1132 errors_html = self._format_errors(error_title, error_list)
1133 document.errors = errors_html
1134
1135 # All other values can be stored directly on the document
1136 keys = ['response_csv', 'state']
1137 for key in keys:
1138 new_value = response_info.get(key, False)
1139 if new_value or document[key]:
1140 document[key] = new_value
1141
1142 # To avoid losing data we commit after every document
1143 if self.env['account.move']._can_commit():
1144 self.env.cr.commit()
1145
1146 waiting_time_seconds = info.get('waiting_time_seconds')
1147 if waiting_time_seconds:
1148 now = fields.Datetime.to_datetime(fields.Datetime.now())
1149 next_batch_time = now + timedelta(seconds=waiting_time_seconds)
1150 self.env.company.l10n_es_edi_verifactu_next_batch_time = next_batch_time
1151
1152 self._cancel_after_sending(info)
1153
1154 if self.env['account.move']._can_commit():
1155 self.env.cr.commit()
1156
1157 return batch_dict, info
1158
1159 @api.model
1160 def _send_as_batch_check(self):
1161 # The batching / sending may happen after the initial check
1162 errors = []
1163 company = self.env.company # sending company
1164
1165 company_NIF = company.partner_id._l10n_es_edi_verifactu_get_values().get('NIF')
1166 if not company_NIF or len(company_NIF) != 9: # NIFType
1167 errors.append(_("The NIF '%(company_NIF)s' of the company is not exactly 9 characters long.",
1168 company_NIF=company_NIF))
1169
1170 certificate = company.sudo()._l10n_es_edi_verifactu_get_certificate()
1171 if not certificate:
1172 errors.append(_("There is no certificate configured for Veri*Factu on the company."))
1173
1174 if len(self) != len(self._filter_waiting()):
1175 errors.append(_("Some of the documents can not be sent. They were sent already or could not be generated correctly."))
1176
1177 return errors
1178
1179 @api.model
1180 def _get_batch_dict(self, document_dict_list, incident=False):
1181 company = self.env.company
1182 company_values = company.partner_id._l10n_es_edi_verifactu_get_values()
1183
1184 batch_dict = {
1185 "Cabecera": {
1186 "ObligadoEmision": {
1187 "NombreRazon": company_values['NombreRazon'],
1188 "NIF": company_values['NIF'],
1189 },
1190 "RemisionVoluntaria": {
1191 "Incidencia": 'S' if incident else 'N',
1192 },
1193 },
1194 "RegistroFactura": document_dict_list,
1195 }
1196
1197 return batch_dict
1198
1199 @api.model
1200 def _extract_record_key(self, document_dict):
1201 record_identifier = self._extract_record_identifiers(document_dict)
1202 return str((record_identifier['IDEmisorFactura'], record_identifier['NumSerieFactura']))
1203
1204 def _cancel_after_sending(self, info):
1205 # This function should not raise since it may be called "in the middle" of the sending process
1206 for document in self:
1207 invoice = document.move_id
1208 if invoice.l10n_es_edi_verifactu_state == 'cancelled' and invoice.state != 'cancel':
1209 try:
1210 invoice.button_cancel()
1211 except UserError as error:
1212 _logger.error("Error while canceling journal entry %(name)s (id %(record_id)s) after Veri*Factu cancellation:\n%(error)s",
1213 record_id=invoice.id, name=invoice.name, error=error)