Debian Codegraph @

addons/l10n_ro_edi/models/account_move.py

raw symbols SCIP
1 import base64
2
3 import requests
4
5 from odoo import _, api, fields, models
6 from odoo.exceptions import UserError
7 from odoo.fields import Domain
8
9 from .utils import (
10 _request_ciusro_download_answer,
11 _request_ciusro_fetch_status,
12 _request_ciusro_send_invoice,
13 _request_ciusro_synchronize_invoices,
14 )
15
16 HOLDING_DAYS = 3 # Arbitrary
17
18
19 class AccountMove(models.Model):
20 _inherit = 'account.move'
21
22 l10n_ro_edi_document_ids = fields.One2many(
23 comodel_name='l10n_ro_edi.document',
24 inverse_name='invoice_id',
25 )
26 l10n_ro_edi_state = fields.Selection(
27 selection=[
28 ('invoice_not_indexed', 'Not indexed'),
29 ('invoice_sent', 'Sent'),
30 ('invoice_refused', 'Refused'),
31 ('invoice_validated', 'Validated'),
32 ],
33 string='E-Factura Status',
34 compute='_compute_l10n_ro_edi_state',
35 store=True,
36 help="""- Not indexed: Invoice index was not received on time due to a server timeout
37 - Sent: Successfully sent to the SPV, waiting for validation
38 - Validated: Sent & validated by the SPV
39 - Refused: Validation error from the SPV
40 """,
41 )
42 l10n_ro_edi_index = fields.Char(string='E-Factura Index', readonly=True, copy=False)
43
44 ################################################################################
45 # Compute Methods
46 ################################################################################
47
48 @api.depends('l10n_ro_edi_document_ids')
49 def _compute_l10n_ro_edi_state(self):
50 self.l10n_ro_edi_state = False
51 for move in self:
52 # set the state of the move depending on the last document created
53 move.l10n_ro_edi_state = move.l10n_ro_edi_document_ids and move.l10n_ro_edi_document_ids.sorted()[0].state
54
55 @api.depends('l10n_ro_edi_state')
56 def _compute_show_reset_to_draft_button(self):
57 """ Prevent user to reset move to draft when there's an
58 active sending document or a successful response has been received """
59 # EXTENDS 'account'
60 super()._compute_show_reset_to_draft_button()
61 for move in self:
62 if move.move_type in ('out_invoice', 'out_refund') and move.l10n_ro_edi_state in ('invoice_sent', 'invoice_validated'):
63 move.show_reset_to_draft_button = False
64
65 ################################################################################
66 # EDI
67 ################################################################################
68
69 def _get_import_file_type(self, file_data):
70 """ Identify OIOUBL files. """
71 # EXTENDS 'account'
72 if (
73 file_data['xml_tree'] is not None
74 and (customization_id := file_data['xml_tree'].findtext('{*}CustomizationID'))
75 and 'CIUS-RO' in customization_id
76 ):
77 return 'account.edi.xml.ubl_ro'
78
79 return super()._get_import_file_type(file_data)
80
81 ################################################################################
82 # Send Logics
83 ################################################################################
84
85 def _l10n_ro_edi_get_pre_send_errors(self, xml_data):
86 """ Compute all possible common errors before sending the XML to the SPV """
87 self.ensure_one()
88 errors = []
89 if self.state != 'posted':
90 errors.append(_('Only posted entries can be sent to SPV.'))
91 if not self.company_id.l10n_ro_edi_access_token:
92 errors.append(_('Romanian access token not found. Please generate or fill it in the settings.'))
93 if not xml_data:
94 errors.append(_('CIUS-RO XML attachment not found.'))
95 if self.l10n_ro_edi_document_ids:
96 errors.append(_('The invoice has already been sent to the SPV.'))
97 return errors
98
99 def _l10n_ro_edi_send_invoice(self, xml_data):
100 """
101 This method send xml_data to the Romanian SPV using the single invoice's (self) data.
102 The invoice's company and move_type will be used to calculate the required params in the send request.
103 The state of the document deletion/creation are as follows:
104
105 - Pre-check any errors from the invoice's pre_send check before sending
106 - Send to E-Factura
107
108 :param xml_data: string of the xml data to be sent
109 :return: the `list` of errors that occured during the sending and processing of data, if any
110 """
111 self.ensure_one()
112 if errors := self._l10n_ro_edi_get_pre_send_errors(xml_data):
113 self.message_post(body=_("The invoice is not ready to be sent: %s", ", ".join(errors)))
114 return errors
115
116 self.env['res.company']._with_locked_records(self)
117 result = _request_ciusro_send_invoice(
118 company=self.company_id,
119 xml_data=xml_data,
120 move_type=self.move_type,
121 is_b2b=self.partner_id.commercial_partner_id.is_company,
122 )
123 if 'error' in result:
124 self.message_post(body=_(
125 "Error when trying to send the e-Factura to the SPV: %s",
126 result['error']
127 ))
128 return [result['error']]
129
130 self.env['l10n_ro_edi.document'].sudo().create({
131 'invoice_id': self.id,
132 'state': 'invoice_sent',
133 'attachment': base64.b64encode(xml_data),
134 })
135 if result['key_loading']:
136 self.l10n_ro_edi_index = result['key_loading']
137 self.message_post(body=_(
138 "The e-Factura has been sent and is now being validated by the SPV with index key: %s",
139 self.l10n_ro_edi_index,
140 ))
141 else:
142 self.l10n_ro_edi_state = 'invoice_not_indexed'
143 self.message_post(body=_(
144 "SPV failed to return with an index on time, synchronize this invoice to recover the index and the status."
145 ))
146
147 if self._can_commit():
148 self.env.cr.commit()
149 return None
150
151 def _l10n_ro_edi_fetch_invoice_sent_documents(self):
152 """
153 This method loops over all invoice with sending document in `self`. For each of them,
154 it pre-checks errors and make a fetch request for the invoice. Then:
155
156 - if no answer is received, it will do nothing on the current invoice
157 - if there is an error during the communication with the server -> log it in the chatter
158 - else (receives `key_download`) -> immediately make a download request and process it:
159 - if there is an error during the communication with the server -> log it in the chatter
160 - if 'nok', then the invoice has been refused by ANAF -> create a refused document
161 - if 'ok', then the invoice has been accepted by ANAF -> create a success document
162 """
163 session = requests.Session()
164 invoices_to_fetch = self.filtered(lambda inv: inv.l10n_ro_edi_state == 'invoice_sent')
165 documents_to_create = []
166 document_ids_to_delete = []
167
168 for invoice in invoices_to_fetch:
169 self.env['res.company']._with_locked_records(invoice)
170 result = _request_ciusro_fetch_status(
171 company=invoice.company_id,
172 key_loading=invoice.l10n_ro_edi_index,
173 session=session,
174 )
175 if not result: # SPV is still processing the XML (no answer yet); do nothing
176 invoice.message_post(body=_("SPV has not finished processing the invoice, try again later."))
177 continue
178
179 if 'error' in result: # Fetch error
180 invoice.message_post(body=_(
181 "Error when trying to fetch the E-Factura status from the SPV: %s",
182 result['error']
183 ))
184 continue
185
186 # SPV finished the validation process and sent us an answer containing: `key_download`` a key
187 # to obtain the signature and, if the invoice is refused, the reason why.
188 download_data = _request_ciusro_download_answer(
189 company=invoice.company_id,
190 key_download=result['key_download'],
191 session=session,
192 )
193 if 'error' in download_data: # Fetch error
194 invoice.message_post(body=_(
195 "Error when trying to download the E-Factura data from the SPV: %s",
196 result['error']
197 ))
198 continue
199
200 document_ids_to_delete += invoice.l10n_ro_edi_document_ids.ids
201
202 document_data = {
203 'invoice_id': invoice.id,
204 'key_download': result['key_download'],
205 'key_signature': download_data['signature']['key_signature'],
206 'key_certificate': download_data['signature']['key_certificate'],
207 'attachment': base64.b64encode(download_data['signature']['attachment_raw']),
208 }
209 if result['state_status'] == 'nok': # Invoice refused
210 error_message = download_data['invoice']['error'].replace('\t', '')
211 invoice.message_post(body=_(
212 "This invoice was refused by the SPV for the following reason: %s",
213 error_message
214 ))
215 document_data.update({
216 'state': 'invoice_refused',
217 'message': error_message,
218 })
219 else: # Invoice accepted
220 invoice.message_post(body=_("This invoice has been accepted by the SPV."))
221 document_data['state'] = 'invoice_validated'
222
223 documents_to_create.append(document_data)
224
225 self.env['l10n_ro_edi.document'].sudo().browse(document_ids_to_delete).unlink()
226 self.env['l10n_ro_edi.document'].sudo().create(documents_to_create)
227 if self._can_commit():
228 self.env.cr.commit()
229
230 @api.model
231 def _l10n_ro_edi_fetch_invoices(self):
232 """ Synchronize bills/invoices from SPV """
233 result = _request_ciusro_synchronize_invoices(
234 company=self.env.company,
235 session=requests.Session(),
236 )
237 if 'error' in result:
238 raise UserError(result['error'])
239
240 if result['sent_invoices_accepted_messages']:
241 self._l10n_ro_edi_process_invoice_accepted_messages(result['sent_invoices_accepted_messages'])
242
243 if result['sent_invoices_refused_messages']:
244 self._l10n_ro_edi_process_invoice_refused_messages(result['sent_invoices_refused_messages'])
245
246 if result['received_bills_messages']:
247 self._l10n_ro_edi_process_bill_messages(result['received_bills_messages'])
248
249 # Non-indexed moves that were not processed after some time have probably been refused by the SPV. Since
250 # there is no way to recover the index for refused invoices, we simply refuse them manually without proper reason.
251 domain = (
252 Domain('company_id', '=', self.env.company.id)
253 & Domain('l10n_ro_edi_index', '=', False)
254 & Domain('l10n_ro_edi_state', '=', 'invoice_not_indexed')
255 )
256 non_indexed_invoices = self.env['account.move'].search(domain)
257
258 document_ids_to_delete = []
259 for invoice in non_indexed_invoices:
260 # At that point, only one sent document should exists on an invoice
261 sent_document = invoice.l10n_ro_edi_document_ids
262
263 if (fields.Datetime.today() - sent_document.create_date).days > HOLDING_DAYS:
264 document_ids_to_delete += invoice.l10n_ro_edi_document_ids.ids
265
266 error_message = _(
267 "The invoice has probably been refused by the SPV. We were unable to recover the reason of the refusal because "
268 "the invoice had not received its index. Duplicate the invoice and attempt to send it again."
269 )
270 invoice.message_post(body=error_message)
271 self.env['l10n_ro_edi.document'].sudo().create({
272 'invoice_id': invoice.id,
273 'state': 'invoice_refused',
274 'message': error_message,
275 })
276
277 self.env['l10n_ro_edi.document'].sudo().browse(document_ids_to_delete).unlink()
278
279 if self._can_commit():
280 self.env.cr.commit()
281
282 @api.model
283 def _l10n_ro_edi_process_invoice_accepted_messages(self, sent_invoices_accepted_messages):
284 ''' Process the validation messages of invoices sent
285
286 It will also attempt to recover the original invoices, that are missing their index,
287 by matching the name returned by the server and the one in the database.
288
289 note: There is an edge case where 2 messages have the same invoice name but different indexes in
290 their data; this could be due to a resequencing of the invoice and/or re-sending of an invoice. In
291 that case coupled with name matching where none of the two invoices received an index, all signatures
292 are added to the invoice; the user will have to manually update/select the correct one.
293
294 For example: 2 invoices in the database
295 - 11 already sent and should have gotten index AA, but did not receive it
296 - 12 not sent
297 Resequence them: 11->12 and 12->11
298 Send new 11 that has not yet been sent, it should have gotten index AB but did not receive it.
299 => In the messages, 2 invoices with name 11 and both index AA and AB.
300 '''
301 invoice_names = {message['answer']['invoice']['name'] for message in sent_invoices_accepted_messages if 'error' not in message['answer']}
302 invoice_indexes = [message['id_solicitare'] for message in sent_invoices_accepted_messages]
303 domain = (
304 Domain('company_id', '=', self.env.company.id)
305 & Domain('move_type', 'in', self.get_sale_types())
306 & (
307 (
308 Domain('l10n_ro_edi_index', 'in', invoice_indexes)
309 & Domain('l10n_ro_edi_state', '=', 'invoice_sent')
310 )
311 | (
312 Domain('name', 'in', list(invoice_names))
313 & Domain('l10n_ro_edi_index', '=', False)
314 & Domain('l10n_ro_edi_state', '=', 'invoice_not_indexed')
315 )
316 )
317 )
318 invoices = self.env['account.move'].search(domain)
319
320 document_ids_to_delete = []
321 index_to_move = {move.l10n_ro_edi_index: move for move in invoices}
322 name_to_move = {move.name: move for move in invoices}
323 for message in sent_invoices_accepted_messages:
324 invoice = index_to_move.get(message['id_solicitare'])
325
326 if not invoice:
327 # The move related to the message does not have an index
328 if 'error' in message['answer'] or not name_to_move.get(message['answer']['invoice']['name']):
329 continue
330
331 # An invoice with the same name has been found
332 invoice = name_to_move.get(message['answer']['invoice']['name'])
333
334 # Update the index of invoices succesfully sent but without SPV indexes due to server
335 # time-out for unknown reasons during the upload
336 invoice.l10n_ro_edi_index = message['id_solicitare']
337 invoice.l10n_ro_edi_state = 'invoice_sent'
338
339 if 'error' in message['answer']:
340 invoice.message_post(body=_(
341 "Error when trying to download the E-Factura data from the SPV: %s",
342 message['answer']['error']
343 ))
344 continue
345
346 # Only delete invoice_sent documents and not all because one invoice can contain several signature due to
347 # the edge case where 2 messages have the same invoice name but different indexes in their data; this could
348 # be due to a resequencing of the invoice and/or re-sending of an invoice. In that case coupled with name
349 # matching where none of the two invoices received an index, all signatures are added to the invoice; the
350 # user will have to manually update/select the correct one.
351 document_ids_to_delete += invoice.l10n_ro_edi_document_ids.filtered(lambda document: document.state == 'invoice_sent').ids
352
353 invoice.message_post(body=_("This invoice has been accepted by the SPV."))
354 self.env['l10n_ro_edi.document'].sudo().create({
355 'invoice_id': invoice.id,
356 'state': 'invoice_validated',
357 'key_download': message['id'],
358 'key_signature': message['answer']['signature']['key_signature'],
359 'key_certificate': message['answer']['signature']['key_certificate'],
360 'attachment': message['answer']['signature']['attachment_raw'],
361 })
362
363 self.env['l10n_ro_edi.document'].sudo().browse(document_ids_to_delete).unlink()
364
365 @api.model
366 def _l10n_ro_edi_process_invoice_refused_messages(self, sent_invoices_refused_messages):
367 ''' Process the refusal messages of invoices sent
368
369 For refused invoices, it is impossible to recover the original invoice from the message content like
370 in `_l10n_ro_edi_process_invoice_accepted_messages` since the message only contains the index and
371 error message (as relevant information).
372 '''
373 refused_invoice_indexes = [message['id_solicitare'] for message in sent_invoices_refused_messages]
374 domain = (
375 Domain('company_id', '=', self.env.company.id)
376 & Domain('move_type', 'in', self.get_sale_types())
377 & Domain('l10n_ro_edi_index', 'in', refused_invoice_indexes)
378 & Domain('l10n_ro_edi_state', '=', 'invoice_sent')
379 )
380 invoices = self.env['account.move'].search(domain)
381 index_to_move = {move.l10n_ro_edi_index: move for move in invoices}
382
383 document_ids_to_delete = []
384 for message in sent_invoices_refused_messages:
385 invoice = index_to_move.get(message['id_solicitare'])
386 if not invoice:
387 continue
388
389 if 'error' in message['answer']:
390 invoice.message_post(body=_(
391 "Error when trying to download the E-Factura data from the SPV: %s",
392 message['answer']['error']
393 ))
394 continue
395
396 document_ids_to_delete += invoice.l10n_ro_edi_document_ids.ids
397
398 error_message = message['answer']['invoice']['error'].replace('\t', '')
399 invoice.message_post(body=_(
400 "This invoice was refused by the SPV for the following reason: %s",
401 error_message
402 ))
403 self.env['l10n_ro_edi.document'].sudo().create({
404 'invoice_id': invoice.id,
405 'state': 'invoice_refused',
406 'message': error_message,
407 'key_download': message['id'],
408 'key_signature': message['answer']['signature']['key_signature'],
409 'key_certificate': message['answer']['signature']['key_certificate'],
410 'attachment': message['answer']['signature']['attachment_raw'],
411 })
412
413 self.env['l10n_ro_edi.document'].sudo().browse(document_ids_to_delete).unlink()
414
415 @api.model
416 def _l10n_ro_edi_process_bill_messages(self, received_bills_messages):
417 ''' Create bill received on the SPV, it it does not already exists.
418 '''
419 # Search potential similar bills: similar bills either:
420 # - have an index that is present in the message data or,
421 # - the same amount and seller VAT, and optionally the same bill date
422 domain = (
423 Domain('company_id', '=', self.env.company.id)
424 & Domain('move_type', 'in', self.get_purchase_types())
425 & (
426 (
427 Domain('l10n_ro_edi_index', '=', False)
428 & Domain('l10n_ro_edi_state', '=', False)
429 & Domain.OR([
430 Domain('amount_total', '=', message['answer']['invoice']['amount_total'])
431 & Domain('commercial_partner_id.vat', '=', message['answer']['invoice']['seller_vat'])
432 & Domain('invoice_date', 'in', [message['answer']['invoice']['date'], False])
433 for message in received_bills_messages
434 if 'error' not in message['answer']
435 ])
436 )
437 | (
438 Domain('l10n_ro_edi_index', 'in', [message['id_solicitare'] for message in received_bills_messages])
439 & Domain('l10n_ro_edi_state', '=', 'invoice_validated')
440 )
441 )
442 )
443 similar_bills = self.env['account.move'].search(domain)
444
445 indexed_similar_bills = similar_bills.filtered('l10n_ro_edi_index').mapped('l10n_ro_edi_index')
446 non_indexed_similar_bills_dict = {
447 (bill.commercial_partner_id.vat, bill.amount_total, bill.invoice_date): bill
448 for bill in similar_bills
449 if not bill.l10n_ro_edi_index
450 }
451
452 for message in received_bills_messages:
453 if 'error' in message['answer']:
454 continue
455
456 if message['id_solicitare'] in indexed_similar_bills:
457 # A bill with the same SPV index was already imported, skip it as we don't want it twice.
458 continue
459
460 # Create new bills if they don't already exist, else update their content
461 bill = non_indexed_similar_bills_dict.get(
462 (message['answer']['invoice']['seller_vat'], float(message['answer']['invoice']['amount_total']), message['answer']['invoice']['date'])
463 )
464 if not bill:
465 bill = non_indexed_similar_bills_dict.get(
466 (message['answer']['invoice']['seller_vat'], float(message['answer']['invoice']['amount_total']), False)
467 )
468 if not bill:
469 bill = self.env['account.move'].create({
470 'company_id': self.env.company.id,
471 'move_type': 'in_invoice',
472 'journal_id': self.env.company.l10n_ro_edi_anaf_imported_inv_journal_id.id,
473 })
474
475 bill.l10n_ro_edi_index = message['id_solicitare']
476
477 self.env['l10n_ro_edi.document'].sudo().create({
478 'invoice_id': bill.id,
479 'state': 'invoice_validated',
480 'key_download': message['id'],
481 'key_signature': message['answer']['signature']['key_signature'],
482 'key_certificate': message['answer']['signature']['key_certificate'],
483 'attachment': base64.b64encode(message['answer']['signature']['attachment_raw']),
484 })
485 xml_attachment_id = self.env['ir.attachment'].sudo().create({
486 'name': f"ciusro_{message['answer']['invoice']['name'].replace('/', '_')}.xml",
487 'raw': message['answer']['invoice']['attachment_raw'],
488 'res_model': 'account.move',
489 'res_id': bill.id,
490 }).id
491 files_data = self._to_files_data(self.env['ir.attachment'].browse(xml_attachment_id))
492 bill._extend_with_attachments(files_data)
493 bill.message_post(body=_("Synchronized with SPV from message %s", message['id']))
494
495 def action_l10n_ro_edi_fetch_invoices(self):
496 self._l10n_ro_edi_fetch_invoices()
497 return {
498 'type': 'ir.actions.client',
499 'tag': 'reload',
500 }