Debian Codegraph @

addons/l10n_hu_edi/models/l10n_hu_edi_connection.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from base64 import b64decode, b64encode
4 import binascii
5 from datetime import datetime, timedelta, timezone
6 import hashlib
7 import logging
8 import secrets
9
10 from cryptography.hazmat.primitives import padding
11 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
12 import dateutil.parser
13 from lxml import etree
14 import requests
15
16 from odoo import _, release
17 from odoo.tools import cleanup_xml_node
18
19
20 _logger = logging.getLogger(__name__)
21
22
23 XML_NAMESPACES = {
24 'api': 'http://schemas.nav.gov.hu/OSA/3.0/api',
25 'common': 'http://schemas.nav.gov.hu/NTCA/1.0/common',
26 'base': 'http://schemas.nav.gov.hu/OSA/3.0/base',
27 'data': 'http://schemas.nav.gov.hu/OSA/3.0/data',
28 }
29
30
31 def format_bool(value):
32 return 'true' if value else 'false'
33
34
35 def format_timestamp(value):
36 return value.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
37
38
39 def decrypt_aes128(key, encrypted_token):
40 """ Decrypt AES-128-ECB encrypted bytes.
41 :param key bytes: the 128-bit key
42 :param encrypted_token bytes: the bytes to decrypt
43 :return: the decrypted bytes
44 """
45 decryptor = Cipher(algorithms.AES(key), modes.ECB()).decryptor()
46 decrypted_token = decryptor.update(encrypted_token) + decryptor.finalize()
47 unpadder = padding.PKCS7(128).unpadder()
48 unpadded_token = unpadder.update(decrypted_token) + unpadder.finalize()
49 return unpadded_token
50
51
52 class L10nHuEdiConnectionError(Exception):
53 def __init__(self, errors, code=None):
54 if not isinstance(errors, list):
55 errors = [errors]
56 self.errors = errors
57 self.code = code
58 super().__init__('\n'.join(errors))
59
60
61 class L10nHuEdiConnection:
62 def __init__(self, env):
63 """ Methods to call NAV API endpoints.
64 Use this as a context manager (`with L10nHuEdiConnection(...) as connection`)
65 to ensure the TCP connection is closed when you are finished calling endpoints.
66
67 :param env: the Odoo environment
68 """
69 self.env = env
70 self.session = requests.Session()
71
72 def __enter__(self):
73 return self
74
75 def __exit__(self, *args):
76 self.session.close()
77
78 def do_token_exchange(self, credentials):
79 """ Request a token for invoice submission.
80
81 :param credentials: a dictionary
82 {
83 'vat': str,
84 'mode': 'production' || 'test',
85 'username': str,
86 'password': str,
87 'signature_key': str,
88 'replacement_key': str
89 }
90 :return: a dictionary {'token': str, 'token_validity_to': datetime}
91 :raise: L10nHuEdiConnectionError
92 """
93 if credentials['mode'] == 'demo':
94 return {'token': 'token', 'token_validity_to': datetime.utcnow() + timedelta(minutes=5)}
95
96 template_values = self._get_header_values(credentials)
97 request_data = self.env['ir.qweb']._render('l10n_hu_edi.token_exchange_request', template_values)
98 request_data = etree.tostring(cleanup_xml_node(request_data, remove_blank_nodes=False), xml_declaration=True, encoding='UTF-8')
99
100 response_xml = self._call_nav_endpoint(credentials['mode'], 'tokenExchange', request_data)
101 self._parse_error_response(response_xml)
102
103 encrypted_token = response_xml.findtext('api:encodedExchangeToken', namespaces=XML_NAMESPACES)
104 token_validity_to = response_xml.findtext('api:tokenValidityTo', namespaces=XML_NAMESPACES)
105 try:
106 # Convert into a naive UTC datetime, since Odoo can't store timezone-aware datetimes
107 token_validity_to = dateutil.parser.isoparse(token_validity_to).astimezone(timezone.utc).replace(tzinfo=None)
108 except ValueError:
109 _logger.warning('Could not parse token validity end timestamp!')
110 token_validity_to = datetime.utcnow() + timedelta(minutes=5)
111
112 if not encrypted_token:
113 raise L10nHuEdiConnectionError(_('Missing token in response from NAV.'))
114
115 try:
116 token = decrypt_aes128(credentials['replacement_key'].encode(), b64decode(encrypted_token.encode())).decode()
117 except ValueError as e:
118 raise L10nHuEdiConnectionError(_('Error during decryption of ExchangeToken.')) from e
119
120 return {'token': token, 'token_validity_to': token_validity_to}
121
122 def do_manage_invoice(self, credentials, token, invoice_operations):
123 """ Submit one or more invoices.
124
125 :param token: a token obtained via `do_token_exchange`
126 :param invoice_operations: a list of dictionaries:
127 {
128 'index': <index given to invoice>,
129 'operation': 'CREATE' or 'MODIFY' or 'STORNO',
130 'invoice_data': <XML data of the invoice as bytes>
131 }
132 :return str: The transaction code issued by NAV.
133 :raise: L10nHuEdiConnectionError, with code='timeout' if a timeout occurred.
134 """
135 if credentials['mode'] == 'demo':
136 return secrets.token_hex(8).upper()
137
138 template_values = {
139 'exchangeToken': token,
140 'compressedContent': False,
141 'invoices': [],
142 }
143 invoice_hashes = []
144 for invoice_operation in invoice_operations:
145 invoice_data_b64 = b64encode(invoice_operation['invoice_data']).decode('utf-8')
146 template_values['invoices'].append({
147 'index': invoice_operation['index'],
148 'invoiceOperation': invoice_operation['operation'],
149 'invoiceData': invoice_data_b64,
150 })
151 invoice_hashes.append(self._calculate_invoice_hash(invoice_operation['operation'] + invoice_data_b64))
152
153 template_values.update(self._get_header_values(credentials, invoice_hashs=invoice_hashes))
154
155 request_data = self.env['ir.qweb']._render('l10n_hu_edi.manage_invoice_request', template_values)
156 request_data = etree.tostring(cleanup_xml_node(request_data, remove_blank_nodes=False), xml_declaration=True, encoding='UTF-8')
157
158 response_xml = self._call_nav_endpoint(credentials['mode'], 'manageInvoice', request_data, timeout=60)
159 self._parse_error_response(response_xml)
160
161 transaction_code = response_xml.findtext('api:transactionId', namespaces=XML_NAMESPACES)
162 if not transaction_code:
163 raise L10nHuEdiConnectionError(_('Invoice Upload failed: NAV did not return a Transaction ID.'))
164
165 return transaction_code
166
167 def do_query_transaction_status(self, credentials, transaction_code, return_original_request=False):
168 """ Query the status of a transaction.
169
170 :param transaction_code: the code of the transaction to query
171 :param return_original_request: whether to request the submitted invoice XML.
172 :return: a list of dicts {'index': str, 'invoice_status': str, 'business_validation_messages', 'technical_validation_messages'}
173 :raise: L10nHuEdiConnectionError
174 """
175 if credentials['mode'] == 'demo':
176 invoices = self.env['account.move'].search([('l10n_hu_edi_transaction_code', '=', transaction_code)])
177 if any(m.l10n_hu_edi_state.startswith('cancel') for m in invoices):
178 return {
179 'processing_results': [
180 {
181 'index': str(i + 1),
182 'invoice_status': 'DONE',
183 'business_validation_messages': [{
184 'validation_result_code': 'INFO',
185 'validation_error_code': 'INFO_SINGLE_INVOICE_ANNULMENT',
186 'message': 'Egyedi számla technikai érvénytelenítése',
187 }],
188 'technical_validation_messages': [],
189 }
190 for i in range(len(invoices))
191 ],
192 'annulment_status': 'VERIFICATION_DONE',
193 }
194 else:
195 return {
196 'processing_results': [
197 {
198 'index': str(i + 1),
199 'invoice_status': 'DONE',
200 'business_validation_messages': [],
201 'technical_validation_messages': [],
202 }
203 for i in range(len(invoices))
204 ],
205 'annulment_status': None,
206 }
207
208 template_values = {
209 **self._get_header_values(credentials),
210 'transactionId': transaction_code,
211 'returnOriginalRequest': return_original_request,
212 }
213 request_data = self.env['ir.qweb']._render('l10n_hu_edi.query_transaction_status_request', template_values)
214 request_data = etree.tostring(cleanup_xml_node(request_data, remove_blank_nodes=False), xml_declaration=True, encoding='UTF-8')
215
216 response_xml = self._call_nav_endpoint(credentials['mode'], 'queryTransactionStatus', request_data)
217 self._parse_error_response(response_xml)
218
219 results = {
220 'processing_results': [],
221 'annulment_status': response_xml.findtext('api:processingResults/api:annulmentData/api:annulmentVerificationStatus', namespaces=XML_NAMESPACES),
222 }
223 for processing_result_xml in response_xml.iterfind('api:processingResults/api:processingResult', namespaces=XML_NAMESPACES):
224 processing_result = {
225 'index': processing_result_xml.findtext('api:index', namespaces=XML_NAMESPACES),
226 'invoice_status': processing_result_xml.findtext('api:invoiceStatus', namespaces=XML_NAMESPACES),
227 'business_validation_messages': [],
228 'technical_validation_messages': [],
229 }
230 for message_xml in processing_result_xml.iterfind('api:businessValidationMessages', namespaces=XML_NAMESPACES):
231 processing_result['business_validation_messages'].append({
232 'validation_result_code': message_xml.findtext('api:validationResultCode', namespaces=XML_NAMESPACES),
233 'validation_error_code': message_xml.findtext('api:validationErrorCode', namespaces=XML_NAMESPACES),
234 'message': message_xml.findtext('api:message', namespaces=XML_NAMESPACES),
235 })
236 for message_xml in processing_result_xml.iterfind('api:technicalValidationMessages', namespaces=XML_NAMESPACES):
237 processing_result['technical_validation_messages'].append({
238 'validation_result_code': message_xml.findtext('common:validationResultCode', namespaces=XML_NAMESPACES),
239 'validation_error_code': message_xml.findtext('common:validationErrorCode', namespaces=XML_NAMESPACES),
240 'message': message_xml.findtext('common:message', namespaces=XML_NAMESPACES),
241 })
242 if return_original_request:
243 try:
244 original_file = b64decode(processing_result_xml.findtext('api:originalRequest', namespaces=XML_NAMESPACES))
245 original_xml = etree.fromstring(original_file)
246 except binascii.Error as e:
247 raise L10nHuEdiConnectionError(str(e)) from e
248 except etree.ParserError as e:
249 raise L10nHuEdiConnectionError(str(e)) from e
250
251 processing_result.update({
252 'original_file': original_file.decode(),
253 'original_xml': original_xml,
254 })
255
256 results['processing_results'].append(processing_result)
257
258 return results
259
260 def do_query_transaction_list(self, credentials, datetime_from, datetime_to, page=1):
261 """ Query the transactions that were submitted in a given time interval.
262
263 :param datetime_from: start of the time interval to query
264 :param datetime_to: end of the time interval to query
265 :return: a dict {'transaction_codes': list[str], 'available_pages': int}
266 :raise: L10nHuEdiConnectionError
267 """
268 if credentials['mode'] == 'demo':
269 return {"transactions": [], "available_pages": 1}
270
271 template_values = {
272 **self._get_header_values(credentials),
273 'page': page,
274 'dateTimeFrom': format_timestamp(datetime_from),
275 'dateTimeTo': format_timestamp(datetime_to),
276 }
277 request_data = self.env['ir.qweb']._render('l10n_hu_edi.query_transaction_list_request', template_values)
278 request_data = etree.tostring(cleanup_xml_node(request_data, remove_blank_nodes=False), xml_declaration=True, encoding='UTF-8')
279
280 response_xml = self._call_nav_endpoint(credentials['mode'], 'queryTransactionList', request_data)
281 self._parse_error_response(response_xml)
282
283 available_pages = response_xml.findtext('api:transactionListResult/api:availablePage', namespaces=XML_NAMESPACES)
284 try:
285 available_pages = int(available_pages)
286 except ValueError:
287 available_pages = 1
288
289 transactions = []
290 for transaction_xml in response_xml.iterfind('api:transactionListResult/api:transaction', namespaces=XML_NAMESPACES):
291 try:
292 send_time = datetime.fromisoformat(transaction_xml.findtext('api:insDate', namespaces=XML_NAMESPACES).replace('Z', ''))
293 except ValueError as e:
294 raise L10nHuEdiConnectionError(_('Could not parse time of previous transaction')) from e
295 transactions.append({
296 'transaction_code': transaction_xml.findtext('api:transactionId', namespaces=XML_NAMESPACES),
297 'annulment': transaction_xml.findtext('api:technicalAnnulment', namespaces=XML_NAMESPACES) == 'true',
298 'username': transaction_xml.findtext('api:insCusUser', namespaces=XML_NAMESPACES),
299 'source': transaction_xml.findtext('api:source', namespaces=XML_NAMESPACES),
300 'send_time': send_time,
301 })
302
303 return {"transactions": transactions, "available_pages": available_pages}
304
305 def do_manage_annulment(self, credentials, token, annulment_operations):
306 """ Request technical annulment of one or more invoices.
307
308 :param token: a token obtained via `do_token_exchange`
309 :param annulment_operations: a list of dictionaries:
310 {
311 'index': <index given to invoice>,
312 'annulmentReference': the name of the invoice to annul,
313 'annulmentCode': one of ('ERRATIC_DATA', 'ERRATIC_INVOICE_NUMBER', 'ERRATIC_INVOICE_ISSUE_DATE', 'ERRATIC_ELECTRONIC_HASH_VALUE'),
314 'annulmentReason': a plain-text explanation of the reason for annulment,
315 }
316 :return str: The transaction code issued by NAV.
317 :raise: L10nHuEdiConnectionError, with code='timeout' if a timeout occurred.
318 """
319 if credentials['mode'] == 'demo':
320 return secrets.token_hex(8).upper()
321
322 template_values = {
323 'exchangeToken': token,
324 'annulments': []
325 }
326
327 annulment_hashes = []
328 for annulment_operation in annulment_operations:
329 annulment_operation['annulmentTimestamp'] = format_timestamp(datetime.utcnow())
330 annulment_data = self.env['ir.qweb']._render('l10n_hu_edi.invoice_annulment', annulment_operation)
331 annulment_data_b64 = b64encode(annulment_data.encode()).decode('utf-8')
332 template_values['annulments'].append({
333 'index': annulment_operation['index'],
334 'annulmentOperation': 'ANNUL',
335 'invoiceAnnulment': annulment_data_b64,
336 })
337 annulment_hashes.append(self._calculate_invoice_hash('ANNUL' + annulment_data_b64))
338
339 template_values.update(self._get_header_values(credentials, invoice_hashs=annulment_hashes))
340
341 request_data = self.env['ir.qweb']._render('l10n_hu_edi.manage_annulment_request', template_values)
342 request_data = etree.tostring(cleanup_xml_node(request_data, remove_blank_nodes=False), xml_declaration=True, encoding='UTF-8')
343
344 response_xml = self._call_nav_endpoint(credentials['mode'], 'manageAnnulment', request_data, timeout=60)
345 self._parse_error_response(response_xml)
346
347 transaction_code = response_xml.findtext('api:transactionId', namespaces=XML_NAMESPACES)
348 if not transaction_code:
349 raise L10nHuEdiConnectionError(_('Invoice Upload failed: NAV did not return a Transaction ID.'))
350
351 return transaction_code
352
353 # === Helpers: XML generation === #
354
355 def _get_header_values(self, credentials, invoice_hashs=None):
356 timestamp = datetime.utcnow()
357 request_id = 'ODOO' + secrets.token_hex(13)
358 request_signature = self._calculate_request_signature(credentials['signature_key'], request_id, timestamp, invoice_hashs=invoice_hashs)
359 odoo_version = release.version
360 module_version = self.env['ir.module.module'].get_module_info('l10n_hu_edi').get('version').replace('saas~', '').replace('.', '')
361
362 return {
363 'requestId': request_id,
364 'timestamp': format_timestamp(timestamp),
365 'login': credentials['username'],
366 'passwordHash': self._calculate_password_hash(credentials['password']),
367 'taxNumber': credentials['vat'][:8],
368 'requestSignature': request_signature,
369 'softwareId': f'BE477472701-{module_version}'[:18],
370 'softwareName': 'Odoo Enterprise',
371 'softwareOperation': 'ONLINE_SERVICE',
372 'softwareMainVersion': odoo_version,
373 'softwareDevName': 'Odoo SA',
374 'softwareDevContact': '[email protected]',
375 'softwareDevCountryCode': 'BE',
376 'softwareDevTaxNumber': '477472701',
377 'format_bool': format_bool,
378 }
379
380 def _calculate_password_hash(self, password):
381 return hashlib.sha512(password.encode()).hexdigest().upper()
382
383 def _calculate_invoice_hash(self, value):
384 return hashlib.sha3_512(value.encode()).hexdigest().upper()
385
386 def _calculate_request_signature(self, key_sign, reqid, reqdate, invoice_hashs=None):
387 strings = [reqid, reqdate.strftime('%Y%m%d%H%M%S'), key_sign]
388
389 # merge the invoice CRCs if we got
390 if invoice_hashs:
391 strings += invoice_hashs
392
393 # return back the uppered hexdigest
394 return self._calculate_invoice_hash(''.join(strings))
395
396 # === Helpers: HTTP Post === #
397
398 def _call_nav_endpoint(self, mode, service, data, timeout=20):
399 if mode == 'production':
400 url = 'https://api.onlineszamla.nav.gov.hu/invoiceService/v3/'
401 elif mode == 'test':
402 url = 'https://api-test.onlineszamla.nav.gov.hu/invoiceService/v3/'
403 else:
404 raise L10nHuEdiConnectionError(_('Mode should be Production or Test!'))
405
406 headers = {'content-type': 'application/xml', 'accept': 'application/xml'}
407 try:
408 response_object = self.session.post(f'{url}{service}', data=data, headers=headers, timeout=timeout)
409 except requests.Timeout as e:
410 raise L10nHuEdiConnectionError(_('Connection to NAV servers timed out.'), code='timeout') from e
411 except requests.RequestException as e:
412 raise L10nHuEdiConnectionError(str(e)) from e
413
414 try:
415 response_xml = etree.fromstring(response_object.text.encode())
416 except etree.ParseError as e:
417 raise L10nHuEdiConnectionError(_('Invalid NAV response!')) from e
418
419 return response_xml
420
421 # === Helpers: Response parsing === #
422
423 def _parse_error_response(self, response_xml):
424 error_code = response_xml.findtext('common:result/common:errorCode', namespaces=XML_NAMESPACES)
425 message = response_xml.findtext('common:result/common:message', namespaces=XML_NAMESPACES)
426 if error_code:
427 errors = [f'{error_code}: {message}']
428 for message_xml in response_xml.iterfind('api:technicalValidationMessages', namespaces=XML_NAMESPACES):
429 message = message_xml.findtext('api:message', namespaces=XML_NAMESPACES)
430 error_code = message_xml.findtext('api:validationErrorCode', namespaces=XML_NAMESPACES)
431 errors.append(f'{error_code}: {message}')
432
433 raise L10nHuEdiConnectionError(errors)