Debian Codegraph @

addons/l10n_hu_edi/models/res_company.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import base64
4 from datetime import timedelta
5 from itertools import islice
6
7 from lxml import etree
8
9 from odoo import models, fields, _
10 from odoo.exceptions import UserError
11 from odoo.addons.l10n_hu_edi.models.l10n_hu_edi_connection import L10nHuEdiConnection, L10nHuEdiConnectionError, XML_NAMESPACES
12
13
14 class ResCompany(models.Model):
15 _inherit = 'res.company'
16
17 l10n_hu_group_vat = fields.Char(
18 related='partner_id.l10n_hu_group_vat',
19 readonly=False,
20 )
21 l10n_hu_tax_regime = fields.Selection(
22 selection=[
23 ('ie', 'Individual Exemption'),
24 ('ca', 'Cash Accounting'),
25 ('sb', 'Small Business'),
26 ],
27 string='NAV Tax Regime',
28 )
29 l10n_hu_edi_server_mode = fields.Selection(
30 selection=[
31 ('production', 'Production'),
32 ('test', 'Test'),
33 ('demo', 'Demo'),
34 ],
35 string='Server Mode',
36 help="""
37 - Production: Sends invoices to the NAV's production system.
38 - Test: Sends invoices to the NAV's test system.
39 - Demo: Mocks the NAV system (does not require credentials).
40 """
41 )
42 l10n_hu_edi_username = fields.Char(
43 string='NAV Username',
44 groups='base.group_system',
45 )
46 l10n_hu_edi_password = fields.Char(
47 string='NAV Password',
48 groups='base.group_system',
49 )
50 l10n_hu_edi_signature_key = fields.Char(
51 string='NAV Signature Key',
52 groups='base.group_system',
53 )
54 l10n_hu_edi_replacement_key = fields.Char(
55 string='NAV Replacement Key',
56 groups='base.group_system',
57 )
58 l10n_hu_edi_last_transaction_recovery = fields.Datetime(
59 string='Last transaction recovery (in production mode)',
60 default=lambda self: fields.Datetime.now(),
61 )
62
63 def _l10n_hu_edi_configure_company(self):
64 """ Single-time configuration for companies, to be applied when l10n_hu_edi is installed
65 or a new company is created.
66 """
67 for company in self:
68 # Set profit/loss accounts on cash rounding method
69 profit_account = self.env['account.chart.template'].with_company(company).ref('l10n_hu_969', raise_if_not_found=False)
70 loss_account = self.env['account.chart.template'].with_company(company).ref('l10n_hu_869', raise_if_not_found=False)
71 rounding_method = self.env.ref('l10n_hu_edi.cash_rounding_1_huf', raise_if_not_found=False)
72 if profit_account and loss_account and rounding_method:
73 rounding_method.with_company(company).write({
74 'profit_account_id': profit_account.id,
75 'loss_account_id': loss_account.id,
76 })
77
78 # Activate cash rounding on the company
79 res_config_id = self.env['res.config.settings'].create({
80 'company_id': company.id,
81 'group_cash_rounding': True,
82 })
83 res_config_id.execute()
84
85 def _l10n_hu_edi_get_credentials_dict(self):
86 self.ensure_one()
87 credentials_dict = {
88 'vat': self.vat,
89 'mode': self.l10n_hu_edi_server_mode,
90 'username': self.l10n_hu_edi_username,
91 'password': self.l10n_hu_edi_password,
92 'signature_key': self.l10n_hu_edi_signature_key,
93 'replacement_key': self.l10n_hu_edi_replacement_key,
94 }
95 if self.l10n_hu_edi_server_mode != 'demo' and not all(credentials_dict.values()):
96 raise UserError(_('Missing NAV credentials for company %s', self.name))
97 return credentials_dict
98
99 def _l10n_hu_edi_test_credentials(self):
100 with L10nHuEdiConnection(self.env) as connection:
101 for company in self:
102 if not company.vat:
103 raise UserError(_('NAV Credentials: Please set the hungarian vat number on the company first!'))
104 try:
105 connection.do_token_exchange(company._l10n_hu_edi_get_credentials_dict())
106 except L10nHuEdiConnectionError as e:
107 raise UserError(
108 _('Incorrect NAV Credentials! Check that your company VAT number is set correctly. \nError details: %s', e)
109 ) from e
110
111 def _l10n_hu_edi_recover_transactions(self, connection):
112 """ Recover transactions that are in force but for some reason are not matched to the company's
113 invoices, and update the invoice state correspondingly.
114
115 This can happen, for example, if the invoice sending timed out: in that case, we don't have a
116 transaction ID for the invoice. It can also happen if for some reason the transaction ID was
117 overwritten by a new request, but the new request fails with a 'duplicate invoice' error.
118
119 To do this, we request a list of all transactions made since l10n_hu_edi_last_transaction_recovery,
120 and then we query the last 10 transactions whose transaction IDs are unknown by Odoo. We try to
121 match them to invoices in Odoo, and if successful, update the invoice state.
122 """
123
124 for company in self:
125 # We use the l10n_hu_edi_last_transaction_recovery time only in production mode
126 # to indicate which transactions to request.
127 # In test mode (where we expect far fewer invoices), we just take the last 24 hours.
128 recovery_end_time = fields.Datetime.now()
129 if company.l10n_hu_edi_server_mode == 'production':
130 recovery_start_time = company.l10n_hu_edi_last_transaction_recovery
131 else:
132 recovery_start_time = recovery_end_time - timedelta(hours=24)
133
134 # Old invoices are already up-to-date - no need to re-check them.
135 invoices_to_check = self.env['account.move'].search([
136 ('company_id', '=', company.id),
137 ('l10n_hu_edi_send_time', '>=', recovery_start_time),
138 ('l10n_hu_edi_state', '!=', False),
139 ])
140 # Step 1: Request a list of all transactions made during the specified time interval.
141 page = 1
142 available_pages = 1
143 transactions = []
144 while page <= available_pages:
145 try:
146 transaction_list = connection.do_query_transaction_list(
147 company.sudo()._l10n_hu_edi_get_credentials_dict(),
148 recovery_start_time,
149 recovery_end_time,
150 page,
151 )
152 except L10nHuEdiConnectionError as e:
153 return {
154 'error_title': _('Error listing transactions while attempting transaction recovery.'),
155 'errors': e.errors,
156 }
157
158 available_pages = transaction_list['available_pages']
159 transactions += transaction_list['transactions']
160 page += 1
161
162 # Step 2: Query unknown transactions in reverse order (latest first) and update invoice states accordingly.
163 # If there are too many, we should only query the last 10, to avoid pointlessly making huge numbers of requests.
164 transactions_to_query = (
165 t for t in reversed(transactions)
166 if t['username'] == company.sudo().l10n_hu_edi_username
167 and t['source'] == 'MGM'
168 and t['transaction_code'] not in invoices_to_check.mapped('l10n_hu_edi_transaction_code')
169 )
170
171 for transaction in islice(transactions_to_query, 10):
172 try:
173 results = connection.do_query_transaction_status(
174 company.sudo()._l10n_hu_edi_get_credentials_dict(),
175 transaction['transaction_code'],
176 return_original_request=True,
177 )
178 except L10nHuEdiConnectionError as e:
179 return {
180 'error_title': _('Error querying transaction while attempting transaction recovery.'),
181 'errors': e.errors,
182 }
183
184 for processing_result in results['processing_results']:
185 invoice_name = processing_result['original_xml'].findtext('data:invoiceNumber', namespaces=XML_NAMESPACES)
186 canonicalized_attachment = etree.canonicalize(processing_result['original_file'])
187 annulment_invoice_name = processing_result['original_xml'].findtext('data:annulmentReference', namespaces=XML_NAMESPACES)
188
189 matched_invoice = invoices_to_check.filtered(
190 lambda m: (
191 # 1. Match invoice if the entire XML matches.
192 # For performance, we first check the invoice name before trying to match the whole XML.
193 (
194 m.name == invoice_name
195 and etree.canonicalize(base64.b64decode(m.l10n_hu_edi_attachment).decode())
196 == canonicalized_attachment
197 )
198 or m.name == annulment_invoice_name
199 ) and (
200 # 2. We update the invoice state only if:
201 # - the invoice doesn't have a transaction code, or
202 # - it currently has a duplicate error, or
203 # - the current transaction is more recent than the latest transaction on the invoice
204 # and is not a duplicate error (this avoid overwriting the state with a previous, obsolete one).
205 not m.l10n_hu_edi_transaction_code
206 or any(
207 'INVOICE_NUMBER_NOT_UNIQUE' in error or 'ANNULMENT_IN_PROGRESS' in error
208 for error in m.l10n_hu_edi_messages['errors']
209 )
210 or (
211 transaction['send_time'] >= m.l10n_hu_edi_send_time
212 and not (
213 processing_result['technical_validation_messages']
214 or any(
215 message['validation_error_code'] in ['INVOICE_NUMBER_NOT_UNIQUE', 'ANNULMENT_IN_PROGRESS']
216 for message in processing_result['business_validation_messages']
217 )
218 )
219 )
220 )
221 )
222
223 if matched_invoice:
224 # Set the correct transaction code on the matched invoice
225 matched_invoice.l10n_hu_edi_transaction_code = transaction['transaction_code']
226 matched_invoice._l10n_hu_edi_process_query_transaction_result(processing_result, results['annulment_status'])
227
228 # The server might still be processing transactions from the last 6 minutes,
229 # so we should keep open the possibility of re-querying them.
230 recovery_close_time = recovery_end_time - timedelta(minutes=6)
231 if company.l10n_hu_edi_server_mode == 'production':
232 company.l10n_hu_edi_last_transaction_recovery = recovery_close_time
233
234 # Any invoices still in a 'timeout' state that are more than 6 minutes old and could not be matched should be considered not received.
235 invoices_to_check.filtered(
236 lambda m: m.l10n_hu_edi_state == 'send_timeout' and m.l10n_hu_edi_send_time < recovery_close_time
237 ).write({
238 'l10n_hu_invoice_chain_index': 0,
239 'l10n_hu_edi_state': 'rejected',
240 })
241
242 invoices_to_check.filtered(
243 lambda m: m.l10n_hu_edi_state == 'cancel_timeout' and m.l10n_hu_edi_send_time < recovery_close_time
244 ).write({
245 'l10n_hu_edi_state': 'confirmed_warning',
246 })