Debian Codegraph @

addons/l10n_dk_nemhandel/tests/test_nemhandel_messages.py

raw
1 import json
2 from base64 import b64encode
3 from contextlib import contextmanager
4 from requests import PreparedRequest, Response, Session
5 from unittest.mock import patch
6 from urllib import parse
7
8 from odoo import Command
9 from odoo.exceptions import UserError
10 from odoo.tests.common import tagged, freeze_time
11 from odoo.tools.misc import file_open
12
13 from odoo.addons.account.tests.test_account_move_send import TestAccountMoveSendCommon
14
15
16 ID_CLIENT = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
17 FAKE_UUID = ['yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy',
18 'zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz']
19 FILE_PATH = 'l10n_dk_nemhandel/tests/assets'
20
21
22 @freeze_time('2023-01-01')
23 @tagged('post_install_l10n', 'post_install', '-at_install')
24 class TestNemhandelMessage(TestAccountMoveSendCommon):
25
26 @classmethod
27 @TestAccountMoveSendCommon.setup_country('dk')
28 def setUpClass(cls):
29 super().setUpClass()
30 cls.env['ir.config_parameter'].sudo().set_param('l10n_dk_nemhandel.edi.mode', 'test')
31
32 cls.env.company.write({
33 'street': 'Boomvej 42',
34 'nemhandel_identifier_type': '0088',
35 'nemhandel_identifier_value': '5798009811512',
36 'vat': 'DK58403288',
37 'l10n_dk_nemhandel_proxy_state': 'receiver',
38 })
39
40 edi_identification = cls.env['account_edi_proxy_client.user']._get_proxy_identification(cls.env.company, 'nemhandel')
41 cls.private_key = cls.env['certificate.key'].create({
42 'name': 'Test key Nemhandel',
43 'content': b64encode(file_open(f'{FILE_PATH}/private_key.pem', 'rb').read()),
44 })
45 cls.proxy_user = cls.env['account_edi_proxy_client.user'].create({
46 'id_client': ID_CLIENT,
47 'proxy_type': 'nemhandel',
48 'edi_mode': 'test',
49 'edi_identification': edi_identification,
50 'private_key_id': cls.private_key.id,
51 'refresh_token': FAKE_UUID[0],
52 })
53
54 cls.invalid_partner, cls.valid_partner = cls.env['res.partner'].create([{
55 'name': 'Wintermute',
56 'city': 'Copenhagen',
57 'country_id': cls.env.ref('base.dk').id,
58 'invoice_sending_method': 'nemhandel',
59 'vat': 'DK12345674',
60 }, {
61 'name': 'Molly',
62 'street': 'Arfvej 7',
63 'city': 'Copenhagen',
64 'email': '[email protected]',
65 'country_id': cls.env.ref('base.dk').id,
66 'invoice_sending_method': 'nemhandel',
67 'vat': 'DK12345666',
68 }])
69
70 cls.env['res.partner.bank'].create({
71 'acc_number': '0144748555',
72 'partner_id': cls.env.company.partner_id.id,
73 })
74
75 def create_move(self, partner, company=None):
76 return self.env['account.move'].create({
77 'move_type': 'out_invoice',
78 'company_id': (company or self.env.company).id,
79 'partner_id': partner.id,
80 'date': '2023-01-01',
81 'ref': 'Test reference',
82 'invoice_line_ids': [
83 Command.create({
84 'name': 'line 1',
85 'product_id': self.product_a.id,
86 }),
87 Command.create({
88 'name': 'line 2',
89 'product_id': self.product_a.id,
90 }),
91 ],
92 })
93
94 @classmethod
95 def _get_mock_data(cls, error=False, nr_invoices=1):
96 proxy_documents = {
97 FAKE_UUID[0]: {
98 'accounting_supplier_party': False,
99 'filename': 'test_outgoing.xml',
100 'enc_key': '',
101 'document': '',
102 'state': 'done' if not error else 'error',
103 'direction': 'outgoing',
104 'document_type': 'Invoice',
105 },
106 FAKE_UUID[1]: {
107 'accounting_supplier_party': '0184:16356706',
108 'filename': 'test_incoming',
109 'enc_key': file_open(f'{FILE_PATH}/enc_key', mode='rb').read(),
110 'document': b64encode(file_open(f'{FILE_PATH}/document', mode='rb').read()),
111 'state': 'done' if not error else 'error',
112 'direction': 'incoming',
113 'document_type': 'Invoice',
114 },
115 }
116
117 responses = {
118 '/api/nemhandel/1/send_document': {'result': {'messages': [{'message_uuid': FAKE_UUID[0]}] * nr_invoices}},
119 '/api/nemhandel/1/ack': {'result': {}},
120 '/api/nemhandel/1/get_all_documents': {'result': {
121 'messages': [
122 {
123 'accounting_supplier_party': '0184:16356706',
124 'filename': 'test_incoming.xml',
125 'uuid': FAKE_UUID[1],
126 'state': 'done',
127 'direction': 'incoming',
128 'document_type': 'Invoice',
129 'sender': '0184:16356706',
130 'receiver': '0088:5798009811512',
131 'timestamp': '2022-12-30',
132 'error': False if not error else 'Test error',
133 }
134 ],
135 }}
136 }
137 return proxy_documents, responses
138
139 @contextmanager
140 def _set_context(self, other_context):
141 cls = self.__class__
142 env = cls.env(context=dict(cls.env.context, **other_context))
143 with patch.object(cls, "env", env):
144 yield
145
146 @classmethod
147 def _request_handler(cls, s: Session, r: PreparedRequest, /, **kw):
148 response = Response()
149 response.status_code = 200
150 if r.path_url.startswith('/api/peppol/1/lookup'):
151 nemhandel_identifier = parse.parse_qs(r.path_url.rsplit('?')[1])['peppol_identifier'][0].lower()
152 url_quoted_nemhandel_identifier = parse.quote_plus(nemhandel_identifier)
153 if nemhandel_identifier.endswith('5798009811512'):
154 response.status_code = 200
155 response.json = lambda: {
156 "result": {
157 'identifier': nemhandel_identifier,
158 'smp_base_url': "https://smp-demo.nemhandel.dk",
159 'ttl': 60,
160 'service_group_url': f'http:///smp-demo.nemhandel.dk/iso6523-actorid-upis%3A%3A{url_quoted_nemhandel_identifier}',
161 'services': [
162 {
163 "href": f"https://smp-demo.nemhandel.dk/iso6523-actorid-upis%3A%3A{url_quoted_nemhandel_identifier}/services/busdox-docid-qns%3A%3Aurn%3Aoasis%3Anames%3Aspecification%3Aubl%3Aschema%3Axsd%3ACreditNote-2%3A%3ACreditNote%23%23OIOUBL-2.1%3A%3A2.1",
164 "document_id": "busdox-docid-qns::urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##OIOUBL-2.1::2.1",
165 },
166 ],
167 },
168 }
169 return response
170 if nemhandel_identifier.endswith('12345674'):
171 response.status_code = 404
172 response.json = lambda: {"error": {"code": "NOT_FOUND", "message": "no naptr record", "retryable": False}}
173 return response
174 if nemhandel_identifier.endswith('12345666'):
175 response.status_code = 200
176 response.json = lambda: {
177 "result": {
178 'identifier': nemhandel_identifier,
179 'smp_base_url': "https://smp-demo.nemhandel.dk",
180 'ttl': 60,
181 'service_group_url': f'http:///smp-demo.nemhandel.dk/iso6523-actorid-upis%3A%3A{url_quoted_nemhandel_identifier}',
182 'services': [
183 {
184 "href": f"https://smp-demo.nemhandel.dk/iso6523-actorid-upis%3A%3A{url_quoted_nemhandel_identifier}/services/busdox-docid-qns%3A%3Aurn%3Aoasis%3Anames%3Aspecification%3Aubl%3Aschema%3Axsd%3ACreditNote-2%3A%3ACreditNote%23%23OIOUBL-2.1%3A%3A2.1",
185 "document_id": "busdox-docid-qns::urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##OIOUBL-2.1::2.1",
186 },
187 ],
188 },
189 }
190 return response
191 if nemhandel_identifier.endswith('16356706'):
192 response.status_code = 200
193 response.json = lambda: {
194 "result": {
195 'identifier': nemhandel_identifier,
196 'smp_base_url': "https://smp-demo.nemhandel.dk",
197 'ttl': 60,
198 'service_group_url': f'http:///smp-demo.nemhandel.dk/iso6523-actorid-upis%3A%3A{url_quoted_nemhandel_identifier}',
199 'services': [],
200 },
201 }
202 return response
203
204 url = r.path_url.lower()
205 body = json.loads(r.body)
206 if url == '/api/nemhandel/1/send_document':
207 if not body['params']['documents']:
208 raise UserError('No documents were provided')
209 proxy_documents, responses = cls._get_mock_data(cls.env.context.get('error'), nr_invoices=len(body['params']['documents']))
210 else:
211 proxy_documents, responses = cls._get_mock_data(cls.env.context.get('error'))
212
213 if url == '/api/nemhandel/1/get_document':
214 uuid = body['params']['message_uuids'][0]
215 response.json = lambda: {'result': {uuid: proxy_documents[uuid]}}
216 return response
217
218 if url not in responses:
219 return super()._request_handler(s, r, **kw)
220 response.json = lambda: responses[url]
221 return response
222
223 def test_nemhandel_attachment_placeholders(self):
224 move = self.create_move(self.valid_partner)
225 move.action_post()
226
227 wizard = self.create_send_and_print(move, sending_methods=['email', 'nemhandel'])
228 self.assertEqual(wizard.invoice_edi_format, 'oioubl_21')
229
230 # the ubl xml placeholder should be generated
231 self._assert_mail_attachments_widget(wizard, [
232 {
233 'mimetype': 'application/pdf',
234 'name': 'INV_2023_00001.pdf',
235 'placeholder': True,
236 },
237 {
238 'mimetype': 'application/xml',
239 'name': 'INV_2023_00001_oioubl_21.xml',
240 'placeholder': True,
241 },
242 ])
243
244 wizard.sending_methods = ['nemhandel']
245 wizard.action_send_and_print()
246 self.assertEqual(self._get_mail_message(move).preview, 'The document has been sent to the Nemhandel Access Point for processing')
247
248 def test_send_nemhandel_alerts_not_valid_partner(self):
249 move = self.create_move(self.invalid_partner)
250 move.action_post()
251 wizard = self.env['account.move.send.wizard'].create({
252 'move_id': move.id,
253 })
254 self.assertEqual(self.invalid_partner.nemhandel_verification_state, 'not_valid') # not on nemhandel at all
255 self.assertFalse(wizard.sending_methods and 'nemhandel' in wizard.sending_methods) # nemhandel is not checked by default
256 self.assertTrue(wizard.sending_method_checkboxes['nemhandel']['readonly']) # can't select nemhandel
257 self.assertFalse(wizard.alerts) # there is no alerts
258
259 def test_resend_error_nemhandel_message(self):
260 # should be able to resend error invoices
261 move = self.create_move(self.valid_partner)
262 move.action_post()
263
264 wizard = self.create_send_and_print(move, default=True)
265 self.assertEqual(wizard.invoice_edi_format, 'oioubl_21')
266 self.assertTrue(wizard.sending_methods and 'nemhandel' in wizard.sending_methods)
267 with self._set_context({'error': True}):
268 wizard.action_send_and_print()
269
270 self.env['account_edi_proxy_client.user']._cron_nemhandel_get_message_status()
271 self.assertRecordValues(move, [{'nemhandel_move_state': 'error', 'nemhandel_message_uuid': FAKE_UUID[0]}])
272
273 # we can't send the ubl document again unless we regenerate the pdf
274 move.invoice_pdf_report_id.unlink()
275 wizard = self.create_send_and_print(move, default=True)
276 self.assertEqual(wizard.invoice_edi_format, 'oioubl_21')
277 self.assertTrue(wizard.sending_methods and 'nemhandel' in wizard.sending_methods)
278
279 wizard.action_send_and_print()
280
281 self.env['account_edi_proxy_client.user']._cron_nemhandel_get_message_status()
282 self.assertEqual(move.nemhandel_move_state, 'done')
283
284 def test_nemhandel_send_success_message(self):
285 # should be able to send valid invoices correctly
286 # attachment should be generated
287 # nemhandel_move_state should be set to done
288 move = self.create_move(self.valid_partner)
289 move.action_post()
290
291 wizard = self.create_send_and_print(move, default=True)
292 self.assertEqual(wizard.invoice_edi_format, 'oioubl_21')
293 self.assertTrue(wizard.sending_methods and 'nemhandel' in wizard.sending_methods)
294
295 wizard.action_send_and_print()
296
297 self.env['account_edi_proxy_client.user']._cron_nemhandel_get_message_status()
298 self.assertRecordValues(
299 move,
300 [{
301 'nemhandel_move_state': 'done',
302 'nemhandel_message_uuid': FAKE_UUID[0],
303 }],
304 )
305 self.assertTrue(bool(move.ubl_cii_xml_id))
306
307 def test_nemhandel_send_invalid_edi_user(self):
308 # an invalid edi user should not be able to send invoices via nemhandel
309 self.env.company.l10n_dk_nemhandel_proxy_state = 'rejected'
310
311 move = self.create_move(self.valid_partner)
312 move.action_post()
313
314 wizard = self.create_send_and_print(move, default=True)
315 self.assertTrue('nemhandel' not in wizard.sending_method_checkboxes)
316
317 def test_receive_error_nemhandel(self):
318 # an error nemhandel message should be created
319 with self._set_context({'error': True}):
320 self.env['account_edi_proxy_client.user']._cron_nemhandel_get_new_documents()
321
322 move = self.env['account.move'].search([('nemhandel_message_uuid', '=', FAKE_UUID[1])])
323 self.assertRecordValues(move, [{'nemhandel_move_state': 'error', 'move_type': 'in_invoice'}])
324
325 def test_receive_success_nemhandel(self):
326 # a correct move should be created
327 self.env['account_edi_proxy_client.user']._cron_nemhandel_get_new_documents()
328
329 move = self.env['account.move'].search([('nemhandel_message_uuid', '=', FAKE_UUID[1])])
330 self.assertRecordValues(move, [{'nemhandel_move_state': 'done', 'move_type': 'in_invoice'}])
331
332 def test_validate_partner_nemhandel(self):
333 new_partner = self.env['res.partner'].create({
334 'name': 'Deanna Troi',
335 'city': 'Copenhagen',
336 'country_id': self.env.ref('base.dk').id,
337 'invoice_sending_method': 'nemhandel',
338
339 })
340 self.assertRecordValues(
341 new_partner,
342 [{
343 'nemhandel_verification_state': False,
344 'nemhandel_identifier_type': '0184',
345 'nemhandel_identifier_value': False,
346 }],
347 )
348 new_partner.write({
349 'nemhandel_identifier_type': '0088',
350 'nemhandel_identifier_value': '5798009811512',
351 })
352 self.assertEqual(new_partner.nemhandel_verification_state, 'valid') # should validate automatically
353
354 new_partner.write({
355 'nemhandel_identifier_type': '0184',
356 'nemhandel_identifier_value': '12345674',
357 })
358
359 self.assertEqual(new_partner.nemhandel_verification_state, 'not_valid')
360
361 def test_nemhandel_edi_formats(self):
362 self.valid_partner.invoice_sending_method = 'nemhandel'
363 with self.assertRaises(UserError):
364 self.valid_partner.invoice_edi_format = 'ubl_bis3'
365
366 self.valid_partner.invoice_sending_method = 'email'
367 self.valid_partner.invoice_edi_format = 'ubl_bis3'
368
369 def test_nemhandel_silent_error_while_creating_xml(self):
370 """When in multi/async mode, the generation of XML can fail silently (without raising).
371 This needs to be reflected as an error and put the move in Nemhandel Error state.
372 """
373 def mocked_export_invoice_constraints(self, invoice, vals):
374 return {'test_error_key': 'test_error_description'}
375
376 self.valid_partner.invoice_edi_format = 'oioubl_21'
377 move_1 = self.create_move(self.valid_partner)
378 move_2 = self.create_move(self.valid_partner)
379 (move_1 + move_2).action_post()
380
381 wizard = self.create_send_and_print(move_1 + move_2)
382 with patch(
383 'odoo.addons.account_edi_ubl_cii.models.account_edi_xml_ubl_20.AccountEdiXmlUBL20._export_invoice_constraints',
384 mocked_export_invoice_constraints
385 ), self.enter_registry_test_mode():
386 wizard.action_send_and_print()
387 self.env.ref('account.ir_cron_account_move_send').method_direct_trigger()
388 self.assertEqual(move_1.nemhandel_move_state, 'error')