Debian Codegraph @

addons/l10n_dk_nemhandel/models/account_edi_proxy_user.py

raw
1 import logging
2
3 from odoo import api, fields, models, modules, tools, _
4 from odoo.exceptions import UserError, ValidationError
5
6 from odoo.addons.account_edi_proxy_client.models.account_edi_proxy_user import AccountEdiProxyError
7 from odoo.addons.l10n_dk_nemhandel.tools.demo_utils import handle_demo
8
9 _logger = logging.getLogger(__name__)
10 BATCH_SIZE = 50
11
12
13 class AccountEdiProxyClientUser(models.Model):
14 _inherit = 'account_edi_proxy_client.user'
15
16 nemhandel_verification_code = fields.Char(string='Nemhandel SMS verification code')
17 proxy_type = fields.Selection(selection_add=[('nemhandel', 'Nemhandel')], ondelete={'nemhandel': 'cascade'})
18
19 # -------------------------------------------------------------------------
20 # HELPER METHODS
21 # -------------------------------------------------------------------------
22
23 def _get_proxy_urls(self):
24 urls = super()._get_proxy_urls()
25 urls['nemhandel'] = {
26 'prod': 'https://nemhandel.api.odoo.com',
27 'test': 'https://nemhandel.test.odoo.com',
28 'demo': 'demo',
29 }
30 return urls
31
32 @handle_demo
33 def _call_nemhandel_proxy(self, endpoint, params=None):
34 self.ensure_one()
35 if self.proxy_type != 'nemhandel':
36 raise UserError(_('EDI user should be of type Nemhandel'))
37
38 errors = {
39 'code_incorrect': _('The verification code is not correct'),
40 'code_expired': _('This verification code has expired. Please request a new one.'),
41 'too_many_attempts': _('Too many attempts to request an SMS code. Please try again later.'),
42 }
43
44 params = params or {}
45 try:
46 response = self._make_request(
47 f"{self._get_server_url()}{endpoint}",
48 params=params,
49 )
50 except AccountEdiProxyError as e:
51 raise UserError(e.message)
52
53 if 'error' in response:
54 error_code = response['error'].get('code')
55 error_message = response['error'].get('subject') or response['error'].get('data', {}).get('message')
56 raise UserError(errors.get(error_code) or error_message or _('Connection error, please try again later.'))
57 return response
58
59 @handle_demo
60 def _check_user_on_alternative_service(self):
61 status = self._call_nemhandel_proxy('/api/nemhandel/1/check_user_valid')
62 if status and status.get('status') != 'valid':
63 error_msg = _(
64 "A participant with these details has already been registered on the network. "
65 "If you have previously registered to an alternative Nemhandel service, please deregister"
66 )
67
68 raise UserError(error_msg)
69
70 # -------------------------------------------------------------------------
71 # CRONS
72 # -------------------------------------------------------------------------
73
74 def _cron_nemhandel_get_new_documents(self):
75 edi_users = self.search([('proxy_type', '=', 'nemhandel'), ('company_id.l10n_dk_nemhandel_proxy_state', '=', 'receiver')])
76 edi_users._nemhandel_get_new_documents(skip_no_journal=True)
77
78 def _cron_nemhandel_get_message_status(self):
79 edi_users = self.search([('proxy_type', '=', 'nemhandel'), ('company_id.l10n_dk_nemhandel_proxy_state', '=', 'receiver')])
80 edi_users._nemhandel_get_message_status()
81
82 def _cron_nemhandel_get_participant_status(self):
83 edi_users = self.search([('proxy_type', '=', 'nemhandel')])
84 edi_users._nemhandel_get_participant_status()
85
86 def _cron_nemhandel_webhook_keepalive(self):
87 edi_users = self.search([('proxy_type', '=', 'nemhandel'), ('company_id.l10n_dk_nemhandel_proxy_state', '=', 'receiver')])
88 edi_users._nemhandel_reset_webhook()
89
90 # -------------------------------------------------------------------------
91 # BUSINESS ACTIONS
92 # -------------------------------------------------------------------------
93
94 def _get_proxy_identification(self, company, proxy_type):
95 if proxy_type != 'nemhandel':
96 return super()._get_proxy_identification(company, proxy_type)
97 if not company.nemhandel_identifier_type or not company.nemhandel_identifier_value:
98 raise UserError(_("Please fill in the Identifier Type and Value."))
99 return f'{company.nemhandel_identifier_type}:{company.nemhandel_identifier_value}'
100
101 def _register_proxy_user(self, company, proxy_type, edi_mode):
102 ''' Override to avoid using the deprecated route on IAP '''
103 if proxy_type != 'nemhandel':
104 return super()._register_proxy_user(company, proxy_type, edi_mode)
105
106 private_key_sudo = self.env['certificate.key'].sudo()._generate_rsa_private_key(
107 company,
108 name=f"{proxy_type}_{edi_mode}_{company.id}.key",
109 )
110 nemhandel_identifier = self._get_proxy_identification(company, proxy_type)
111 if edi_mode == 'demo':
112 # simulate registration
113 response = {'id_client': f'demo{company.id}{proxy_type}', 'refresh_token': 'demo'}
114 else:
115 try:
116 # b64encode returns a bytestring, we need it as a string
117 response = self._make_request(self._get_server_url(proxy_type, edi_mode) + '/api/nemhandel/1/connect', params={
118 'dbuuid': company.env['ir.config_parameter'].get_param('database.uuid'),
119 'company_id': company.id,
120 'nemhandel_identifier': nemhandel_identifier,
121 'public_key': private_key_sudo._get_public_key_bytes(encoding='pem').decode(),
122 })
123 except AccountEdiProxyError as e:
124 raise UserError(e.message)
125
126 return self.create({
127 'id_client': response['id_client'],
128 'company_id': company.id,
129 'proxy_type': proxy_type,
130 'edi_mode': edi_mode,
131 'edi_identification': nemhandel_identifier,
132 'private_key_id': private_key_sudo.id,
133 'refresh_token': response['refresh_token'],
134 })
135
136 def _nemhandel_import_invoice(self, attachment, nemhandel_state, uuid, journal=None):
137 """Save new documents in an accounting journal, when one is specified on the company.
138
139 :param attachment: the new document
140 :param nemhandel_state: the state of the received Nemhandel document
141 :param uuid: the UUID of the Nemhandel document
142 :return: `True` if the document was saved, `False` if it was not
143 """
144 self.ensure_one()
145 journal = journal or self.company_id.nemhandel_purchase_journal_id
146 if not journal:
147 return False
148
149 move = self.env['account.move'].create({
150 'journal_id': journal.id,
151 'move_type': 'in_invoice',
152 'nemhandel_move_state': nemhandel_state,
153 'nemhandel_message_uuid': uuid,
154 })
155 if 'is_in_extractable_state' in move._fields:
156 move.is_in_extractable_state = False
157
158 move._extend_with_attachments(move._to_files_data(attachment), new=True)
159 move._message_log(
160 body=_(
161 "Nemhandel document (UUID: %(uuid)s) has been received successfully.",
162 uuid=uuid,
163 ),
164 attachment_ids=attachment.ids,
165 )
166 attachment.write({'res_model': 'account.move', 'res_id': move.id})
167 return {'uuid': uuid, 'move': move}
168
169 def _nemhandel_get_new_documents(self, skip_no_journal=True, batch_size=None):
170 job_count = batch_size or BATCH_SIZE
171 need_retrigger = False
172 params = {
173 'domain': {
174 'direction': 'incoming',
175 'errors': False,
176 }
177 }
178 for edi_user in self:
179 edi_user = edi_user.with_company(edi_user.company_id)
180 journal = edi_user.company_id.nemhandel_purchase_journal_id
181 if not journal:
182 msg = _('Please set a journal for Nemhandel invoices on %s before receiving documents.', edi_user.company_id.display_name)
183 if skip_no_journal:
184 _logger.warning(msg)
185 else:
186 raise UserError(msg)
187
188 params['domain']['receiver_identifier'] = edi_user.edi_identification
189 try:
190 # request all messages that haven't been acknowledged
191 messages = edi_user._call_nemhandel_proxy(
192 "/api/nemhandel/1/get_all_documents",
193 params=params,
194 )
195 except UserError as e:
196 _logger.error(
197 'Error while receiving the document from Nemhandel Proxy: %s', ', '.join(e.args),
198 )
199 continue
200
201 message_uuids = [
202 message['uuid']
203 for message in messages.get('messages', [])
204 ]
205 if not message_uuids:
206 continue
207
208 need_retrigger = need_retrigger or len(message_uuids) > job_count
209 message_uuids = message_uuids[:job_count]
210
211 created_moves = self.env['account.move']
212 uuids_to_ack = []
213 # retrieve attachments for filtered messages
214 all_messages = edi_user._call_nemhandel_proxy(
215 "/api/nemhandel/1/get_document",
216 params={'message_uuids': message_uuids},
217 )
218
219 for uuid, content in all_messages.items():
220 enc_key = content["enc_key"]
221 document_content = content["document"]
222 filename = content["filename"] or 'attachment' # default to attachment, which should not usually happen
223 decoded_document = edi_user._decrypt_data(document_content, enc_key)
224 attachment = self.env["ir.attachment"].create(
225 {
226 "name": f"{filename}.xml",
227 "raw": decoded_document,
228 "type": "binary",
229 "mimetype": "application/xml",
230 }
231 )
232 vals_to_ack = edi_user._nemhandel_import_invoice(attachment, content["state"], uuid, journal=journal)
233 if move_to_ack := vals_to_ack.get('move'):
234 created_moves |= move_to_ack
235 if uuid_to_ack := vals_to_ack.get('uuid'):
236 uuids_to_ack.append(uuid_to_ack)
237
238 if not (modules.module.current_test or tools.config['test_enable']):
239 self.env.cr.commit()
240 if uuids_to_ack:
241 edi_user._call_nemhandel_proxy(
242 "/api/nemhandel/1/ack",
243 params={'message_uuids': created_moves.mapped('nemhandel_message_uuid')},
244 )
245 if created_moves:
246 journal._notify_einvoices_received(created_moves)
247
248 if need_retrigger:
249 self.env.ref('l10n_dk_nemhandel.ir_cron_nemhandel_get_new_documents')._trigger()
250
251 def _nemhandel_get_message_status(self, batch_size=None):
252 job_count = batch_size or BATCH_SIZE
253 need_retrigger = False
254 for edi_user in self:
255 edi_user = edi_user.with_company(edi_user.company_id)
256 edi_user_moves = self.env['account.move'].search(
257 [
258 ('nemhandel_move_state', '=', 'processing'),
259 ('company_id', '=', edi_user.company_id.id),
260 ],
261 limit=job_count + 1,
262 )
263 if not edi_user_moves:
264 continue
265
266 need_retrigger = need_retrigger or len(edi_user_moves) > job_count
267 message_uuids = {move.nemhandel_message_uuid: move for move in edi_user_moves[:job_count]}
268 messages_to_process = edi_user._call_nemhandel_proxy(
269 "/api/nemhandel/1/get_document",
270 params={'message_uuids': list(message_uuids.keys())},
271 )
272
273 for uuid, content in messages_to_process.items():
274 if uuid == 'error':
275 # this rare edge case can happen if the participant is not active on the proxy side
276 # in this case we can't get information about the invoices
277 edi_user_moves.nemhandel_move_state = 'error'
278 log_message = _("Nemhandel error: %s", content['message'])
279 edi_user_moves._message_log_batch(bodies={move.id: log_message for move in edi_user_moves})
280 break
281
282 move = message_uuids[uuid]
283 if content.get('error'):
284 # "Nemhandel request not ready" error:
285 # thrown when the IAP is still processing the message
286 if content['error'].get('code') == 702:
287 continue
288
289 move.nemhandel_move_state = 'error'
290 move._message_log(body=_("Nemhandel error: %s", content['error'].get('data', {}).get('message') or content['error']['message']))
291 continue
292
293 move.nemhandel_move_state = content['state']
294 move._message_log(body=_('Nemhandel status update: %s', content['state']))
295
296 edi_user._call_nemhandel_proxy(
297 "/api/nemhandel/1/ack",
298 params={'message_uuids': list(message_uuids.keys())},
299 )
300 if need_retrigger:
301 self.env.ref('l10n_dk_nemhandel.ir_cron_nemhandel_get_message_status')._trigger()
302
303 def _nemhandel_get_participant_status(self):
304 for edi_user in self:
305 edi_user = edi_user.with_company(edi_user.company_id)
306 try:
307 proxy_user = edi_user._call_nemhandel_proxy("/api/nemhandel/1/participant_status")
308 except AccountEdiProxyError as e:
309 _logger.error('Error while updating Nemhandel participant status: %s', e)
310 continue
311
312 if proxy_user['nemhandel_state'] in {'not_registered', 'receiver', 'rejected'}:
313 edi_user.company_id.l10n_dk_nemhandel_proxy_state = proxy_user['nemhandel_state']
314
315 def _get_nemhandel_company_details(self):
316 self.ensure_one()
317 return {
318 'nemhandel_company_name': self.company_id.display_name,
319 'nemhandel_company_cvr': self.company_id.vat[2:] if self.company_id.vat[:2].isalpha() else self.company_id.vat,
320 'nemhandel_country_code': self.company_id.country_id.code,
321 'nemhandel_phone_number': self.company_id.nemhandel_phone_number,
322 'nemhandel_contact_email': self.company_id.nemhandel_contact_email,
323 'nemhandel_webhook_endpoint': self.company_id._get_nemhandel_webhook_endpoint(),
324 'nemhandel_webhook_token': self._generate_nemhandel_webhook_token(),
325 }
326
327 def _nemhandel_register_as_receiver(self):
328 self.ensure_one()
329
330 company = self.company_id
331
332 if company.l10n_dk_nemhandel_proxy_state != 'in_verification':
333 # a participant can only try registering as a receiver if they are not registered
334 nemhandel_state_translated = dict(company._fields['l10n_dk_nemhandel_proxy_state'].selection)[company.l10n_dk_nemhandel_proxy_state]
335 raise UserError(_('Cannot register a user with a %s application', nemhandel_state_translated))
336
337 company_vat = company.vat[2:] if company.vat and company.vat[:2].isalpha() else company.vat
338 if company.nemhandel_identifier_type == '0184' and company_vat != company.nemhandel_identifier_value:
339 raise ValidationError(_("If you try to register with your CVR, please make sure your company has the same VAT"))
340
341 self._check_user_on_alternative_service()
342
343 self._call_nemhandel_proxy(endpoint='/api/nemhandel/1/register_participant')
344 company.l10n_dk_nemhandel_proxy_state = 'receiver'
345
346 def _nemhandel_deregister_participant(self):
347 self.ensure_one()
348
349 if self.company_id.l10n_dk_nemhandel_proxy_state == 'receiver':
350 # fetch all documents and message statuses before unlinking the edi user
351 # so that the invoices are acknowledged
352 self._cron_nemhandel_get_message_status()
353 self._cron_nemhandel_get_new_documents()
354 if not tools.config['test_enable'] and not modules.module.current_test:
355 self.env.cr.commit()
356
357 if self.company_id.l10n_dk_nemhandel_proxy_state != 'not_registered':
358 try:
359 self._call_nemhandel_proxy(endpoint='/api/nemhandel/1/cancel_nemhandel_registration')
360 except UserError as e:
361 if e.args and e.args[0] != "The user doesn't exist on the proxy":
362 raise
363
364 self.company_id.l10n_dk_nemhandel_proxy_state = 'not_registered'
365 self.unlink()
366
367 def _generate_nemhandel_webhook_token(self):
368 self.ensure_one()
369 expiration = 30 * 24 # in 30 days
370 msg = [self.id, self.company_id._get_nemhandel_webhook_endpoint()]
371 payload = tools.hash_sign(self.sudo().env, 'account_nemhandel_webhook', msg, expiration_hours=expiration)
372 return payload
373
374 @api.model
375 def _get_nemhandel_user_from_token(self, token: str, url: str):
376 try:
377 if not (payload := tools.verify_hash_signed(self.sudo().env, 'account_nemhandel_webhook', token)):
378 return None
379 except ValueError:
380 return None
381 else:
382 user_id, endpoint = payload
383 if not url.startswith(endpoint):
384 return None
385 return self.browse(user_id).exists()
386
387 def _nemhandel_reset_webhook(self):
388 for edi_user in self:
389 edi_user._call_nemhandel_proxy(
390 '/api/nemhandel/1/set_webhook',
391 params={
392 'webhook_url': edi_user.company_id._get_nemhandel_webhook_endpoint(),
393 'token': edi_user._generate_nemhandel_webhook_token()
394 }
395 )