Debian Codegraph @

addons/l10n_tr_nilvera_einvoice/models/account_move.py

raw
1 import uuid
2 from dateutil.relativedelta import relativedelta
3 from markupsafe import Markup
4 from urllib.parse import quote, urlencode, urlparse
5
6 from odoo import _, api, fields, models
7 from odoo.exceptions import UserError
8 from odoo.tools import SQL
9 from odoo.addons.l10n_tr_nilvera.const import NILVERA_ERROR_CODE_MESSAGES
10 from odoo.addons.l10n_tr_nilvera.lib.nilvera_client import _get_nilvera_client
11
12 MOVE_TYPE_CATEGORY_MAP = {
13 "out_invoice": {
14 "earchive": "invoices",
15 "einvoice": "sale",
16 },
17 "in_invoice": {
18 "einvoice": "purchase",
19 },
20 }
21
22 CATEGORY_MOVE_TYPE_MAP = {
23 "invoices": "out_invoice",
24 "sale": "out_invoice",
25 "purchase": "in_invoice",
26 }
27
28
29 class AccountMove(models.Model):
30 _name = 'account.move'
31 _inherit = ['account.move']
32
33 l10n_tr_nilvera_uuid = fields.Char(
34 string="Nilvera Document UUID",
35 copy=False,
36 readonly=True,
37 help="Universally unique identifier of the Invoice",
38 )
39
40 l10n_tr_nilvera_send_status = fields.Selection(
41 selection=[
42 ('error', "Error"),
43 ('not_sent', "Not sent"),
44 ('sent', "Sent and waiting response"),
45 ('succeed', "Successful"),
46 ('waiting', "Waiting"),
47 ('unknown', "Unknown"),
48 ],
49 string="Nilvera Status",
50 readonly=True,
51 copy=False,
52 default='not_sent',
53 )
54
55 def _get_import_file_type(self, file_data):
56 """ Identify Nilvera UBL files. """
57 # EXTENDS 'account'
58 if (
59 file_data['xml_tree'] is not None
60 and (customization_id := file_data['xml_tree'].findtext('{*}CustomizationID'))
61 and 'TR1.2' in customization_id
62 ):
63 return 'account.edi.xml.ubl.tr'
64
65 return super()._get_import_file_type(file_data)
66
67 def _l10n_tr_types_to_update_status(self):
68 return list(MOVE_TYPE_CATEGORY_MAP)
69
70 def _l10n_tr_get_document_category(self, invoice_channel):
71 return MOVE_TYPE_CATEGORY_MAP.get(self.move_type, {}).get(invoice_channel)
72
73 def _l10n_tr_get_category_move_type(self, document_category):
74 return CATEGORY_MOVE_TYPE_MAP.get(document_category.lower())
75
76 @api.model
77 def _get_ubl_cii_builder_from_xml_tree(self, tree):
78 customization_id = tree.find('{*}CustomizationID')
79 if customization_id is not None and 'TR1.2' in customization_id.text:
80 return self.env['account.edi.xml.ubl.tr']
81 return super()._get_ubl_cii_builder_from_xml_tree(tree)
82
83 def button_draft(self):
84 # EXTENDS account
85 for move in self.filtered('l10n_tr_nilvera_uuid'):
86 if move.l10n_tr_nilvera_send_status == 'error':
87 move.message_post(body=_("To preserve accounting integrity and comply with legal requirements, invoices cannot be reused once an error occurs. Please create a new invoice to continue."))
88 elif move.l10n_tr_nilvera_send_status != 'not_sent':
89 raise UserError(_("You cannot reset to draft an entry that has been sent to Nilvera."))
90 super().button_draft()
91
92 def _post(self, soft=True):
93 for move in self:
94 if move.l10n_tr_nilvera_send_status == 'error' and move.l10n_tr_nilvera_uuid:
95 raise UserError(_("To preserve accounting integrity and comply with legal requirements, invoices cannot be reused once an error occurs. Please create a new invoice to continue."))
96 if move.country_code == 'TR' and not move.l10n_tr_nilvera_uuid:
97 move.l10n_tr_nilvera_uuid = str(uuid.uuid4())
98 return super()._post(soft=soft)
99
100 def _l10n_tr_nilvera_submit_einvoice(self, xml_file, customer_alias):
101 self._l10n_tr_nilvera_submit_document(
102 xml_file=xml_file,
103 endpoint=f"/einvoice/Send/Xml?{urlencode({'Alias': customer_alias})}",
104 )
105
106 def _l10n_tr_nilvera_submit_earchive(self, xml_file):
107 self._l10n_tr_nilvera_submit_document(
108 xml_file=xml_file,
109 endpoint="/earchive/Send/Xml",
110 )
111
112 def _l10n_tr_nilvera_submit_document(self, xml_file, endpoint, post_series=True):
113 """
114 Submits an e-invoice or e-archive document to Nilvera for processing.
115
116 :param xml_file: The XML file to be submitted.
117 :type xml_file: file-like object
118 :param endpoint: The Nilvera API endpoint for submission.
119 :type endpoint: str
120 :param post_series: Whether to attempt posting the series/sequence to Nilvera if it is missing.
121 Defaults to True. Useful for avoiding an infinite loop.
122 :type post_series: bool
123 :raises UserError: If the API key lacks necessary rights (401 or 403 responses), if the response
124 indicates a client error (4xx), or if a server error occurs (500).
125 :return: None
126 """
127 with _get_nilvera_client(self.env.company) as client:
128 response = client.request(
129 "POST",
130 endpoint,
131 files={'file': (xml_file.name, xml_file, 'application/xml')},
132 handle_response=False,
133 )
134
135 if response.status_code == 200:
136 self.is_move_sent = True
137 self.l10n_tr_nilvera_send_status = 'sent'
138 elif response.status_code in {401, 403}:
139 raise UserError(_("Oops, seems like you're unauthorised to do this. Try another API key with more rights or contact Nilvera."))
140 elif 400 <= response.status_code < 500:
141 error_message, error_codes = self._l10n_tr_nilvera_einvoice_get_error_messages_from_response(response)
142
143 # If the sequence/series is not found on Nilvera, add it then retry.
144 if 3009 in error_codes and post_series:
145 self._l10n_tr_nilvera_post_series(endpoint, client)
146 xml_file.seek(0) # reset stream before retry, as previous POST moved the buffer to the EOF
147 return self._l10n_tr_nilvera_submit_document(xml_file, endpoint, post_series=False)
148 raise UserError(error_message)
149 elif response.status_code == 500:
150 raise UserError(_("Server error from Nilvera, please try again later."))
151
152 self.message_post(body=_("The invoice has been successfully sent to Nilvera."))
153
154 def _l10n_tr_nilvera_post_series(self, endpoint, client):
155 """Post the series to Nilvera based on the endpoint."""
156 path = urlparse(endpoint).path # Remove query params from te endpoint.
157 if path == "/einvoice/Send/Xml":
158 series_endpoint = "/einvoice/Series"
159 elif path == "/earchive/Send/Xml":
160 series_endpoint = "/earchive/Series"
161 else:
162 # Return early if endpoint couldn't be matched.
163 return
164
165 if not self.sequence_prefix:
166 return
167
168 series = self.sequence_prefix.split('/', 1)[0]
169 client.request(
170 "POST",
171 series_endpoint,
172 json={
173 'Name': series,
174 'IsActive': True,
175 'IsDefault': False,
176 },
177 )
178
179 def _l10n_tr_nilvera_get_submitted_document_status(self):
180 for company, invoices in self.grouped("company_id").items():
181 with _get_nilvera_client(company) as client:
182 for invoice in invoices:
183 invoice_channel = invoice.partner_id.l10n_tr_nilvera_customer_status
184 document_category = invoice._l10n_tr_get_document_category(invoice_channel)
185 if not document_category or not invoice_channel:
186 continue
187
188 response = client.request(
189 "GET",
190 f"/{invoice_channel}/{quote(document_category)}/{invoice.l10n_tr_nilvera_uuid}/Status",
191 )
192
193 nilvera_status = response.get('InvoiceStatus', {}).get('Code') or response.get('StatusCode')
194 if nilvera_status in dict(invoice._fields['l10n_tr_nilvera_send_status'].selection):
195 invoice.l10n_tr_nilvera_send_status = nilvera_status
196 if nilvera_status == 'error':
197 invoice.message_post(
198 body=Markup(
199 "%s<br/>%s - %s<br/>"
200 ) % (
201 _("The invoice couldn't be sent to the recipient."),
202 response.get('InvoiceStatus', {}).get('Description') or response.get('StatusDetail'),
203 response.get('InvoiceStatus', {}).get('DetailDescription') or response.get('ReportStatus'),
204 )
205 )
206 else:
207 invoice.message_post(body=_("The invoice status couldn't be retrieved from Nilvera."))
208
209 def _get_nilvera_last_fetch_date(self, invoice_channel, journal_type):
210 """
211 Fetches the last fetched date for Nilvera e-invoice synchronization specific to the
212 current company. If no value exists, it sets a default date of one month prior to
213 the current date, stores it, and returns it.
214 """
215 # A config param is used to be able to store the date in stable. One for einvoice and one for earchive.
216 # Should be removed in master and replaced with two date fields on the company.
217 param_key = f"l10n_tr_nilvera_{invoice_channel}_{journal_type}.last_fetched_date.{self.env.company.id}"
218 last_fetched_date = self.env['ir.config_parameter'].sudo().get_param(param_key)
219 if not last_fetched_date:
220 last_fetched_date = (fields.Date.today() - relativedelta(months=1)).strftime("%Y-%m-%d")
221 self.env['ir.config_parameter'].sudo().set_param(param_key, last_fetched_date)
222 return last_fetched_date
223
224 def _l10n_tr_nilvera_get_documents(self, invoice_channel="einvoice", document_category="Purchase", journal_type="purchase"):
225 with _get_nilvera_client(self.env.company) as client:
226 endpoint = f"/{invoice_channel}/{quote(document_category)}"
227 start_date = self._get_nilvera_last_fetch_date(invoice_channel, journal_type)
228 end_date = fields.Datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
229 page = 1
230
231 # We filter documents by their CreatedDate on Nilvera, which represents when the document was created on
232 # their platform. This ensures we always fetch the most recently uploaded documents, regardless of their
233 # actual invoicing date (which might be much older).
234 # The sorting allows us to resume from the last successfully fetched document in case an error interrupts
235 # the batch fetching process.
236 params = {
237 'StatusCode': ['succeed'],
238 'StartDate': start_date,
239 'EndDate': end_date,
240 'DateFilterType': 'CreatedDate',
241 'SortColumn': 'CreationDateTime',
242 'SortType': 'ASC',
243 }
244 response = client.request("GET", endpoint, params={**params, "Page": page})
245 total_pages = response.get("TotalPages")
246 if not total_pages:
247 return
248
249 moves = self.env['account.move']
250 journal = self._l10n_tr_get_nilvera_invoice_journal(journal_type)
251 date_param_key = f"l10n_tr_nilvera_{invoice_channel}_{journal_type}.last_fetched_date.{self.env.company.id}"
252 while page <= total_pages:
253 # Reuse first response, fetch subsequent pages.
254 if page > 1:
255 response = client.request("GET", endpoint, params={**params, "Page": page})
256
257 uuid_to_created_date = {
258 content.get('UUID'): content.get('CreatedDate')
259 for content in response.get('Content')
260 }
261 existing_document_uuids = {
262 rec['l10n_tr_nilvera_uuid'] for rec in self.env['account.move'].search_read(
263 [('l10n_tr_nilvera_uuid', 'in', list(uuid_to_created_date))],
264 ['l10n_tr_nilvera_uuid'],
265 )
266 }
267 for document_uuid, created_date in uuid_to_created_date.items():
268 # Skip invoices that have already been downloaded.
269 if document_uuid in existing_document_uuids:
270 continue
271 move = self._l10n_tr_nilvera_get_invoice_from_uuid(client, journal, document_uuid, document_category, invoice_channel)
272 self._l10n_tr_nilvera_add_pdf_to_invoice(client, move, document_uuid, document_category, invoice_channel)
273 moves |= move
274 # Update the last fetched date.
275 self.env['ir.config_parameter'].sudo().set_param(date_param_key, created_date)
276 self.env.cr.commit()
277 page += 1
278 journal._notify_einvoices_received(moves)
279
280 def _l10n_tr_get_nilvera_invoice_journal(self, journal_type):
281 journal = self._l10n_tr_get_document_category_default_journal(journal_type)
282 if not journal:
283 journal = self.env['account.journal'].search([
284 *self.env['account.journal']._check_company_domain(self.env.company),
285 ('type', '=', f'{journal_type}'),
286 ], limit=1)
287 return journal
288
289 def _l10n_tr_get_document_category_default_journal(self, journal_type):
290 if journal_type == "purchase":
291 return self.env.company.l10n_tr_nilvera_purchase_journal_id
292 return None
293
294 @api.deprecated("Deprecated since 19.0, logic moved to _l10n_tr_nilvera_get_documents")
295 def _l10n_tr_build_document_uuids_list(self, response):
296 contents = response.get("Content", [])
297 document_uuids = [content.get("UUID") for content in contents if content.get("UUID")]
298 # Should be unique per invoice so we get the records with the invoice to use the records
299 document_uuids_records = dict(self.env["account.move"]._read_group([("l10n_tr_nilvera_uuid", "in", document_uuids)], groupby=["l10n_tr_nilvera_uuid", "id"]))
300 document_uuids_references = {
301 content["UUID"]: content["InvoiceNumber"]
302 for content in contents
303 if content.get("UUID") and content.get("InvoiceNumber")
304 }
305
306 return document_uuids, document_uuids_records, document_uuids_references
307
308 def _l10n_tr_nilvera_get_invoice_from_uuid(self, client, journal, document_uuid, document_category="Purchase", invoice_channel="einvoice"):
309 response = client.request(
310 "GET",
311 f"/{invoice_channel}/{quote(document_category)}/{quote(document_uuid)}/xml",
312 params={"StatusCode": ["succeed"]},
313 )
314
315 attachment_vals = {
316 'name': 'attachment.xml',
317 'raw': response,
318 'type': 'binary',
319 'mimetype': 'application/xml',
320 }
321
322 attachment = self.env['ir.attachment'].create(attachment_vals)
323 move_type = self._l10n_tr_get_category_move_type(document_category)
324 try:
325 move = journal.with_context(
326 default_move_type=move_type,
327 default_l10n_tr_nilvera_uuid=document_uuid,
328 default_message_main_attachment_id=attachment.id,
329 default_l10n_tr_nilvera_send_status='succeed',
330 )._create_document_from_attachment(attachment.id)
331
332 # If move creation was successful, update the attachment name with the bill reference.
333 if move.ref:
334 attachment.name = f'{move.ref}.xml'
335
336 move._message_log(body=_("Nilvera document has been received successfully"))
337 except Exception: # noqa: BLE001
338 # If the invoice creation fails, create an empty invoice with the attachment. The PDF will be
339 # added in a later step as well. Nilvera only returns uuid of the successful attachments.
340 move = self.env['account.move'].create({
341 'move_type': move_type,
342 'company_id': self.env.company.id,
343 'l10n_tr_nilvera_uuid': document_uuid,
344 'l10n_tr_nilvera_send_status': 'succeed',
345 'message_main_attachment_id': attachment.id,
346 })
347 attachment.write({
348 'res_model': 'account.move',
349 'res_id': move.id,
350 })
351
352 return move
353
354 def _l10n_tr_nilvera_add_pdf_to_invoice(self, client, invoice, document_uuid, document_category="Purchase", invoice_channel="einvoice"):
355 response = client.request(
356 "GET",
357 f"/{invoice_channel}/{quote(document_category)}/{quote(document_uuid)}/pdf",
358 )
359
360 filename = f'{invoice.ref}.pdf' if invoice.ref else invoice._get_invoice_nilvera_pdf_report_filename()
361
362 attachment = self.env['ir.attachment'].create({
363 'name': filename,
364 'res_id': invoice.id,
365 'res_model': 'account.move',
366 'datas': response,
367 'type': 'binary',
368 'mimetype': 'application/pdf',
369 })
370 # The created attachement coming form Nilvera should be the main attachment
371 invoice.message_main_attachment_id = attachment
372 invoice.with_context(no_new_invoice=True).message_post(attachment_ids=attachment.ids)
373
374 def l10n_tr_nilvera_get_pdf(self):
375 with _get_nilvera_client(self.env.company) as client:
376 for invoice in self:
377 if (
378 invoice.l10n_tr_nilvera_customer_status not in {'einvoice', 'earchive'}
379 or invoice.message_main_attachment_id.id != invoice.invoice_pdf_report_id.id
380 or invoice.l10n_tr_nilvera_send_status != 'succeed'
381 ):
382 continue
383 self._l10n_tr_nilvera_add_pdf_to_invoice(
384 client,
385 invoice,
386 invoice.l10n_tr_nilvera_uuid,
387 document_category="Sale",
388 invoice_channel=invoice.l10n_tr_nilvera_customer_status,
389 )
390
391 def _l10n_tr_nilvera_einvoice_get_error_messages_from_response(self, response):
392 msg = ""
393 error_codes = []
394
395 response_json = response.json()
396 if errors := response_json.get('Errors'):
397 msg += _("The invoice couldn't be sent due to the following errors:\n")
398
399 for error in errors:
400 code = error.get('Code')
401 description = NILVERA_ERROR_CODE_MESSAGES.get(code, error.get('Description'))
402 msg += "\n%s - %s:\n%s\n" % (code, description, error.get('Detail'))
403 error_codes.append(code)
404
405 return msg, error_codes
406
407 def _l10n_tr_nilvera_einvoice_check_invalid_subscription_dates(self):
408 if 'deferred_start_date' not in self.invoice_line_ids._fields:
409 return False
410
411 # Ensure that either no lines have the start and end dates or all lines have the same start and end dates.
412 lines_to_check = self.invoice_line_ids.filtered(lambda line: line.display_type == 'product')
413 if not (subscription_lines := lines_to_check.filtered('deferred_start_date')):
414 return False
415
416 return len(subscription_lines) != len(lines_to_check) or len(set(subscription_lines.mapped(
417 lambda aml: (aml.deferred_start_date, aml.deferred_end_date))
418 )) > 1
419
420 def _l10n_tr_nilvera_einvoice_check_negative_lines(self):
421 return any(
422 line.display_type not in {'line_note', 'line_section'}
423 and (line.quantity < 0 or line.price_unit < 0)
424 for line in self.invoice_line_ids
425 )
426
427 def _get_partner_l10n_tr_nilvera_customer_alias_name(self):
428 # Allows overriding the default customer alias with a custom one.
429 self.ensure_one()
430 return self.partner_id.l10n_tr_nilvera_customer_alias_id.name
431
432 def _get_invoice_nilvera_pdf_report_filename(self):
433 """ Get the filename of the Nilvera PDF invoice report. """
434 self.ensure_one()
435 return f"{self._get_move_display_name().replace(' ', '_').replace('/', '_')}_einvoice.pdf"
436
437 # -------------------------------------------------------------------------
438 # CRONS
439 # -------------------------------------------------------------------------
440
441 def _l10n_tr_nilvera_company_get_documents(self, invoice_channel, category, journal_type):
442 for company in self.env.companies:
443 if company.country_code != "TR" or not company.l10n_tr_nilvera_api_key:
444 continue
445 self.with_company(company)._l10n_tr_nilvera_get_documents(invoice_channel, category, journal_type)
446
447 def _cron_nilvera_get_new_einvoice_purchase_documents(self):
448 self._l10n_tr_nilvera_company_get_documents("einvoice", "Purchase", "purchase")
449
450 def _cron_nilvera_get_new_einvoice_sale_documents(self):
451 self._l10n_tr_nilvera_company_get_documents("einvoice", "Sale", "sale")
452
453 def _cron_nilvera_get_new_earchive_sale_documents(self):
454 self._l10n_tr_nilvera_company_get_documents("earchive", "Invoices", "sale")
455
456 def _cron_nilvera_get_invoice_status(self):
457 invoices_to_update = self.env['account.move'].search([
458 ('l10n_tr_nilvera_send_status', 'in', ['waiting', 'sent']),
459 ('move_type', 'in', self._l10n_tr_types_to_update_status()),
460 ])
461 invoices_to_update._l10n_tr_nilvera_get_submitted_document_status()
462
463 def _cron_nilvera_get_sale_pdf(self, batch_size=100):
464 """ Fetches the Nilvera generated PDFs for the sales generated on Odoo. """
465 # We fetch all invoices whose message_main_attachment_id is the same
466 # as their invoice_pdf_report_id attachment. After we add the Nilvera
467 # PDF, `_l10n_tr_nilvera_add_pdf_to_invoice` will set
468 # `message_main_attachment_id` to the Nilvera attachment, so they
469 # won't be picked up by next runs.
470 # This is a workaround to do this in stable without adding a dedicated field.
471 sql = SQL("""
472 SELECT am.id
473 FROM account_move am
474 JOIN ir_attachment ia
475 ON ia.res_model = 'account.move'
476 AND ia.res_id = am.id
477 AND ia.mimetype = 'application/pdf'
478 AND ia.res_field = 'invoice_pdf_report_file'
479 WHERE am.message_main_attachment_id = ia.id
480 AND am.l10n_tr_nilvera_send_status = 'succeed'
481 AND am.move_type = 'out_invoice'
482 LIMIT %s
483 """, batch_size)
484 move_ids = [row[0] for row in self.env.execute_query(sql)]
485 invoice_to_fetch_pdf = self.env['account.move'].browse(move_ids)
486 for company, invoices in invoice_to_fetch_pdf.grouped("company_id").items():
487 with _get_nilvera_client(company) as client:
488 for invoice in invoices:
489 self._l10n_tr_nilvera_add_pdf_to_invoice(
490 client,
491 invoice,
492 invoice.l10n_tr_nilvera_uuid,
493 document_category="Sale",
494 invoice_channel=invoice.l10n_tr_nilvera_customer_status,
495 )