Debian Codegraph @

addons/l10n_dk_nemhandel/models/account_move_send.py

raw
1 from base64 import b64encode
2 from datetime import timedelta
3
4 from odoo import _, fields, models
5 from odoo.exceptions import UserError
6
7
8 class AccountMoveSend(models.AbstractModel):
9 _inherit = 'account.move.send'
10
11 # -------------------------------------------------------------------------
12 # SENDING METHODS
13 # -------------------------------------------------------------------------
14
15 def _get_default_invoice_edi_format(self, move, **kwargs) -> str:
16 # EXTENDS 'account' - default on OIOUBL 2.1 if Nemhandel is set but no format on the partner
17 if 'nemhandel' in kwargs.get('sending_methods', []):
18 return 'oioubl_21'
19
20 return super()._get_default_invoice_edi_format(move, **kwargs)
21
22 def _is_applicable_to_company(self, method, company):
23 # EXTENDS 'account'
24 if method == 'nemhandel':
25 return company.l10n_dk_nemhandel_proxy_state != 'rejected'
26 return super()._is_applicable_to_company(method, company)
27
28 def _is_applicable_to_move(self, method, move, **move_data):
29 # EXTENDS 'account'
30 if method == 'nemhandel':
31 partner = move.partner_id.commercial_partner_id.with_company(move.company_id)
32 invoice_edi_format = move_data.get('invoice_edi_format') or 'oioubl_21'
33 return all([
34 self._is_applicable_to_company(method, move.company_id),
35 partner.nemhandel_verification_state == 'valid',
36 move._need_ubl_cii_xml(invoice_edi_format)
37 or move.ubl_cii_xml_id and move.nemhandel_move_state not in {'processing', 'done'},
38 ])
39
40 return super()._is_applicable_to_move(method, move, **move_data)
41
42 def _hook_if_errors(self, moves_data, allow_raising=True):
43 # EXTENDS 'account'
44 # to update `nemhandel_move_state` as `error` to show users that something went wrong
45 # because those moves that failed XML/PDF files generation are not sent via Nemhandel
46 moves_failed_file_generation = self.env['account.move']
47 for move, move_data in moves_data.items():
48 if 'nemhandel' in move_data['sending_methods'] and move_data.get('blocking_error'):
49 moves_failed_file_generation |= move
50
51 moves_failed_file_generation.nemhandel_move_state = 'error'
52
53 return super()._hook_if_errors(moves_data, allow_raising=allow_raising)
54
55 def _call_web_service_after_invoice_pdf_render(self, invoices_data):
56 # EXTENDS 'account'
57 super()._call_web_service_after_invoice_pdf_render(invoices_data)
58
59 params = {'documents': []}
60 invoices_data_nemhandel = {}
61 for invoice, invoice_data in invoices_data.items():
62 partner = invoice.partner_id.commercial_partner_id.with_company(invoice.company_id)
63 if 'nemhandel' not in invoice_data['sending_methods']:
64 continue
65
66 if not partner.nemhandel_identifier_type or not partner.nemhandel_identifier_value:
67 invoice.nemhandel_move_state = 'error'
68 invoice_data['error'] = _('The partner is missing Nemhandel Endpoint Type or Value.')
69 continue
70
71 if partner._get_nemhandel_verification_state(invoice_data['invoice_edi_format']) != 'valid':
72 invoice.nemhandel_move_state = 'error'
73 invoice_data['error'] = _('Please verify partner configuration in partner settings.')
74 continue
75
76 if not self._is_applicable_to_move('nemhandel', invoice, **invoice_data):
77 continue
78
79 if invoice_data.get('ubl_cii_xml_attachment_values'):
80 xml_file = invoice_data['ubl_cii_xml_attachment_values']['raw']
81 filename = invoice_data['ubl_cii_xml_attachment_values']['name']
82 elif invoice.ubl_cii_xml_id and invoice.nemhandel_move_state not in {'processing', 'done'}:
83 xml_file = invoice.ubl_cii_xml_id.raw
84 filename = invoice.ubl_cii_xml_id.name
85 else:
86 invoice.nemhandel_move_state = 'error'
87 builder = invoice.partner_id.commercial_partner_id._get_edi_builder(invoice_data['invoice_edi_format'])
88 invoice_data['error'] = _(
89 "Errors occurred while creating the EDI document (format: %s):",
90 builder._description,
91 )
92 continue
93
94 receiver_identification = f"{partner.nemhandel_identifier_type}:{partner.nemhandel_identifier_value}"
95 params['documents'].append({
96 'filename': filename,
97 'receiver': receiver_identification,
98 'ubl': b64encode(xml_file).decode(),
99 })
100 invoices_data_nemhandel[invoice] = invoice_data
101
102 if not params['documents']:
103 return
104
105 edi_user = next(iter(invoices_data)).company_id.nemhandel_edi_user
106
107 try:
108 response = edi_user._call_nemhandel_proxy(
109 "/api/nemhandel/1/send_document",
110 params=params,
111 )
112 except UserError as e:
113 for invoice, invoice_data in invoices_data_nemhandel.items():
114 invoice.nemhandel_move_state = 'error'
115 invoice_data['error'] = str(e)
116 else:
117 if response.get('error'):
118 # at the moment the only error that can happen here is ParticipantNotReady error
119 for invoice, invoice_data in invoices_data_nemhandel.items():
120 invoice.nemhandel_move_state = 'error'
121 invoice_data['error'] = response['error']['message']
122 else:
123 # the response only contains message uuids,
124 # so we have to rely on the order to connect nemhandel messages to account.move
125 invoices = self.env['account.move']
126 for message, (invoice, invoice_data) in zip(response['messages'], invoices_data_nemhandel.items()):
127 invoice.nemhandel_message_uuid = message['message_uuid']
128 invoice.nemhandel_move_state = 'processing'
129 invoices |= invoice
130 log_message = _('The document has been sent to the Nemhandel Access Point for processing')
131 invoices._message_log_batch(bodies={invoice.id: log_message for invoice in invoices})
132 self.env.ref('l10n_dk_nemhandel.ir_cron_nemhandel_get_message_status')._trigger(at=fields.Datetime.now() + timedelta(minutes=5))
133
134 if self._can_commit():
135 self.env.cr.commit()