Debian Codegraph @

addons/l10n_my_edi/tests/test_submissions.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 from datetime import datetime
3 from unittest.mock import patch
4
5 from dateutil.relativedelta import relativedelta
6 from freezegun import freeze_time
7
8 from odoo import Command
9 from odoo.exceptions import UserError
10 from odoo.tests import tagged
11
12 from odoo.addons.account.tests.common import AccountTestInvoicingCommon
13 from odoo.addons.account.tests.test_account_move_send import TestAccountMoveSendCommon
14
15 CONTACT_PROXY_METHOD = 'odoo.addons.l10n_my_edi.models.account_edi_proxy_user.AccountEdiProxyClientUser._l10n_my_edi_contact_proxy'
16
17
18 @tagged('post_install_l10n', 'post_install', '-at_install')
19 class L10nMyEDITestNewSubmission(TestAccountMoveSendCommon):
20 """ The tests in this file are similar to the ones in test_submissions but use the new flow (outside of send & print)
21 to test the features of the EDI.
22 These will fully replace the old tests in master.
23 """
24
25 @classmethod
26 @AccountTestInvoicingCommon.setup_country('my')
27 def setUpClass(cls):
28 super().setUpClass()
29
30 # TIN number is required
31 cls.company_data['company'].write({
32 'vat': 'C2584563200',
33 'l10n_my_edi_mode': 'test',
34 'l10n_my_edi_industrial_classification': cls.env['l10n_my_edi.industry_classification'].search([('code', '=', '01111')]).id,
35 'l10n_my_identification_type': 'BRN',
36 'l10n_my_identification_number': '202001234567',
37 'state_id': cls.env.ref('base.state_my_jhr').id,
38 'street': 'that one street, 5',
39 'city': 'Main city',
40 'phone': '+60123456789',
41 })
42 cls.partner_a.write({
43 'vat': 'C2584563201',
44 'l10n_my_identification_type': 'BRN',
45 'l10n_my_identification_number': '202001234568',
46 'country_id': cls.env.ref('base.my').id,
47 'state_id': cls.env.ref('base.state_my_jhr').id,
48 'street': 'that other street, 3',
49 'city': 'Main city',
50 'phone': '+60123456786',
51 'ref': "MY-REF",
52 })
53 cls.product_a.l10n_my_edi_classification_code = "001"
54
55 # We can reuse this invoice for the flow tests.
56 cls.basic_invoice = cls.init_invoice('out_invoice', taxes=cls.company_data['default_tax_sale'], products=cls.product_a)
57 cls.basic_invoice.action_post()
58
59 # For simplicity, we will test everything using a 'test' mode user, but we create it using demo to avoid triggering any api calls.
60 cls.proxy_user = cls.env['account_edi_proxy_client.user']._register_proxy_user(cls.company_data['company'], 'l10n_my_edi', 'demo')
61 cls.proxy_user.edi_mode = 'test'
62
63 @freeze_time('2024-07-15 10:00:00')
64 def test_01_new_basic_submission(self):
65 """
66 This tests the most basic flow: an invoice is successfully sent to the MyInvois platform, and then pass validation.
67 """
68 # Send to MyInvois
69 with patch(CONTACT_PROXY_METHOD, new=self._test_01_mock):
70 self.basic_invoice.action_l10n_my_edi_send_invoice()
71
72 myinvois_document = self.basic_invoice.l10n_my_edi_document_ids._get_active_myinvois_document()
73 # Now that the invoice has been sent successfully, we assert that some info have been saved correctly.
74 self.assertRecordValues(
75 myinvois_document,
76 [{
77 'myinvois_state': 'valid',
78 'myinvois_validation_time': datetime.strptime('2024-07-15 05:00:00', '%Y-%m-%d %H:%M:%S'),
79 'myinvois_document_long_id': '123-789-654',
80 'myinvois_submission_uid': '123456789',
81 'myinvois_external_uuid': '123458974513518',
82 }],
83 )
84
85 # We will test the actual file in another test class, but we ensure it was generated as expected.
86 self.assertTrue(myinvois_document.myinvois_file_id)
87
88 @freeze_time('2024-07-15 10:00:00')
89 def test_02_new_failed_submission(self):
90 """
91 This test will test a flow where the submission itself (not the documents inside) fails for any reason.
92 A general error as such should be handled, but is not expected and should be treated as a bug on our side.
93
94 As we submit a single invoice, we expect a UserError to be raised.
95 """
96 with patch(CONTACT_PROXY_METHOD, new=self._test_02_mock):
97 with self.assertRaisesRegex(UserError, 'Server error; If the problem persists, please contact the Odoo support.'):
98 self.basic_invoice.action_l10n_my_edi_send_invoice()
99
100 @freeze_time('2024-07-15 10:00:00')
101 def test_03_new_failed_document_submission(self):
102 """
103 Unlike the previous test, this will test the use case where the submission is done correctly but the document
104 itself is incorrect.
105
106 This would be due to an incorrect supplier tin for example.
107 """
108 with patch(CONTACT_PROXY_METHOD, new=self._test_03_mock):
109 # We want to assert that some values are saved during the commit, which won't happen during a test if we raise all the way.
110 # So instead of doing an assertRaises, we will catch the error (ensuring that it does happen) then continue.
111 try:
112 self.basic_invoice.action_l10n_my_edi_send_invoice()
113 except UserError:
114 pass # We expect a user error to be raised here.
115 else:
116 assert False, 'The expected user error did not raise.'
117
118 # When such error occurs, we expect the hash and retry time to be set, has we need to avoid allowing a user to
119 # resend an invoice right away without any changes.
120 self.assertRecordValues(
121 self.basic_invoice.l10n_my_edi_document_ids[0],
122 [{
123 'myinvois_error_document_hash': 'HX164532#=',
124 'myinvois_retry_at': '2024-07-15 10:10:00',
125 'myinvois_state': 'invalid',
126 }],
127 )
128
129 @freeze_time('2024-07-15 10:00:00')
130 def test_04_new_cancellation(self):
131 """
132 An invoice can be cancelled up to 72h after validation.
133 Test the cancellation flow when it works well.
134 """
135 with patch(CONTACT_PROXY_METHOD, new=self._test_04_mock):
136 self.basic_invoice.action_l10n_my_edi_send_invoice()
137
138 # Open the wizard successfully, 72h did not pass
139 action = self.basic_invoice.button_request_cancel()
140 wizard = self.env[action['res_model']].with_context(action['context']).create({
141 'reason': 'Discount not applied',
142 })
143 # Cancel the invoice
144 wizard.button_request_update()
145 self.assertEqual(self.basic_invoice.state, 'cancel')
146 self.assertEqual(self.basic_invoice.l10n_my_edi_document_ids[0].myinvois_state, 'cancelled')
147
148 @freeze_time('2024-07-15 10:00:00')
149 def test_05_new_cancellation_failures(self):
150 """
151 Tests two scenarios when cancellation fails.
152 First on is trying to launch the wizard past the 72h mark, and then an actual cancellation error.
153 """
154 with patch(CONTACT_PROXY_METHOD, new=self._test_05_mock):
155 self.basic_invoice.action_l10n_my_edi_send_invoice()
156
157 self.basic_invoice.l10n_my_edi_document_ids[0].myinvois_validation_time = datetime.strptime('2024-07-12 10:00:00', '%Y-%m-%d %H:%M:%S')
158
159 # More than 72h, it failed
160 with self.assertRaises(UserError, msg='It has been more than 72h since the invoice validation, you can no longer cancel it.\nInstead, you should issue a debit or credit note.'):
161 self.basic_invoice.button_request_cancel()
162
163 self.basic_invoice.l10n_my_edi_document_ids[0].myinvois_validation_time = datetime.now()
164 action = self.basic_invoice.button_request_cancel()
165 wizard = self.env[action['res_model']].with_context(action['context']).create({
166 'reason': 'Discount not applied',
167 })
168 # Cancel the invoice. It failed during cancellation and logged an error.
169 wizard.button_request_update()
170 self.assertEqual(self.basic_invoice.message_ids[0].preview, 'You do not have the permission to update this invoice.')
171
172 @freeze_time('2024-07-15 10:00:00')
173 def test_06_new_invalid_reset(self):
174 """
175 Test that an invalid invoice can be reset, and that after reset the edi related fields are correctly reset beside the hash and retry time.
176 Also test that the invoice can be sent again after correction.
177 """
178 with patch(CONTACT_PROXY_METHOD, new=self._test_06_mock):
179 # We want to assert that some values are saved during the commit, which won't happen during a test if we raise all the way.
180 # So instead of doing an assertRaises, we will catch the error (ensuring that it does happen) then continue.
181 try:
182 self.basic_invoice.action_l10n_my_edi_send_invoice()
183 except UserError:
184 pass # We expect a user error to be raised here.
185 else:
186 assert False, 'The expected user error did not raise.'
187
188 # Invalid invoices are cancelled automatically.
189 self.assertEqual(self.basic_invoice.state, 'cancel')
190 self.basic_invoice.button_draft()
191
192 self.assertRecordValues(
193 self.basic_invoice.l10n_my_edi_document_ids[0],
194 [{
195 'myinvois_error_document_hash': 'HX164532#=',
196 'myinvois_retry_at': '2024-07-15 10:10:00',
197 'myinvois_state': 'invalid',
198 'myinvois_validation_time': False,
199 'myinvois_submission_uid': '123456789',
200 'myinvois_external_uuid': False,
201 }],
202 )
203
204 # ... we change whatever
205 self.basic_invoice.action_post()
206
207 self.basic_invoice.action_l10n_my_edi_send_invoice()
208
209 self.assertRecordValues(
210 self.basic_invoice,
211 [{
212 'l10n_my_edi_state': 'valid',
213 }],
214 )
215
216 @freeze_time('2024-07-15 10:00:00')
217 def test_07_new_pending_submission(self):
218 """
219 Test the case of a submission status being unavailable at the time of submission.
220 No errors should be raised, and it should be handled by the cron later on.
221 """
222 self.get_submission_status_count = 0 # Needed for the mock; we get it twice. Once during submission and once from the cron.
223 with patch(CONTACT_PROXY_METHOD, new=self._test_07_mock):
224 self.basic_invoice.action_l10n_my_edi_send_invoice()
225
226 self.assertRecordValues(
227 self.basic_invoice.l10n_my_edi_document_ids[0],
228 [{
229 'myinvois_state': 'in_progress',
230 'myinvois_submission_uid': '123456789',
231 'myinvois_external_uuid': '123458974513518',
232 }],
233 )
234
235 # ... some time later, the cron runs.
236 self.env['myinvois.document']._myinvois_statuses_update_cron()
237
238 # The update should be reflected on the move.
239 self.assertRecordValues(
240 self.basic_invoice.l10n_my_edi_document_ids[0],
241 [{
242 'myinvois_state': 'valid',
243 'myinvois_validation_time': datetime.strptime('2024-07-15 05:00:00', '%Y-%m-%d %H:%M:%S'),
244 'myinvois_document_long_id': '123-789-654',
245 }],
246 )
247
248 @freeze_time('2024-07-15 10:00:00')
249 def test_08_new_mass_submission(self):
250 """ This test will ensure that invoices are split as expected if there are more than SUBMISSION_MAX_SIZE at once. """
251 # For performance purposes we will not create 100 invoices here, but instead patch SUBMISSION_MAX_SIZE to make batches of two invoices.
252 self.submission_count = 0
253 invoice_vals = []
254 for i in range(1, 10):
255 invoice_vals.append({
256 'move_type': 'out_invoice',
257 'partner_id': self.partner_a.id,
258 'invoice_line_ids': [
259 Command.create({
260 'product_id': self.product_a.id,
261 'tax_ids': [Command.set(self.company_data['default_tax_sale'].ids)],
262 }),
263 ],
264 })
265
266 self.submission_invoice = self.env['account.move'].create(invoice_vals)
267 self.submission_invoice.action_post()
268 self.submission_invoice |= self.basic_invoice
269
270 with patch(CONTACT_PROXY_METHOD, new=self._test_08_mock), \
271 patch('odoo.addons.l10n_my_edi.models.myinvois_document.SUBMISSION_MAX_SIZE', 2):
272 self.submission_invoice.action_l10n_my_edi_send_invoice()
273
274 # we have 10 invoices, with a max size of 2 we expect 5 different submissions.
275 self.assertEqual(self.submission_count, 5)
276
277 @freeze_time('2024-07-15 10:00:00')
278 def test_09_new_fetch_status(self):
279 """ After pushing an invoice, we can optionally fetch the status manually if needed. """
280 with patch(CONTACT_PROXY_METHOD, new=self._test_09_mock):
281 self.basic_invoice.action_l10n_my_edi_send_invoice()
282
283 self.assertRecordValues(
284 self.basic_invoice.l10n_my_edi_document_ids[0],
285 [{
286 'myinvois_state': 'in_progress',
287 'myinvois_submission_uid': '123456789',
288 'myinvois_external_uuid': '123458974513518',
289 }],
290 )
291
292 # ... some time later, the user does not want to wait for the cron and press the button.
293 self.basic_invoice.action_l10n_my_edi_update_status()
294
295 # The update should be reflected on the move.
296 self.assertEqual(self.basic_invoice.l10n_my_edi_state, 'valid')
297
298 @freeze_time('2024-07-15 10:00:00')
299 def test_10_new_full_rejection_flow_invoice(self):
300 """
301 We issue an invoice to our customer with the wrong address.
302 The customer reject it for that reason.
303 We receive the updated status later on, and cancel the invoice to issue a new one later.
304 """
305 with patch(CONTACT_PROXY_METHOD, new=self._test_10_mock):
306 # Issue the invoice, and get a valid status.
307 self.basic_invoice.action_l10n_my_edi_send_invoice()
308 # Update the status, and receive a rejection request.
309 self.basic_invoice.action_l10n_my_edi_update_status()
310 self.assertEqual(self.basic_invoice.l10n_my_edi_state, 'rejected')
311 # We then cancel the invoice as the reason is valid.
312 action = self.basic_invoice.button_request_cancel()
313 wizard = self.env[action['res_model']].with_context(action['context']).create({
314 'reason': 'Wrong address',
315 })
316 # Cancel the invoice
317 wizard.button_request_update()
318 self.assertEqual(self.basic_invoice.l10n_my_edi_document_ids[0].myinvois_state, 'cancelled')
319
320 @freeze_time('2024-07-15 10:00:00')
321 def test_11_qr_code_generation(self):
322 """ Basic test that ensure that a valid invoice can generate a QR code. """
323 with patch(CONTACT_PROXY_METHOD, new=self._test_11_mock):
324 self.basic_invoice.action_l10n_my_edi_send_invoice()
325
326 qr_data_uri = self.basic_invoice._generate_myinvois_qr_code()
327 self.assertTrue(qr_data_uri)
328
329 def test_12_multiple_moves_with_one_failed_submission(self):
330 """Test that an error happening in the middle of multiple submissions is correctly handled."""
331 self.submission_count = 0
332 invoice_vals = []
333 for i in range(1, 5):
334 invoice_vals.append({
335 'move_type': 'out_invoice',
336 'partner_id': self.partner_a.id,
337 'invoice_line_ids': [
338 Command.create({
339 'product_id': self.product_a.id,
340 'tax_ids': [Command.set(self.company_data['default_tax_sale'].ids)],
341 }),
342 ],
343 })
344
345 self.submission_invoice = self.env['account.move'].create(invoice_vals)
346 self.submission_invoice.action_post()
347 self.submission_invoice |= self.basic_invoice
348
349 with patch(CONTACT_PROXY_METHOD, new=self._test_12_mock), \
350 patch('odoo.addons.l10n_my_edi.models.myinvois_document.SUBMISSION_MAX_SIZE', 1):
351 self.submission_invoice.action_l10n_my_edi_send_invoice()
352
353 self.assertEqual(self.submission_count, 5)
354 valid_invoices = self.submission_invoice.filtered(lambda inv: inv.l10n_my_edi_state == "valid")
355 self.assertEqual(len(valid_invoices), 4, 'The four invoices are in a valid state.')
356
357 failed_invoice = self.submission_invoice.filtered(lambda inv: not inv.l10n_my_edi_state)
358 self.assertEqual(len(failed_invoice), 1, 'One invoice has no state.')
359
360 def test_13_multiple_cron_runs(self):
361 """
362 Simulate the cron running more than once; ensure that we correctly update l10n_my_edi_retry_at for valid invoices.
363 For the purpose of the test, we will use two separate submissions.
364 """
365 all_invoices = self.env['account.move']
366 # First submission of 5 invoices
367 with patch(CONTACT_PROXY_METHOD, new=self._test_13_mock_first_submission):
368 first_batch = self.env['account.move']
369 for i in range(5):
370 first_batch |= self.init_invoice(
371 'out_invoice', taxes=self.company_data['default_tax_sale'], products=self.product_a, post=True,
372 )
373 with freeze_time('2024-07-15 10:00:00'):
374 first_batch.action_l10n_my_edi_send_invoice()
375
376 all_invoices |= first_batch
377
378 # Second submission of 5 invoices.
379 self.submission_status_count = 0
380 with patch(CONTACT_PROXY_METHOD, new=self._test_13_mock):
381 second_batch = self.basic_invoice
382 for i in range(4):
383 second_batch |= self.init_invoice(
384 'out_invoice', taxes=self.company_data['default_tax_sale'], products=self.product_a, post=True,
385 )
386 with freeze_time('2024-07-15 10:00:00'):
387 second_batch.action_l10n_my_edi_send_invoice()
388 self.submission_status_count += 1 # Done once during the sending flow
389
390 all_invoices |= second_batch
391
392 with patch(CONTACT_PROXY_METHOD, new=self._test_13_mock):
393 with freeze_time('2024-07-15 10:00:00'):
394 # We use multiple invoices to test the cron logic, but all of them will always keep a same status so we can just validate the one.
395 self.assertRecordValues(
396 self.basic_invoice.l10n_my_edi_document_ids[0],
397 [{
398 'myinvois_state': 'in_progress',
399 'myinvois_submission_uid': '123456789',
400 'myinvois_external_uuid': '123458974513510',
401 }],
402 )
403
404 # ... some time later, the cron runs.
405 self.env['myinvois.document']._myinvois_statuses_update_cron()
406 self.submission_status_count += 1
407
408 # The move got updated to valid, and the retry time should have been set.
409 self.assertRecordValues(
410 self.basic_invoice.l10n_my_edi_document_ids[0],
411 [{
412 'myinvois_state': 'valid',
413 'myinvois_validation_time': datetime.strptime('2024-07-15 05:00:00', '%Y-%m-%d %H:%M:%S'),
414 'myinvois_document_long_id': '123-789-654',
415 'myinvois_retry_at': '2024-07-15 11:00:00',
416 }],
417 )
418
419 with freeze_time('2024-07-15 10:01:00'):
420 # We have more invoices to process, the cron got triggered again. Our invoice won't trigger an API call
421 self.env['myinvois.document']._myinvois_statuses_update_cron() # If failed to avoid the query, the mock method will raise.
422 self.submission_status_count += 1
423
424 with freeze_time('2024-07-15 11:00:00'):
425 # One hour later, the next cron run starts and our invoice is updated again
426 self.env['myinvois.document']._myinvois_statuses_update_cron()
427 self.submission_status_count += 1
428 # We should have updated the status again, and thus pushed the l10n_my_edi_retry_at time to one hour later.
429 self.assertRecordValues(
430 self.basic_invoice.l10n_my_edi_document_ids[0],
431 [{
432 'myinvois_state': 'valid',
433 'myinvois_validation_time': datetime.strptime('2024-07-15 05:00:00', '%Y-%m-%d %H:%M:%S'),
434 'myinvois_document_long_id': '123-789-654',
435 'myinvois_retry_at': '2024-07-15 12:00:00',
436 }],
437 )
438
439 # -------------------------------------------------------------------------
440 # Patched methods
441 # -------------------------------------------------------------------------
442
443 def _test_01_mock(self, endpoint, params):
444 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
445 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
446 return {
447 'submission_uid': '123456789',
448 'documents': [{
449 'move_id': params['documents'][0]['move_id'],
450 'uuid': '123458974513518',
451 'success': True,
452 }],
453 }
454 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
455 return {
456 'statuses': {
457 '123458974513518': {
458 'status': 'valid',
459 'reason': '',
460 'long_id': '123-789-654',
461 'valid_datetime': '2024-07-15T05:00:00Z',
462 },
463 },
464 'document_count': 1,
465 }
466 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
467
468 def _test_02_mock(self, endpoint, params):
469 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
470 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
471 return {
472 'error': {
473 'reference': 'internal_server_error',
474 'data': {},
475 },
476 }
477 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
478
479 def _test_03_mock(self, endpoint, params):
480 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
481 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
482 return {
483 'submission_uid': '123456789',
484 'documents': [{
485 'move_id': params['documents'][0]['move_id'],
486 'success': False,
487 'errors': [{
488 'reference': 'Y503',
489 'target': 'TIN',
490 }],
491 'error_document_hash': 'HX164532#=',
492 'retry_at': datetime.now() + relativedelta(minutes=10),
493 }],
494 }
495 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
496
497 def _test_04_mock(self, endpoint, params):
498 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
499 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
500 return {
501 'submission_uid': '123456789',
502 'documents': [{
503 'move_id': params['documents'][0]['move_id'],
504 'uuid': '123458974513518',
505 'success': True,
506 }],
507 }
508 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
509 return {
510 'statuses': {
511 '123458974513518': {
512 'status': 'valid',
513 'reason': '',
514 'long_id': '',
515 'valid_datetime': '2024-07-15T13:15:10Z',
516 },
517 },
518 'document_count': 1,
519 }
520 if endpoint == 'api/l10n_my_edi/1/update_status':
521 return {
522 'success': True,
523 }
524 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
525
526 def _test_05_mock(self, endpoint, params):
527 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
528 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
529 return {
530 'submission_uid': '123456789',
531 'documents': [{
532 'move_id': params['documents'][0]['move_id'],
533 'uuid': '123458974513518',
534 'success': True,
535 }],
536 }
537 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
538 return {
539 'statuses': {
540 '123458974513518': {
541 'status': 'valid',
542 'reason': '',
543 'long_id': '',
544 'valid_datetime': '2024-07-15T13:15:10Z',
545 },
546 },
547 'document_count': 1,
548 }
549 if endpoint == 'api/l10n_my_edi/1/update_status':
550 return {
551 'error': {
552 'reference': 'update_forbidden',
553 'data': {},
554 },
555 }
556 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
557
558 def _test_06_mock(self, endpoint, params):
559 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
560 if endpoint == 'api/l10n_my_edi/1/submit_invoices' and not params['documents'][0]['error_document_hash']:
561 return {
562 'submission_uid': '123456789',
563 'documents': [{
564 'move_id': params['documents'][0]['move_id'],
565 'success': False,
566 'errors': [{
567 'reference': 'Y503',
568 'target': 'TIN',
569 }],
570 'error_document_hash': 'HX164532#=',
571 'retry_at': datetime.now() + relativedelta(minutes=10),
572 }],
573 }
574 if endpoint == 'api/l10n_my_edi/1/submit_invoices' and params['documents'][0]['error_document_hash']:
575 return {
576 'submission_uid': '123456789',
577 'documents': [{
578 'move_id': params['documents'][0]['move_id'],
579 'uuid': '123458974513518',
580 'success': True,
581 }],
582 }
583 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
584 return {
585 'statuses': {
586 '123458974513518': {
587 'status': 'valid',
588 'reason': '',
589 'long_id': '',
590 'valid_datetime': '2024-07-15T05:00:00Z',
591 },
592 },
593 'document_count': 1,
594 }
595 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
596
597 def _test_07_mock(self, endpoint, params):
598 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
599 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
600 return {
601 'submission_uid': '123456789',
602 'documents': [{
603 'move_id': params['documents'][0]['move_id'],
604 'uuid': '123458974513518',
605 'success': True,
606 }],
607 }
608 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses' and self.get_submission_status_count < 3:
609 self.get_submission_status_count += 1
610 return {
611 'statuses': {
612 '123458974513518': {
613 'status': 'in_progress',
614 'reason': '',
615 'long_id': '',
616 'valid_datetime': '',
617 },
618 },
619 'document_count': 1,
620 }
621 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses' and self.get_submission_status_count == 3:
622 self.get_submission_status_count += 1
623 return {
624 'statuses': {
625 '123458974513518': {
626 'status': 'valid',
627 'reason': '',
628 'long_id': '123-789-654',
629 'valid_datetime': '2024-07-15T05:00:00Z',
630 },
631 },
632 'document_count': 1,
633 }
634 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
635
636 def _test_08_mock(self, endpoint, params):
637 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
638 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
639 # While there are easier ways, holding a count helps make it easy to test many loops.
640 self.submission_count += 1
641 return {
642 'submission_uid': str(123456789 + self.submission_count),
643 'documents': [{
644 'move_id': document['move_id'],
645 'uuid': str(123458974513519 + i + self.submission_count),
646 'success': True,
647 } for i, document in enumerate(params['documents'])],
648 }
649 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
650 documents = self.submission_invoice.l10n_my_edi_document_ids.grouped('myinvois_submission_uid').get(params['submission_uid'])
651 return {
652 'statuses': {
653 document.myinvois_external_uuid: {
654 'status': 'valid',
655 'reason': '',
656 'long_id': '',
657 'valid_datetime': '2024-07-15T05:00:00Z',
658 } for document in documents
659 },
660 'document_count': 1,
661 }
662 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
663
664 def _test_09_mock(self, endpoint, params):
665 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
666 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
667 return {
668 'submission_uid': '123456789',
669 'documents': [{
670 'move_id': params['documents'][0]['move_id'],
671 'uuid': '123458974513518',
672 'success': True,
673 }],
674 }
675 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
676 return {
677 'statuses': {
678 '123458974513518': {
679 'status': 'in_progress',
680 'reason': '',
681 'long_id': '',
682 'valid_datetime': '',
683 },
684 },
685 'document_count': 1,
686 }
687 if endpoint == 'api/l10n_my_edi/1/get_status':
688 return {
689 'status': 'valid',
690 'status_reason': '',
691 'long_id': '',
692 'valid_datetime': '2024-07-15T05:00:00Z',
693 }
694 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
695
696 def _test_10_mock(self, endpoint, params):
697 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
698 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
699 return {
700 'submission_uid': '123456789',
701 'documents': [{
702 'move_id': params['documents'][0]['move_id'],
703 'uuid': '123458974513518',
704 'success': True,
705 }],
706 }
707 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
708 return {
709 'statuses': {
710 '123458974513518': {
711 'status': 'valid',
712 'reason': '',
713 'long_id': '',
714 'valid_datetime': '2024-07-15T05:00:00Z',
715 },
716 },
717 'document_count': 1,
718 }
719 if endpoint == 'api/l10n_my_edi/1/get_status':
720 return {
721 'status': 'rejected',
722 'status_reason': 'Wrong address',
723 'long_id': '',
724 'valid_datetime': '',
725 }
726 if endpoint == 'api/l10n_my_edi/1/update_status':
727 return {
728 'success': True,
729 }
730 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
731
732 def _test_11_mock(self, endpoint, params):
733 """ Basic mocked method that simulate what the proxy would return depending on the endpoint. """
734 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
735 return {
736 'submission_uid': '123456789',
737 'documents': [{
738 'move_id': params['documents'][0]['move_id'],
739 'uuid': '123458974513518',
740 'success': True,
741 }],
742 }
743 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
744 return {
745 'statuses': {
746 '123458974513518': {
747 'status': 'valid',
748 'reason': '',
749 'long_id': '123-789-654',
750 'valid_datetime': '2024-07-15T05:00:00Z',
751 },
752 },
753 'document_count': 1,
754 }
755 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
756
757 def _test_12_mock(self, endpoint, params):
758 """ Mock response simulating multiple invoice submissions where one fails. """
759 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
760 self.submission_count += 1
761 if self.submission_count == 5:
762 return {
763 'error': {
764 'reference': 'internal_server_error',
765 'data': {},
766 },
767 }
768 return {
769 'submission_uid': str(123456789 + self.submission_count),
770 'documents': [{
771 'move_id': document['move_id'],
772 'uuid': str(123458974513519 + i + self.submission_count),
773 'success': True,
774 } for i, document in enumerate(params['documents'])],
775 }
776 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
777 documents = self.submission_invoice.l10n_my_edi_document_ids.grouped('myinvois_submission_uid').get(params['submission_uid'])
778 return {
779 'statuses': {
780 document.myinvois_external_uuid: {
781 'status': 'valid',
782 'reason': '',
783 'long_id': '',
784 'valid_datetime': '2024-07-15T05:00:00Z',
785 } for document in documents
786 },
787 'document_count': 1,
788 }
789 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
790
791 def _test_13_mock_first_submission(self, endpoint, params):
792 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
793 res = {
794 'submission_uid': '123456788',
795 'documents': [],
796 }
797 for i, document in enumerate(params['documents']):
798 res['documents'].append({
799 'move_id': document['move_id'],
800 'uuid': f'12345897451350{i}',
801 'success': True,
802 })
803 return res
804 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses':
805 return {
806 'statuses': {
807 '123458974513500': {
808 'status': 'in_progress',
809 'reason': '',
810 'long_id': '',
811 'valid_datetime': '',
812 },
813 '123458974513501': {
814 'status': 'in_progress',
815 'reason': '',
816 'long_id': '',
817 'valid_datetime': '',
818 },
819 '123458974513502': {
820 'status': 'in_progress',
821 'reason': '',
822 'long_id': '',
823 'valid_datetime': '',
824 },
825 '123458974513503': {
826 'status': 'in_progress',
827 'reason': '',
828 'long_id': '',
829 'valid_datetime': '',
830 },
831 '123458974513504': {
832 'status': 'in_progress',
833 'reason': '',
834 'long_id': '',
835 'valid_datetime': '',
836 },
837 },
838 'document_count': 5,
839 }
840 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))
841
842 def _test_13_mock(self, endpoint, params):
843 if endpoint == 'api/l10n_my_edi/1/submit_invoices':
844 res = {
845 'submission_uid': '123456789',
846 'documents': [],
847 }
848 for i, document in enumerate(params['documents']):
849 res['documents'].append({
850 'move_id': document['move_id'],
851 'uuid': f'12345897451351{i}',
852 'success': True,
853 })
854 return res
855 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses' and self.submission_status_count == 0:
856 return {
857 'statuses': {
858 '123458974513510': {
859 'status': 'in_progress',
860 'reason': '',
861 'long_id': '',
862 'valid_datetime': '',
863 },
864 '123458974513511': {
865 'status': 'in_progress',
866 'reason': '',
867 'long_id': '',
868 'valid_datetime': '',
869 },
870 '123458974513512': {
871 'status': 'in_progress',
872 'reason': '',
873 'long_id': '',
874 'valid_datetime': '',
875 },
876 '123458974513513': {
877 'status': 'in_progress',
878 'reason': '',
879 'long_id': '',
880 'valid_datetime': '',
881 },
882 '123458974513514': {
883 'status': 'in_progress',
884 'reason': '',
885 'long_id': '',
886 'valid_datetime': '',
887 },
888 },
889 'document_count': 5,
890 }
891 if endpoint == 'api/l10n_my_edi/1/get_submission_statuses' and self.submission_status_count in [1, 3]:
892 res = {'statuses': {}, 'document_count': 10}
893 # Build the res using loops otherwise it'd take a lot of lines.
894 for i in range(2):
895 for j in range(5):
896 res['statuses'][f'1234589745135{i}{j}'] = {
897 'status': 'valid',
898 'reason': '',
899 'long_id': '123-789-654',
900 'valid_datetime': '2024-07-15T05:00:00Z',
901 }
902 return res
903 raise UserError('Unexpected endpoint called during a test: %s with params %s.' % (endpoint, params))