Debian Codegraph @

addons/account_peppol/tests/test_peppol_messages.py

raw symbols SCIP
1 import json
2 from base64 import b64encode
3 from contextlib import contextmanager
4 from unittest.mock import patch
5 from urllib import parse
6
7 from requests import PreparedRequest, Response, Session
8
9 from odoo import Command
10 from odoo.exceptions import UserError
11 from odoo.tests.common import tagged, freeze_time
12 from odoo.tools.misc import file_open
13
14 from odoo.addons.account.tests.test_account_move_send import TestAccountMoveSendCommon
15 from odoo.addons.mail.tests.common import MailCommon
16
17 ID_CLIENT = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
18 FAKE_UUID = ['yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy',
19 'zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz']
20 FILE_PATH = 'account_peppol/tests/assets'
21
22 @freeze_time('2023-01-01')
23 @tagged('-at_install', 'post_install')
24 class TestPeppolMessage(TestAccountMoveSendCommon, MailCommon):
25
26 @classmethod
27 def setUpClass(cls):
28 super().setUpClass()
29 cls.env['ir.config_parameter'].sudo().set_param('account_peppol.edi.mode', 'test')
30 cls.mocked_incoming_invoice_fname = 'incoming_invoice'
31
32 cls.env.company.write({
33 'country_id': cls.env.ref('base.be').id,
34 'peppol_eas': '0208',
35 'peppol_endpoint': '0477472701',
36 'account_peppol_proxy_state': 'receiver',
37 })
38
39 edi_identification = cls.env['account_edi_proxy_client.user']._get_proxy_identification(cls.env.company, 'peppol')
40 cls.private_key = cls.env['certificate.key'].create({
41 'name': 'Test key PEPPOL',
42 'content': b64encode(file_open(f'{FILE_PATH}/private_key.pem', 'rb').read()),
43 })
44 cls.proxy_user = cls.env['account_edi_proxy_client.user'].create({
45 'id_client': ID_CLIENT,
46 'proxy_type': 'peppol',
47 'edi_mode': 'test',
48 'edi_identification': edi_identification,
49 'private_key_id': cls.private_key.id,
50 'refresh_token': FAKE_UUID[0],
51 })
52
53 cls.invalid_partner, cls.valid_partner = cls.env['res.partner'].create([{
54 'name': 'Wintermute',
55 'city': 'Charleroi',
56 'country_id': cls.env.ref('base.be').id,
57 'peppol_eas': '0208',
58 'peppol_endpoint': '3141592654',
59 }, {
60 'name': 'Molly',
61 'city': 'Namur',
62 'email': '[email protected]',
63 'country_id': cls.env.ref('base.be').id,
64 'peppol_eas': '0208',
65 'peppol_endpoint': '2718281828',
66 }])
67
68 cls.env['res.partner.bank'].create({
69 'acc_number': '0144748555',
70 'partner_id': cls.env.company.partner_id.id,
71 })
72
73 def create_move(self, partner, company=None):
74 return self.env['account.move'].create({
75 'move_type': 'out_invoice',
76 'company_id': (company or self.env.company).id,
77 'partner_id': partner.id,
78 'date': '2023-01-01',
79 'ref': 'Test reference',
80 'invoice_line_ids': [
81 (0, 0, {
82 'name': 'line 1',
83 'product_id': self.product_a.id,
84 }),
85 (0, 0, {
86 'name': 'line 2',
87 'product_id': self.product_a.id,
88 }),
89 ],
90 })
91
92 @contextmanager
93 def _set_context(self, other_context):
94 cls = self.__class__
95 env = cls.env(context=dict(cls.env.context, **other_context))
96 with patch.object(cls, "env", env):
97 yield
98
99 @classmethod
100 def _request_handler(cls, s: Session, r: PreparedRequest, /, **kw):
101 response = Response()
102 response.status_code = 200
103 url = r.path_url.lower()
104 if r.path_url.startswith('/api/peppol/1/lookup'):
105 peppol_identifier = parse.parse_qs(r.path_url.rsplit('?')[1])['peppol_identifier'][0].lower()
106 url_quoted_peppol_identifier = parse.quote_plus(peppol_identifier)
107 if peppol_identifier == '0208:0477472701':
108 response.status_code = 200
109 response.json = lambda: {
110 "result": {
111 'identifier': peppol_identifier,
112 'smp_base_url': "http://iap-services.odoo.com",
113 'ttl': 60,
114 'service_group_url': f'http://iap-services.odoo.com/iso6523-actorid-upis%3A%3A{url_quoted_peppol_identifier}',
115 'services': [
116 {
117 "href": f"http://iap-services.odoo.com/iso6523-actorid-upis%3A%3A{url_quoted_peppol_identifier}/services/busdox-docid-qns%3A%3Aurn%3Aoasis%3Anames%3Aspecification%3Aubl%3Aschema%3Axsd%3AInvoice-2%3A%3AInvoice%23%23urn%3Acen.eu%3Aen16931%3A2017%23compliant%23urn%3Afdc%3Apeppol.eu%3A2017%3Apoacc%3Abilling%3A3.0%3A%3A2.1",
118 "document_id": "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1",
119 },
120 ],
121 },
122 }
123 return response
124 if peppol_identifier == '0208:2718281828':
125 response.status_code = 200
126 response.json = lambda: {
127 "result": {
128 'identifier': peppol_identifier,
129 'smp_base_url': "http://iap-services.odoo.com",
130 'ttl': 60,
131 'service_group_url': f'http://iap-services.odoo.com/iso6523-actorid-upis%3A%3A{url_quoted_peppol_identifier}',
132 'services': [
133 {
134 "href": f"http://iap-services.odoo.com/iso6523-actorid-upis%3A%3A{url_quoted_peppol_identifier}/services/busdox-docid-qns%3A%3Aurn%3Aoasis%3Anames%3Aspecification%3Aubl%3Aschema%3Axsd%3AInvoice-2%3A%3AInvoice%23%23urn%3Acen.eu%3Aen16931%3A2017%23compliant%23urn%3Afdc%3Apeppol.eu%3A2017%3Apoacc%3Abilling%3A3.0%3A%3A2.1",
135 "document_id": "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1",
136 }
137 ],
138 },
139 }
140 return response
141
142 if peppol_identifier == '0198:dk16356706':
143 response.status_code = 200
144 response.json = lambda: {"result": {
145 'identifier': peppol_identifier,
146 'smp_base_url': "http://iap-services.odoo.com",
147 'ttl': 60,
148 'service_group_url': f'http://iap-services.odoo.com/iso6523-actorid-upis%3A%3A{url_quoted_peppol_identifier}',
149 'services': [],
150 },
151 }
152 return response
153 else:
154 response.status_code = 404
155 response.json = lambda: {"error": {"code": "NOT_FOUND", "message": "no naptr record", "retryable": False}}
156 return response
157
158 body = json.loads(r.body)
159 if url == '/api/peppol/1/send_document':
160 if not body['params']['documents']:
161 raise UserError('No documents were provided')
162 num_invoices = len(body['params']['documents'])
163 response.json = lambda: {
164 'result': {
165 'messages': [{'message_uuid': FAKE_UUID[0]}] * num_invoices
166 }
167 }
168 return response
169
170 if url == '/api/peppol/1/ack':
171 response.json = lambda: {'result': {}}
172 return response
173
174 if url == '/api/peppol/1/get_all_documents':
175 response.json = lambda: {
176 'result': {
177 'messages': [
178 {
179 'accounting_supplier_party': '0198:dk16356706',
180 'filename': 'test_incoming.xml',
181 'uuid': FAKE_UUID[1],
182 'state': 'done',
183 'direction': 'incoming',
184 'document_type': 'Invoice',
185 'sender': '0198:dk16356706',
186 'receiver': '0208:0477472701',
187 'timestamp': '2022-12-30',
188 'error': False if not cls.env.context.get('error') else 'Test error',
189 }
190 ],
191 }
192 }
193 return response
194
195 if url == '/api/peppol/1/get_document':
196 uuid = body['params']['message_uuids'][0]
197 if uuid == FAKE_UUID[0]:
198 response_content = {
199 'accounting_supplier_party': False,
200 'filename': 'test_outgoing.xml',
201 'enc_key': '',
202 'document': '',
203 'state': 'done' if not cls.env.context.get('error') else 'error',
204 'direction': 'outgoing',
205 'document_type': 'Invoice',
206 }
207 elif uuid == FAKE_UUID[1]:
208 response_content = {
209 'accounting_supplier_party': '0198:dk16356706',
210 'filename': 'test_incoming',
211 'enc_key': file_open(f'{FILE_PATH}/enc_key', mode='rb').read(),
212 'document': b64encode(file_open(f'{FILE_PATH}/{cls.mocked_incoming_invoice_fname}', mode='rb').read()),
213 'state': 'done' if not cls.env.context.get('error') else 'error',
214 'direction': 'incoming',
215 'document_type': 'Invoice',
216 }
217
218 response.json = lambda: {'result': {uuid: response_content}}
219 return response
220
221 return super()._request_handler(s, r, **kw)
222
223 def test_non_xml_compatible_characters(self):
224 """
225 Test that non xml compatible characters doesn't block Peppol Invoice sending
226 """
227 move = self.create_move(self.valid_partner)
228 product_a = self._create_product(
229 name='Test\x02Product',
230 lst_price=1000.0,
231 standard_price=800.0
232 )
233 move.invoice_line_ids[0].product_id = product_a
234 move.action_post()
235
236 wizard = self.create_send_and_print(move, sending_methods=['peppol'])
237 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
238 wizard.action_send_and_print()
239 self.assertEqual(self._get_mail_message(move).preview, 'The invoice has been sent to the Peppol Access Point. The following attachments were sent with the XML:')
240
241 def test_attachment_placeholders(self):
242 move = self.create_move(self.valid_partner)
243 move.action_post()
244
245 wizard = self.create_send_and_print(move, default=True)
246 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
247
248 # the ubl xml placeholder should be generated
249 self._assert_mail_attachments_widget(wizard, [
250 {
251 'mimetype': 'application/pdf',
252 'name': 'INV_2023_00001.pdf',
253 'placeholder': True,
254 },
255 {
256 'mimetype': 'application/xml',
257 'name': 'INV_2023_00001_ubl_bis3.xml',
258 'placeholder': True,
259 },
260 ])
261
262 wizard.sending_methods = ['peppol']
263 wizard.action_send_and_print()
264 self.assertEqual(self._get_mail_message(move).preview, 'The invoice has been sent to the Peppol Access Point. The following attachments were sent with the XML:')
265
266 def test_send_peppol_alerts_not_valid_partner(self):
267 move = self.create_move(self.invalid_partner)
268 self.invalid_partner.invoice_edi_format = 'ubl_bis3'
269 move.action_post()
270 wizard = self.create_send_and_print(move, default=True)
271
272 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
273 self.assertEqual(self.invalid_partner.peppol_verification_state, 'not_valid') # not on peppol at all
274 self.assertFalse(wizard.sending_methods and 'peppol' in wizard.sending_methods) # peppol is not checked
275 self.assertTrue(wizard.sending_method_checkboxes['peppol']['readonly']) # peppol is not possible to select
276 self.assertFalse(wizard.alerts) # there is no alerts
277
278 @patch('odoo.addons.account_peppol.models.res_partner.ResPartner._check_document_type_support', return_value=False)
279 def test_send_peppol_alerts_not_valid_format_partner(self, mocked_check):
280 move = self.create_move(self.valid_partner)
281 move.action_post()
282 wizard = self.create_send_and_print(move, sending_methods=['peppol'])
283
284 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
285 self.assertEqual(self.valid_partner.peppol_verification_state, 'not_valid_format') # on peppol but can't receive bis3
286 self.assertTrue('account_peppol_warning_partner' in wizard.alerts)
287
288 def test_send_peppol_alerts_invalid_partner(self):
289 """If there's already account_edi_ubl_cii_configure_partner, the warning should not appear."""
290 move = self.create_move(self.invalid_partner)
291 move.action_post()
292 self.invalid_partner.peppol_endpoint = False
293 wizard = self.create_send_and_print(move, default=True)
294 self.assertFalse(wizard.sending_methods and 'peppol' in wizard.sending_methods) # by default peppol is not selected for non-valid partners
295 wizard.sending_method_checkboxes = {**wizard.sending_method_checkboxes, 'peppol': {'checked': True}}
296 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
297 self.assertTrue('account_edi_ubl_cii_configure_partner' in wizard.alerts)
298 self.assertFalse('account_peppol_warning_partner' in wizard.alerts)
299
300 def test_resend_error_peppol_message(self):
301 # should be able to resend error invoices
302 move = self.create_move(self.valid_partner)
303 move.action_post()
304
305 wizard = self.create_send_and_print(move, default=True)
306 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
307 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
308 with self._set_context({'error': True}):
309 wizard.with_env(self.env).action_send_and_print()
310
311 self.env['account_edi_proxy_client.user']._cron_peppol_get_message_status()
312 self.assertRecordValues(
313 move, [{
314 'peppol_move_state': 'error',
315 'peppol_message_uuid': FAKE_UUID[0],
316 }])
317
318 # we can't send the ubl document again unless we regenerate the pdf
319 move.invoice_pdf_report_id.unlink()
320 wizard = self.create_send_and_print(move, default=True)
321 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
322 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
323
324 wizard.action_send_and_print()
325
326 self.env['account_edi_proxy_client.user']._cron_peppol_get_message_status()
327 self.assertEqual(move.peppol_move_state, 'done')
328
329 def test_send_success_message(self):
330 # should be able to send valid invoices correctly
331 # attachment should be generated
332 # peppol_move_state should be set to done
333 move = self.create_move(self.valid_partner)
334 move.action_post()
335
336 wizard = self.create_send_and_print(move, default=True)
337 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
338 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
339
340 wizard.action_send_and_print()
341
342 self.env['account_edi_proxy_client.user']._cron_peppol_get_message_status()
343 self.assertRecordValues(move, [{
344 'peppol_move_state': 'done',
345 'peppol_message_uuid': FAKE_UUID[0],
346 }],
347 )
348 self.assertTrue(bool(move.ubl_cii_xml_id))
349
350 def test_send_invalid_edi_user(self):
351 # an invalid edi user should not be able to send invoices via peppol
352 self.env.company.account_peppol_proxy_state = 'rejected'
353
354 move = self.create_move(self.valid_partner)
355 move.action_post()
356
357 wizard = self.create_send_and_print(move, default=True)
358 self.assertTrue('peppol' not in wizard.sending_method_checkboxes)
359
360 def test_receive_error_peppol(self):
361 # an error peppol message should be created
362 with self._set_context({'error': True}):
363 self.env['account_edi_proxy_client.user']._cron_peppol_get_new_documents()
364
365 move = self.env['account.move'].search([('peppol_message_uuid', '=', FAKE_UUID[1])])
366 self.assertRecordValues(
367 move, [{
368 'peppol_move_state': 'error',
369 'move_type': 'in_invoice',
370 }])
371
372 def test_receive_success_peppol(self):
373 # a correct move should be created
374 self.env['account_edi_proxy_client.user']._cron_peppol_get_new_documents()
375
376 move = self.env['account.move'].search([('peppol_message_uuid', '=', FAKE_UUID[1])])
377 self.assertRecordValues(
378 move, [{
379 'peppol_move_state': 'done',
380 'move_type': 'in_invoice',
381 }])
382
383 def test_received_bill_notification(self):
384 peppol_purchase_journal = self.env.company.peppol_purchase_journal_id
385 peppol_purchase_journal.incoming_einvoice_notification_email = '[email protected]'
386 self.env.company.email = '[email protected]'
387
388 with self.mock_mail_gateway():
389 self.env['account_edi_proxy_client.user']._cron_peppol_get_new_documents()
390
391 self.assertSentEmail(
392 '"company_1_data" <[email protected]>',
393 ['[email protected]'],
394 subject=f"{self.env.company.name} - New invoice in {peppol_purchase_journal.display_name} journal",
395 )
396
397 def test_validate_partner(self):
398 new_partner = self.env['res.partner'].create({
399 'name': 'Deanna Troi',
400 'city': 'Namur',
401 'country_id': self.env.ref('base.be').id,
402 })
403 self.assertRecordValues(
404 new_partner, [{
405 'peppol_verification_state': 'not_verified',
406 'peppol_eas': '0208',
407 'peppol_endpoint': False,
408 }])
409
410 new_partner.peppol_endpoint = '0477472701'
411 new_partner.button_account_peppol_check_partner_endpoint()
412 self.assertRecordValues(
413 new_partner, [{
414 'peppol_verification_state': 'valid',
415 'peppol_eas': '0208',
416 'peppol_endpoint': '0477472701',
417 }])
418
419 new_partner.peppol_endpoint = '3141592654'
420 new_partner.button_account_peppol_check_partner_endpoint()
421 self.assertRecordValues(
422 new_partner, [{
423 'peppol_verification_state': 'not_valid',
424 'peppol_eas': '0208',
425 'peppol_endpoint': '3141592654',
426 }])
427
428 # the participant exists on the network but cannot receive XRechnung
429 new_partner.write({
430 'invoice_edi_format': 'xrechnung',
431 'peppol_endpoint': '0477472701',
432 })
433 new_partner.button_account_peppol_check_partner_endpoint()
434 self.assertRecordValues(
435 new_partner, [{
436 'peppol_verification_state': 'not_valid_format',
437 'peppol_eas': '0208',
438 'peppol_endpoint': '0477472701',
439 }])
440
441 def test_peppol_send_multi_async(self):
442 company_2 = self.setup_other_company()['company']
443 company_2.write({
444 'country_id': self.env.ref('base.be').id,
445 })
446
447 new_partner = self.env['res.partner'].create({
448 'name': 'Deanna Troi',
449 'city': 'Namur',
450 'country_id': self.env.ref('base.be').id,
451 'peppol_endpoint': '0477472701',
452 'invoice_edi_format': 'ubl_bis3',
453 })
454
455 # partner is valid for company 1
456 self.assertRecordValues(new_partner, [{
457 'peppol_verification_state': 'valid',
458 'peppol_eas': '0208',
459 'peppol_endpoint': '0477472701',
460 'invoice_edi_format': 'ubl_bis3',
461 }])
462 # but not valid for company 2
463 new_partner.with_company(company_2).invoice_edi_format = 'nlcius'
464 new_partner.button_account_peppol_check_partner_endpoint(company=company_2)
465 self.assertRecordValues(new_partner.with_company(company_2), [{
466 'peppol_verification_state': 'not_valid_format',
467 'peppol_eas': '0208',
468 'peppol_endpoint': '0477472701',
469 'invoice_edi_format': 'nlcius',
470 }])
471 move_1 = self.create_move(new_partner)
472 move_2 = self.create_move(new_partner)
473 move_3 = self.create_move(new_partner, company_2)
474 (move_1 + move_2 + move_3).action_post()
475
476 wizard = self.create_send_and_print(move_1 + move_2 + move_3)
477 wizard.action_send_and_print()
478 self.assertEqual((move_1 + move_2 + move_3).mapped('is_being_sent'), [True, True, True])
479 # the cron is ran asynchronously and should be agnostic from the current self.env.company
480 with self.enter_registry_test_mode():
481 self.env.ref('account.ir_cron_account_move_send').with_company(company_2).method_direct_trigger()
482 # only move 1 & 2 should be processed, move_3 is related to an invalid partner (with regard to company_2) thus should not be sent
483 self.assertRecordValues((move_1 + move_2 + move_3), [
484 {'peppol_move_state': 'processing', 'is_move_sent': True},
485 {'peppol_move_state': 'processing', 'is_move_sent': True},
486 {'peppol_move_state': False, 'is_move_sent': True}, # only sent by email
487 ])
488
489 def test_peppol_send_multi_async_mixed(self):
490 """Try to send invoices to partners with multiple sending methods each. """
491 peppol_partner = self.env['res.partner'].create({
492 'name': 'Peppol partner',
493 'country_id': self.env.ref('base.be').id,
494 'company_registry': '0477472701',
495 })
496 self.assertRecordValues(peppol_partner, [{
497 'peppol_verification_state': 'not_verified',
498 'peppol_eas': '0208',
499 'peppol_endpoint': '0477472701',
500 }])
501 not_peppol_partner = self.env['res.partner'].create({
502 'name': 'Not Peppol partner',
503 'country_id': self.env.ref('base.us').id,
504 })
505 self.assertEqual(not_peppol_partner.peppol_verification_state, 'not_verified')
506 move_1 = self.create_move(peppol_partner)
507 move_2 = self.create_move(not_peppol_partner)
508 (move_1 + move_2).action_post()
509 wizard = self.create_send_and_print(move_1 + move_2)
510 self.assertEqual(peppol_partner.peppol_verification_state, 'valid')
511 self.assertEqual(not_peppol_partner.peppol_verification_state, 'not_verified')
512 wizard.action_send_and_print()
513 self.assertEqual((move_1 + move_2).mapped('is_being_sent'), [True, True])
514 with self.enter_registry_test_mode():
515 self.env.ref('account.ir_cron_account_move_send').method_direct_trigger()
516 self.assertRecordValues((move_1 + move_2), [
517 {'peppol_move_state': 'processing', 'is_move_sent': True},
518 {'peppol_move_state': False, 'is_move_sent': True}, # only sent by email
519 ])
520
521 def test_available_peppol_sending_methods(self):
522 company_us = self.setup_other_company()['company'] # not a valid Peppol country
523 self.assertTrue('peppol' in self.valid_partner.with_company(self.env.company).available_peppol_sending_methods)
524 self.assertFalse('peppol' in self.valid_partner.with_company(company_us).available_peppol_sending_methods)
525
526 def test_available_peppol_edi_formats(self):
527 self.valid_partner.invoice_sending_method = 'peppol'
528 self.assertFalse('facturx' in self.valid_partner.available_peppol_edi_formats)
529 self.valid_partner.invoice_sending_method = 'email'
530 self.assertTrue('facturx' in self.valid_partner.available_peppol_edi_formats)
531
532 def test_peppol_default_ubl_bis3_single(self):
533 """In single invoice sending, if a partner is set on 'by Peppol' sending method,
534 and has no specific e-invoice format, we should default on BIS3
535 and generate invoices without errors.
536 """
537 self.valid_partner.invoice_edi_format = False
538
539 move = self.create_move(self.valid_partner)
540 move.action_post()
541 wizard = self.create_send_and_print(move, default=True)
542 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
543 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
544 wizard.action_send_and_print()
545 self.assertTrue(move.ubl_cii_xml_id)
546 self.assertEqual(move.peppol_move_state, 'processing')
547
548 def test_peppol_default_ubl_bis3_multi(self):
549 """In multi-sending, if a partner is set on 'by Peppol' sending method, and
550 has no specific e-invoice format, we should default on BIS3
551 and generate invoices without errors.
552 """
553 self.valid_partner.invoice_edi_format = False
554
555 move_1 = self.create_move(self.valid_partner)
556 move_2 = self.create_move(self.valid_partner)
557 moves = (move_1 + move_2)
558 moves.action_post()
559 wizard = self.create_send_and_print(moves, default=True)
560 self.assertEqual(wizard.summary_data, {
561 'email': {'count': 2, 'label': 'by Email'},
562 'peppol': {'count': 2, 'label': 'by Peppol'},
563 })
564 wizard.action_send_and_print()
565 with self.enter_registry_test_mode():
566 self.env.ref('account.ir_cron_account_move_send').method_direct_trigger()
567
568 self.assertEqual(len(moves.ubl_cii_xml_id), 2)
569 self.assertEqual(moves.mapped('peppol_move_state'), ['processing', 'processing'])
570
571 def test_silent_error_while_creating_xml(self):
572 """When in multi/async mode, the generation of XML can fail silently (without raising).
573 This needs to be reflected as an error and put the move in Peppol Error state.
574 """
575 def mocked_export_invoice_constraints(self, invoice, vals):
576 return {'test_error_key': 'test_error_description'}
577
578 self.valid_partner.invoice_edi_format = 'ubl_bis3'
579 move_1 = self.create_move(self.valid_partner)
580 move_2 = self.create_move(self.valid_partner)
581 (move_1 + move_2).action_post()
582
583 wizard = self.create_send_and_print(move_1 + move_2)
584 with patch(
585 'odoo.addons.account_edi_ubl_cii.models.account_edi_xml_ubl_20.AccountEdiXmlUBL20._export_invoice_constraints',
586 mocked_export_invoice_constraints
587 ), self.enter_registry_test_mode():
588 wizard.action_send_and_print()
589 self.env.ref('account.ir_cron_account_move_send').method_direct_trigger()
590 self.assertEqual(move_1.peppol_move_state, 'error')
591
592 def test_peppol_branch_company_send(self):
593 branch_spoiled, branch_independent = self.env['res.company'].create([
594 {
595 'name': 'BE Spoiled Kid',
596 'country_id': self.env.ref('base.be').id,
597 'parent_id': self.env.company.id,
598 'peppol_eas': '0208',
599 'peppol_endpoint': '0477472701',
600 'account_peppol_proxy_state': 'receiver',
601 },
602 {
603 'name': 'BE Independent Kid',
604 'country_id': self.env.ref('base.be').id,
605 'parent_id': self.env.company.id,
606 'peppol_eas': '0208',
607 'peppol_endpoint': '0477471111',
608 'account_peppol_proxy_state': 'receiver',
609 },
610 ])
611 self.cr.precommit.run() # load the COA
612 self.valid_partner.button_account_peppol_check_partner_endpoint()
613 self.env['account_edi_proxy_client.user'].create([
614 {
615 'company_id': branch_spoiled.id,
616 'id_client': ID_CLIENT.replace('x', 'a'),
617 'proxy_type': 'peppol',
618 'edi_mode': 'test',
619 'edi_identification': self.env['account_edi_proxy_client.user']._get_proxy_identification(branch_spoiled, 'peppol'),
620 'private_key_id': self.private_key.id,
621 'refresh_token': FAKE_UUID[1],
622 },
623 {
624 'company_id': branch_independent.id,
625 'id_client': ID_CLIENT.replace('x', 'b'),
626 'proxy_type': 'peppol',
627 'edi_mode': 'test',
628 'edi_identification': self.env['account_edi_proxy_client.user']._get_proxy_identification(branch_independent, 'peppol'),
629 'private_key_id': self.private_key.id,
630 'refresh_token': FAKE_UUID[1],
631 }
632 ])
633
634 # Branch uses parent's active peppol connection
635 spoiled_move = self.create_move(self.valid_partner, company=branch_spoiled)
636 spoiled_move.action_post()
637 wizard = self.create_send_and_print(spoiled_move, sending_methods=['peppol'])
638 wizard.action_send_and_print()
639 self.assertEqual(spoiled_move.peppol_move_state, 'processing')
640
641 # Branch uses peppol configuration independent of their parent
642 independent_move = self.create_move(self.valid_partner, company=branch_independent)
643 independent_move.action_post()
644 wizard = self.create_send_and_print(independent_move, sending_methods=['peppol'])
645 wizard.action_send_and_print()
646 self.assertEqual(independent_move.peppol_move_state, 'processing')
647
648 def test_compute_available_peppol_eas_multi_partner(self):
649 """Check _compute_available_peppol_eas works with multiple partners"""
650
651 # Create multiple partners
652 partners = self.env['res.partner'].create([
653 {'name': 'Partner A'},
654 {'name': 'Partner B'},
655 ])
656 partners._compute_available_peppol_eas()
657 for partner in partners:
658 self.assertFalse('odemo' in partner.available_peppol_eas)
659
660 def test_send_self_billed_invoice_via_peppol(self):
661 """Test sending a self-billed invoice (vendor bill) via Peppol.
662
663 Self-billed invoices are vendor bills that can be sent via Peppol when
664 the company has self-billing sending activated.
665 """
666 # Enable self-billing sending for the company
667 self.env.company.peppol_activate_self_billing_sending = True
668 self.valid_partner.invoice_edi_format = 'ubl_bis3'
669
670 self_billing_journal = self.env['account.journal'].create({
671 'name': 'Self Billing',
672 'code': 'SB',
673 'type': 'purchase',
674 'is_self_billing': True,
675 })
676
677 # Create a vendor bill (in_invoice) that can be sent as self-billed
678 vendor_bill = self.env['account.move'].create({
679 'move_type': 'in_invoice',
680 'journal_id': self_billing_journal.id,
681 'company_id': self.env.company.id,
682 'partner_id': self.valid_partner.id,
683 'date': '2023-01-01',
684 'invoice_date': '2023-01-01',
685 'ref': 'Test vendor bill reference',
686 'invoice_line_ids': [
687 (0, 0, {
688 'name': 'vendor line 1',
689 'product_id': self.product_a.id,
690 }),
691 (0, 0, {
692 'name': 'vendor line 2',
693 'product_id': self.product_a.id,
694 }),
695 ],
696 })
697 vendor_bill.action_post()
698
699 # Verify the bill is exportable as self-invoice
700 self.assertTrue(vendor_bill._is_exportable_as_self_invoice())
701
702 # Create and configure the send wizard
703 wizard = self.create_send_and_print(vendor_bill, default=True)
704 self.assertEqual(wizard.invoice_edi_format, 'ubl_bis3')
705 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
706
707 # Send the self-billed invoice
708 wizard.action_send_and_print()
709
710 # Verify the invoice was sent successfully
711 self.env['account_edi_proxy_client.user']._cron_peppol_get_message_status()
712 self.assertRecordValues(vendor_bill, [{
713 'peppol_move_state': 'done',
714 'peppol_message_uuid': FAKE_UUID[0],
715 }],
716 )
717 self.assertTrue(bool(vendor_bill.ubl_cii_xml_id))
718
719 def test_self_billing_sending_constraints(self):
720 """Test that self-billing sending constraints are properly handled."""
721 self.valid_partner.invoice_edi_format = 'ubl_bis3'
722
723 self_billing_journal = self.env['account.journal'].create({
724 'name': 'Self Billing',
725 'code': 'SB',
726 'type': 'purchase',
727 'is_self_billing': True,
728 })
729
730 vendor_bill = self.env['account.move'].create({
731 'move_type': 'in_invoice',
732 'journal_id': self_billing_journal.id,
733 'company_id': self.env.company.id,
734 'partner_id': self.valid_partner.id,
735 'date': '2023-01-01',
736 'invoice_date': '2023-01-01',
737 'ref': 'Test vendor bill reference',
738 'invoice_line_ids': [
739 (0, 0, {
740 'name': 'vendor line 1',
741 'product_id': self.product_a.id,
742 }),
743 ],
744 })
745 vendor_bill.action_post()
746
747 # Verify the bill is exportable as self-invoice
748 self.assertTrue(vendor_bill._is_exportable_as_self_invoice())
749
750 # Test that the constraint 'not_sale_document' is removed for self-billed invoices
751 wizard = self.create_send_and_print(vendor_bill, default=True)
752 self.assertTrue(wizard.sending_methods and 'peppol' in wizard.sending_methods)
753
754 # Test that vendor bills can be sent as soon as the format allows (bis3) and the journal is in self-billing
755 self.create_send_and_print(vendor_bill, default=True)
756
757 def test_receive_self_billed_invoice_from_peppol(self):
758 """Test receiving a self-billed invoice from Peppol.
759
760 Self-billed invoices received via Peppol should be created as out_invoice
761 in the self-billing reception journal.
762 """
763 # Set up the 21% VAT sale tax which should be put on the invoice line
764 tax_21 = self.percent_tax(21.0, type_tax_use='sale')
765
766 # Set up the self-billing reception journal
767 sale_journal = self.env['account.journal'].search([
768 ('company_id', '=', self.env.company.id),
769 ('type', '=', 'sale'),
770 ], limit=1)
771 self.env.company.peppol_self_billing_reception_journal_id = sale_journal
772 cls = self.__class__
773 cls.mocked_incoming_invoice_fname = 'incoming_self_billed_invoice'
774
775 def restore_mocked_incoming_invoice_fname():
776 cls.mocked_incoming_invoice_fname = 'incoming_invoice'
777 self.addCleanup(restore_mocked_incoming_invoice_fname)
778
779 # Receive the self-billed invoice (using existing mock data)
780 # The mock data already includes a document that will be processed
781 self.env['account_edi_proxy_client.user']._cron_peppol_get_new_documents()
782
783 # Verify the self-billed invoice was created correctly
784 move = self.env['account.move'].search([('peppol_message_uuid', '=', FAKE_UUID[1])])
785 self.assertRecordValues(move, [{
786 'peppol_move_state': 'done',
787 'move_type': 'out_invoice',
788 'journal_id': self.env.company.peppol_self_billing_reception_journal_id.id,
789 }])
790
791 self.assertRecordValues(move.line_ids, [
792 {
793 'name': 'product_a',
794 'quantity': 1.0,
795 'price_unit': 100.0,
796 'tax_ids': tax_21.ids,
797 'amount_currency': -100.0,
798 'currency_id': self.env.ref('base.EUR').id,
799 },
800 {
801 'name': 'percent_21.0_(1)',
802 'quantity': False,
803 'price_unit': False,
804 'tax_ids': [],
805 'amount_currency': -21.0,
806 'currency_id': self.env.ref('base.EUR').id,
807 },
808 {
809 'name': 'BILL/2017/01/0001',
810 'quantity': False,
811 'price_unit': False,
812 'tax_ids': [],
813 'amount_currency': 121.0,
814 'currency_id': self.env.ref('base.EUR').id,
815 },
816 ])
817
818 def test_automatic_invoicing_auto_update_partner_peppol_status(self):
819 self.ensure_installed('sale')
820 tax = self.percent_tax(21.0)
821 product = self._create_product(lst_price=100.0, taxes_id=tax)
822 partner = self.env['res.partner'].create({
823 'name': 'partner_be',
824 'street': "Rue des Bourlottes 9",
825 'zip': "1367",
826 'city': "Ramillies",
827 'vat': 'BE0477472701',
828 'company_registry': '0477472701',
829 'invoice_sending_method': 'peppol',
830 'invoice_edi_format': 'ubl_bis3',
831 'company_id': self.env.company.id,
832 'country_id': self.env.ref('base.be').id,
833 })
834 self.env.user.group_ids |= self.env.ref('sales_team.group_sale_salesman')
835
836 self.env['ir.config_parameter'].sudo().set_param('sale.automatic_invoice', True)
837 so = self._create_sale_order_one_line(product_id=product, partner_id=partner)
838
839 payment_method = self.env.ref('payment.payment_method_unknown')
840
841 dummy_provider = self.env['payment.provider'].create({
842 'name': "Dummy Provider",
843 'code': 'none',
844 'state': 'test',
845 'is_published': True,
846 'payment_method_ids': [Command.set(payment_method.ids)],
847 'allow_tokenization': True,
848 })
849 self._create_dummy_payment_method_for_provider(
850 provider=dummy_provider,
851 journal=self.company_data['default_journal_bank'],
852 )
853 transaction = self.env['payment.transaction'].create({
854 'payment_method_id': payment_method.id,
855 'amount': so.amount_total,
856 'state': 'done',
857 'provider_id': dummy_provider.id,
858 'currency_id': so.currency_id.id,
859 'reference': so.name,
860 'partner_id': partner.id,
861 'sale_order_ids': [Command.set(so.ids)],
862 })
863 transaction.sudo()._post_process()
864
865 self.assertRecordValues(partner, [{'peppol_verification_state': 'valid'}])