Debian Codegraph @

addons/sale_pdf_quote_builder/tests/test_pdf_quote_builder.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import json
4 from base64 import b64encode
5 from functools import partial
6 from unittest.mock import patch
7
8 from werkzeug.datastructures import FileStorage
9
10 from odoo.exceptions import ValidationError
11 from odoo.fields import Command
12 from odoo.http import Response
13 from odoo.tests import Form, tagged
14 from odoo.tools.misc import file_open
15
16 from odoo.addons.sale_management.tests.common import SaleManagementCommon
17 from odoo.addons.sale_pdf_quote_builder.controllers.quotation_document import (
18 QuotationDocumentController
19 )
20 from .files import forms_pdf, plain_pdf
21
22
23 @tagged('-at_install', 'post_install')
24 class TestPDFQuoteBuilder(SaleManagementCommon):
25
26 @classmethod
27 def setUpClass(cls):
28 super().setUpClass()
29
30 cls.QuotationDocumentController = QuotationDocumentController()
31
32 cls.sale_order.validity_date = '2020-11-04'
33 cls.sale_order.partner_id.tz = 'Europe/Brussels'
34 cls.env['product.document'].search([]).action_archive()
35 cls.env['quotation.document'].search([]).action_archive()
36
37 with file_open(forms_pdf, 'rb') as file:
38 forms_pdf_data = b64encode(file.read())
39
40 with file_open(plain_pdf, 'rb') as file:
41 plain_pdf_data = b64encode(file.read())
42
43 att_header, att_footer, att_prod_doc = cls.env['ir.attachment'].create([{
44 'name': "Header",
45 'datas': plain_pdf_data,
46 }, {
47 'name': "Footer",
48 'datas': forms_pdf_data,
49 }, {
50 'name': "Product Document",
51 'datas': forms_pdf_data,
52 }])
53 cls.header, cls.footer = cls.env['quotation.document'].create([{
54 'name': "Header",
55 'ir_attachment_id': att_header.id,
56 'document_type': 'header',
57 }, {
58 'name': "Footer",
59 'ir_attachment_id': att_footer.id,
60 'document_type': 'footer',
61 }])
62 cls.product_document = cls.env['product.document'].create({
63 'name': "Product Document",
64 'ir_attachment_id': att_prod_doc.id,
65 'attached_on_sale': 'inside',
66 'res_model': 'product.product',
67 'res_id': cls.product.id,
68 })
69 cls.internal_user = cls._create_new_internal_user(login='[email protected]', groups='sales_team.group_sale_salesman')
70 cls.alt_company = cls.env['res.company'].create({'name': "Backup Company"})
71
72 def _create_so_form(self, **values):
73 """Default values limited to preexisting ones. No Command"""
74 SaleOrder = self.env['sale.order'].with_context(default_partner_id=self.partner.id)
75 so_form = Form(SaleOrder)
76 for field_name, value in values.items():
77 so_form[field_name] = value
78 so_form.save()
79 return so_form
80
81 def test_compute_customizable_pdf_form_fields_when_no_file(self):
82 self.env['quotation.document'].search([]).action_archive()
83 self.env['product.document'].search([]).action_archive()
84 self.assertEqual(self.sale_order.customizable_pdf_form_fields, False)
85
86 def test_dynamic_fields_mapping_for_quotation_document(self):
87 FormField = self.env['sale.pdf.form.field']
88 new_form_field = partial(dict, document_type='quotation_document')
89 new_form_fields = FormField.create([
90 new_form_field(name="boolean_test", path='locked'),
91 new_form_field(name="char_test", path='name'),
92 new_form_field(name="date_test", path='validity_date'),
93 new_form_field(name="datetime_test", path='commitment_date'),
94 new_form_field(name="float_test", path='prepayment_percent'),
95 new_form_field(name="integer_test", path='company_id.color'),
96 new_form_field(name="selection_test", path='state'),
97 new_form_field(name="monetary_test", path='amount_total'),
98
99 new_form_field(name="one2many_test", path='order_line'),
100 new_form_field(name="many2one_test", path='company_id'),
101 new_form_field(name="many2many_test", path='company_id.parent_ids'),
102 ])
103 sol_1, sol_2 = self.sale_order.order_line
104 form_field_expected_value_map = {
105 new_form_fields[0]: "No", # boolean
106 new_form_fields[1]: self.sale_order.name, # char
107 new_form_fields[2]: "11/04/2020", # date
108 new_form_fields[3]: "", # datetime missing
109 new_form_fields[4]: "1.0", # float
110 new_form_fields[5]: "1", # integer
111 new_form_fields[6]: dict(self.sale_order._fields['state'].selection)['draft'], # selection
112 new_form_fields[7]: "$\xa0725.00", # monetary
113 new_form_fields[8]: f"{sol_1.display_name}, {sol_2.display_name}", # one2many
114 new_form_fields[9]: f"{self.sale_order.company_id.display_name}", # many2one
115 new_form_fields[10]: f"{self.sale_order.company_id.display_name}", # many2many
116 }
117 for form_field, expected_value in form_field_expected_value_map.items():
118 result = self.env['ir.actions.report']._get_value_from_path(
119 form_field, self.sale_order
120 )
121 self.assertEqual(result, expected_value)
122
123 def test_dynamic_fields_mapping_for_product_document(self):
124 self.sale_order.commitment_date = '2121-12-21 12:21:12'
125 sol_1, sol_2 = self.sale_order.order_line
126 sol_1.update({
127 'sequence': 0,
128 'discount': 4.99,
129 'tax_ids': [
130 Command.create({'name': "test tax1"}),
131 Command.create({'name': "test tax2"}),
132 ],
133 })
134 new_form_field = partial(dict, document_type='product_document')
135 new_form_fields = self.env['sale.pdf.form.field'].create([
136 new_form_field(name="boolean_test", path='order_id.locked'),
137 new_form_field(name="char_test", path='order_id.name'),
138 new_form_field(name="date_test", path='order_id.validity_date'),
139 new_form_field(name="datetime_test", path='order_id.commitment_date'),
140 new_form_field(name="float_test", path='discount'),
141 new_form_field(name="integer_test", path='sequence'),
142 new_form_field(name="selection_test", path='order_id.state'),
143 new_form_field(name="monetary_test", path='order_id.amount_total'),
144
145 new_form_field(name="one2many_test", path='order_id.order_line'),
146 new_form_field(name="many2one_test", path='order_id.company_id'),
147 new_form_field(name="many2many_test", path='tax_ids'),
148 ])
149 expected = {
150 'boolean_test': "No",
151 'char_test': self.sale_order.name,
152 'date_test': "11/04/2020",
153 'datetime_test': "12/21/2121 01:21:12 PM",
154 'float_test': "4.99",
155 'integer_test': "0",
156 'selection_test': dict(self.sale_order._fields['state'].selection)['draft'],
157 'monetary_test': self.sale_order.currency_id.format(720.01),
158 'one2many_test': f"{sol_1.display_name}, {sol_2.display_name}",
159 'many2one_test': self.sale_order.company_id.display_name,
160 'many2many_test': "test tax1, test tax2",
161 }
162 for form_field in new_form_fields:
163 result = self.env['ir.actions.report']._get_value_from_path(
164 form_field, self.sale_order, sol_1
165 )
166 self.assertEqual(' '.join(result.split()), ' '.join(expected[form_field.name].split()))
167
168 def test_product_document_dialog_params_access(self):
169 sale_order_internal_user = self.sale_order.copy({'user_id': self.internal_user.id})
170 dialog_param = sale_order_internal_user.with_user(
171 self.internal_user.id
172 ).get_update_included_pdf_params()
173 # should return all document data regardless of access
174 self.assertEqual('Header', dialog_param['headers']['files'][0]['name'])
175 self.assertEqual('Product > Test Product', dialog_param['lines'][0]['name'])
176
177 def test_quotation_document_is_removed_on_template_change(self):
178 so_tmpl = self.env['sale.order.template'].create({
179 'name': "test1",
180 'quotation_document_ids': [Command.link(self.header.id)],
181 })
182 so_tmpl_2 = self.env['sale.order.template'].create({'name': "test2"})
183
184 self.sale_order.write({
185 'sale_order_template_id': so_tmpl.id,
186 'quotation_document_ids': [Command.link(self.header.id)],
187 })
188
189 self.assertEqual(self.sale_order.quotation_document_ids, self.header)
190
191 so_form = Form(self.sale_order)
192 so_form.sale_order_template_id = so_tmpl_2
193 so_form.save()
194
195 self.assertNotIn(self.header, self.sale_order.available_quotation_document_ids)
196 self.assertEqual(len(self.sale_order.quotation_document_ids), 0)
197
198 def test_non_pdf_attachment_inside_quote_form_save(self):
199 non_pdf_att = self.env['ir.attachment'].create({
200 'name': 'Not a PDF',
201 'datas': b64encode(b"hello"),
202 'mimetype': 'text/plain',
203 })
204
205 product_document = self.product_document
206
207 product_document.write({
208 'ir_attachment_id': non_pdf_att.id,
209 })
210 with self.assertRaises(ValidationError):
211 with Form(product_document) as doc_form:
212 doc_form.attached_on_sale = 'inside'
213
214 def test_onchange_product_removes_previously_selected_documents(self):
215 """ Check that changing a line that has a selected document unselect said document. """
216
217 available_doc = self.sale_order.order_line[0].available_product_document_ids
218 self.sale_order.order_line[0].product_document_ids = available_doc # select the document
219
220 self.assertTrue(available_doc, msg="Default order line should have an available document.")
221 msg = "The available document should have been selected."
222 self.assertEqual(
223 self.sale_order.order_line[0].product_document_ids, available_doc, msg=msg
224 )
225
226 so_form = Form(self.sale_order)
227 with so_form.order_line.edit(0) as line:
228 line.product_id = self._create_product()
229 so_form.save()
230
231 msg = "There shouldn't be any available product documents."
232 self.assertFalse(self.sale_order.order_line[0].available_product_document_ids, msg=msg)
233 msg = "There shouldn't be any selected product documents left."
234 self.assertFalse(self.sale_order.order_line[0].product_document_ids, msg=msg)
235
236 def test_available_documents_order(self):
237 product_document = self.product_document.copy()
238 product_document.sequence = self.product_document.sequence - 1
239 docs = self.sale_order.order_line[0].available_product_document_ids
240 self.assertEqual(len(docs), 2, "There should be 2 available documents.")
241 self.assertEqual(docs[0], product_document, "The first available document should be the one with the lowest sequence.")
242 self.assertEqual(
243 docs[1], self.product_document, "The second available document should be the one with the highest sequence."
244 )
245
246 def test_available_documents_multiple_products(self):
247 product_doc_copy = self.product_document.copy()
248 product2 = self._create_product(name="Test Product 2")
249 product_template_document2 = self.product_document.copy(
250 {'res_model': 'product.template', 'res_id': product2.product_tmpl_id.id, 'sequence': 1}
251 )
252 product_document2 = self.product_document.copy({'res_model': 'product.product', 'res_id': product2.id, 'sequence': 99})
253 self.sale_order.write(
254 {
255 'order_line': [
256 Command.create({'product_id': self.product.id}),
257 Command.create({'product_id': product2.id}),
258 ]
259 }
260 )
261 self.assertEqual(
262 self.sale_order.order_line[0].available_product_document_ids,
263 self.product_document | product_doc_copy,
264 )
265 self.assertFalse(
266 self.sale_order.order_line[1].available_product_document_ids,
267 "The second order line should not have any available product documents.",
268 )
269 self.assertEqual(
270 self.sale_order.order_line[0].available_product_document_ids,
271 self.sale_order.order_line[2].available_product_document_ids,
272 "The first and third order lines should have the same available product documents.",
273 )
274 self.assertEqual(
275 self.sale_order.order_line[3].available_product_document_ids[0].res_model,
276 'product.product',
277 "Alphabetical order of res_model should be respected.",
278 )
279 self.assertEqual(
280 self.sale_order.order_line[3].available_product_document_ids[0],
281 product_document2,
282 )
283 self.assertEqual(
284 self.sale_order.order_line[3].available_product_document_ids[1],
285 product_template_document2,
286 )
287
288 def test_quotation_document_upload_no_template(self):
289 """Check that uploading quotation documents get assigned the active company."""
290 if 'website' not in self.env:
291 self.skipTest("Module `website` not found")
292 else:
293 from odoo.addons.http_routing.tests.common import MockRequest # noqa: PLC0415
294
295 # Upload document without Sale Order Template
296 with (
297 MockRequest(self.env) as request,
298 file_open(plain_pdf, 'rb') as file,
299 patch.object(request.httprequest.files, 'getlist', lambda _key: [FileStorage(file)]),
300 patch.object(request, 'make_json_response',
301 lambda data, status=200, headers=None: Response(
302 json.dumps(data),
303 status=status,
304 headers=headers,
305 mimetype='application/json',
306 ),
307 ),
308 ):
309 res = self.QuotationDocumentController.upload_document(
310 ufile=FileStorage(file),
311 allowed_company_ids=json.dumps([self.alt_company.id, self.env.company.id]),
312 )
313 self.assertEqual(res.status_code, 200, "Upload should be successful")
314
315 quotation_document = self.env['quotation.document'].search([
316 ('name', '=', plain_pdf),
317 ], limit=1)
318 self.assertTrue(quotation_document, "A new quotation document should be created")
319 self.assertEqual(
320 quotation_document.company_id,
321 self.alt_company,
322 "Quotation document company should be the currently active company",
323 )
324
325 def test_quotation_document_upload_for_template(self):
326 """Check that uploading quotation documents get assigned the the quotation company."""
327 if 'website' not in self.env:
328 self.skipTest("Module `website` not found")
329 else:
330 from odoo.addons.http_routing.tests.common import MockRequest # noqa: PLC0415
331
332 # Upload a document for a Sale Order Template without company id
333 self.empty_order_template.company_id = False
334 with (
335 MockRequest(self.env) as request,
336 file_open(forms_pdf, 'rb') as file,
337 patch.object(request.httprequest.files, 'getlist', lambda _key: [FileStorage(file)]),
338 patch.object(request, 'make_json_response',
339 lambda data, status=200, headers=None: Response(
340 json.dumps(data),
341 status=status,
342 headers=headers,
343 mimetype='application/json',
344 ),
345 ),
346 ):
347 res = self.QuotationDocumentController.upload_document(
348 ufile=FileStorage(file),
349 sale_order_template_id=str(self.empty_order_template.id),
350 allowed_company_ids=json.dumps([self.alt_company.id, self.env.company.id]),
351 )
352 self.assertEqual(res.status_code, 200, "Upload should be successful")
353
354 quotation_document = self.env['quotation.document'].search([
355 ('name', '=', forms_pdf),
356 ], limit=1)
357 self.assertTrue(quotation_document, "A new quotation document should be created")
358 self.assertFalse(
359 quotation_document.company_id,
360 "Quotation document shouldn't have a company id",
361 )
362
363 def _test_custom_content_kanban_like(self):
364 # TODO VCR finish tour and uncomment
365 self.start_tour(
366 f'/odoo/sales/{self.sale_order.id}',
367 'custom_content_kanban_like_tour',
368 login='admin',
369 )
370 # Assert documents are selected
371
372 def test_quotation_document_is_added_iff_default(self):
373 self.assertFalse(self._create_so().quotation_document_ids)
374
375 self.header.add_by_default = True
376
377 self.assertEqual(self._create_so().quotation_document_ids, self.header)
378
379 def test_default_quotation_document_is_added_iff_available(self):
380 # header is default but only for quote_tmpl
381 so_tmpl = self.env['sale.order.template'].create({'name': 'Awesome Template'})
382 self.header.write({
383 'add_by_default': True,
384 'quotation_template_ids': [Command.link(so_tmpl.id)],
385 })
386
387 sof_without_tmpl = self._create_so_form()
388 sof_with_tmpl = self._create_so_form(sale_order_template_id=so_tmpl)
389
390 self.assertFalse(sof_without_tmpl.record.quotation_document_ids)
391 self.assertEqual(sof_with_tmpl.record.quotation_document_ids, self.header)
392
393 def test_quotation_document_is_removed_if_unavailable(self):
394 so_tmpl = self.env['sale.order.template'].create({'name': "Awesome Template"})
395 self.header.write({
396 'add_by_default': True,
397 'quotation_template_ids': [Command.link(so_tmpl.id)],
398 })
399 sof = self._create_so_form(sale_order_template_id=so_tmpl)
400 self.assertEqual(sof.record.quotation_document_ids, self.header)
401
402 sof.sale_order_template_id = self.env['sale.order.template']
403 sof.save()
404
405 self.assertFalse(sof.record.quotation_document_ids)