Debian Codegraph @

addons/mrp_subcontracting_purchase/tests/test_mrp_subcontracting_purchase.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import logging
4 from datetime import datetime, timedelta
5 from json import loads
6
7 from freezegun import freeze_time
8
9 from odoo import Command
10 from odoo.fields import Date
11 from odoo.tests import Form, tagged
12
13 from odoo.addons.mrp_subcontracting_account.tests.test_subcontracting_account import TestAccountSubcontractingFlows
14
15 _logger = logging.getLogger(__name__)
16
17
18 @tagged('post_install', '-at_install')
19 class MrpSubcontractingPurchaseTest(TestAccountSubcontractingFlows):
20
21 @classmethod
22 def setUpClass(self):
23 super().setUpClass()
24
25 self.finished2, self.comp3 = self.env['product.product'].create([{
26 'name': 'SuperProduct',
27 'is_storable': True,
28 }, {
29 'name': 'Component',
30 'type': 'consu',
31 }])
32 self.vendor = self.env['res.partner'].create({
33 'name': 'Vendor',
34 })
35
36 self.bom_finished2 = self.env['mrp.bom'].create({
37 'product_tmpl_id': self.finished2.product_tmpl_id.id,
38 'type': 'subcontract',
39 'subcontractor_ids': [(6, 0, self.subcontractor_partner1.ids)],
40 'bom_line_ids': [(0, 0, {
41 'product_id': self.comp3.id,
42 'product_qty': 1,
43 })],
44 })
45
46 def test_bom_overview_availability(self):
47 # Create routes for components and the main product
48 self.comp2.bom_ids.unlink()
49 self.env['product.supplierinfo'].create({
50 'product_tmpl_id': self.finished.product_tmpl_id.id,
51 'partner_id': self.subcontractor_partner1.id,
52 'price': 1.0,
53 'delay': 10
54 })
55 self.env['product.supplierinfo'].create({
56 'product_tmpl_id': self.comp1.product_tmpl_id.id,
57 'partner_id': self.subcontractor_partner1.id,
58 'price': 648.0,
59 'delay': 5
60 })
61 self.env['product.supplierinfo'].create({
62 'product_tmpl_id': self.comp2.product_tmpl_id.id,
63 'partner_id': self.subcontractor_partner1.id,
64 'price': 648.0,
65 'delay': 5
66 })
67
68 self.bom.produce_delay = 1
69 self.bom.days_to_prepare_mo = 3
70
71 # Add 4 units of each component to subcontractor's location
72 subcontractor_location = self.env.company.subcontracting_location_id
73 self.env['stock.quant']._update_available_quantity(self.comp1, subcontractor_location, 4)
74 self.env['stock.quant']._update_available_quantity(self.comp2, subcontractor_location, 4)
75
76 # Generate a report for 3 products: all products should be ready for production
77 bom_data = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, 3)
78
79 self.assertTrue(bom_data['lines']['components_available'])
80 for component in bom_data['lines']['components']:
81 self.assertEqual(component['quantity_on_hand'], 4)
82 self.assertEqual(component['availability_state'], 'available')
83
84 # Generate a report for 5 products: only 4 products should be ready for production
85 bom_data = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, 5)
86
87 self.assertFalse(bom_data['lines']['components_available'])
88 for component in bom_data['lines']['components']:
89 self.assertEqual(component['quantity_on_hand'], 4)
90 self.assertEqual(component['availability_state'], 'estimated')
91
92 def test_count_smart_buttons(self):
93 resupply_sub_on_order_route = self.env['stock.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
94 (self.comp1 + self.comp2).write({'route_ids': [Command.link(resupply_sub_on_order_route.id)]})
95
96 # I create a draft Purchase Order for first in move for 10 kg at 50 euro
97 po = self.env['purchase.order'].create({
98 'partner_id': self.subcontractor_partner1.id,
99 'order_line': [Command.create({
100 'name': 'finished',
101 'product_id': self.finished.id,
102 'product_qty': 1.0,
103 'product_uom_id': self.finished.uom_id.id,
104 'price_unit': 50.0}
105 )],
106 })
107
108 po.button_confirm()
109
110 self.assertEqual(po.subcontracting_resupply_picking_count, 1)
111 action1 = po.action_view_subcontracting_resupply()
112 picking = self.env[action1['res_model']].browse(action1['res_id'])
113 self.assertEqual(picking.subcontracting_source_purchase_count, 1)
114 action2 = picking.action_view_subcontracting_source_purchase()
115 po_action2 = self.env[action2['res_model']].browse(action2['res_id'])
116 self.assertEqual(po_action2, po)
117
118 def test_decrease_qty(self):
119 """ Tests when a PO for a subcontracted product has its qty decreased after confirmation
120 """
121
122 product_qty = 5.0
123 po = self.env['purchase.order'].create({
124 'partner_id': self.subcontractor_partner1.id,
125 'order_line': [Command.create({
126 'name': 'finished',
127 'product_id': self.finished.id,
128 'product_qty': product_qty,
129 'product_uom_id': self.finished.uom_id.id,
130 'price_unit': 50.0}
131 )],
132 })
133
134 po.button_confirm()
135 receipt = po.picking_ids
136 sub_mo = receipt._get_subcontract_production()
137 self.assertEqual(len(receipt), 1, "A receipt should have been created")
138 self.assertEqual(receipt.move_ids.product_qty, product_qty, "Qty of subcontracted product to receive is incorrect")
139 self.assertEqual(len(sub_mo), 1, "A subcontracting MO should have been created")
140 self.assertEqual(sub_mo.product_qty, product_qty, "Qty of subcontracted product to produce is incorrect")
141
142 # create a neg qty to proprogate to receipt
143 lower_qty = product_qty - 1.0
144 po.order_line.product_qty = lower_qty
145 sub_mos = receipt._get_subcontract_production()
146 self.assertEqual(receipt.move_ids.product_qty, lower_qty, "Qty of subcontracted product to receive should update (not validated yet)")
147 self.assertEqual(len(sub_mos), 1, "Original subcontract MO should have absorbed qty change")
148 self.assertEqual(sub_mo.product_qty, lower_qty, "Qty of subcontract MO should update (none validated yet)")
149
150 # increase qty again
151 po.order_line.product_qty = product_qty
152 sub_mos = receipt._get_subcontract_production()
153 self.assertEqual(sum(receipt.move_ids.mapped('product_qty')), product_qty, "Qty of subcontracted product to receive should update (not validated yet)")
154 self.assertEqual(len(sub_mos), 1, "The subcontracted mo should have been updated")
155
156 # check that a neg qty can't proprogate once receipt is done
157 for move in receipt.move_ids:
158 move.move_line_ids.quantity = move.product_qty
159 receipt.move_ids.picked = True
160 receipt.button_validate()
161 self.assertEqual(receipt.state, 'done')
162 self.assertEqual(sub_mos.state, 'done')
163
164 def test_purchase_and_return01(self):
165 """
166 The user buys 10 x a subcontracted product P. He receives the 10
167 products and then does a return with 3 x P. The test ensures that the
168 final received quantity is correctly computed
169 """
170 po = self.env['purchase.order'].create({
171 'partner_id': self.subcontractor_partner1.id,
172 'order_line': [(0, 0, {
173 'name': self.finished2.name,
174 'product_id': self.finished2.id,
175 'product_uom_qty': 10,
176 'product_uom_id': self.finished2.uom_id.id,
177 'price_unit': 1,
178 })],
179 })
180 po.button_confirm()
181
182 mo = self.env['mrp.production'].search([('bom_id', '=', self.bom_finished2.id)])
183 self.assertTrue(mo)
184
185 receipt = po.picking_ids
186 receipt.move_ids.quantity = 10
187 receipt.move_ids.picked = True
188 receipt.button_validate()
189
190 return_form = Form(self.env['stock.return.picking'].with_context(active_id=receipt.id, active_model='stock.picking'))
191 return_wizard = return_form.save()
192 return_wizard.product_return_moves.quantity = 3
193 return_wizard.product_return_moves.to_refund = True
194 return_picking = return_wizard._create_return()
195 return_picking.move_ids.quantity = 3
196 return_picking.move_ids.picked = True
197 return_picking.button_validate()
198
199 self.assertEqual(self.finished2.qty_available, 7.0)
200 self.assertEqual(po.order_line.qty_received, 7.0)
201
202 def test_purchase_and_return02(self):
203 """
204 The user buys 10 x a subcontracted product P. He receives the 10
205 products and then does a return with 3 x P (with the flag to_refund
206 disabled and the subcontracting location as return location). The test
207 ensures that the final received quantity is correctly computed
208 """
209 grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
210 self.env.user.write({'group_ids': [(4, grp_multi_loc.id)]})
211
212 po = self.env['purchase.order'].create({
213 'partner_id': self.subcontractor_partner1.id,
214 'order_line': [(0, 0, {
215 'name': self.finished2.name,
216 'product_id': self.finished2.id,
217 'product_uom_qty': 10,
218 'product_uom_id': self.finished2.uom_id.id,
219 'price_unit': 1,
220 })],
221 })
222 po.button_confirm()
223
224 mo = self.env['mrp.production'].search([('bom_id', '=', self.bom_finished2.id)])
225 self.assertTrue(mo)
226
227 receipt = po.picking_ids
228 receipt.move_ids.quantity = 10
229 receipt.move_ids.picked = True
230 receipt.button_validate()
231
232 return_form = Form(self.env['stock.return.picking'].with_context(active_id=receipt.id, active_model='stock.picking'))
233 return_wizard = return_form.save()
234 return_wizard.product_return_moves.quantity = 3
235 return_wizard.product_return_moves.to_refund = False
236 return_picking = return_wizard._create_return()
237 return_picking.move_ids.quantity = 3
238 return_picking.move_ids.picked = True
239 return_picking.button_validate()
240
241 self.assertEqual(self.finished2.qty_available, 7.0)
242 self.assertEqual(po.order_line.qty_received, 10.0)
243
244 def test_subcontracting_purchase_bill(self):
245 (self.comp1 | self.comp2 | self.finished).categ_id = self.category_fifo_auto
246 self.finished.purchase_method = 'purchase'
247 po_form = Form(self.env['purchase.order'])
248 po_form.partner_id = self.subcontractor_partner1
249 with po_form.order_line.new() as po_line:
250 po_line.product_id = self.finished
251 po_line.product_qty = 2
252 po_line.price_unit = 50 # should be 70
253 po = po_form.save()
254 po.button_confirm()
255 # create bill
256 po.action_create_invoice()
257 aml = self.env['account.move.line'].search([('purchase_line_id', '=', po.order_line.id)])
258 # add 50 per unit ( 50 x 1 ) = 50 extra valuation
259 aml.price_unit = 60
260 aml.move_id.invoice_date = Date.today()
261 aml.move_id.action_post()
262 amls = self.env['account.move.line'].search([
263 ('product_id', 'in', (self.comp1 | self.comp2 | self.finished).ids)
264 ])
265 self.assertRecordValues(amls, [
266 {'account_id': self.account_stock_valuation.id, 'debit': 120, 'product_id': self.finished.id},
267 ])
268
269 # receive subcontracted product (MO will be done)
270 receipt = po.picking_ids
271 receipt.move_ids.picked = True
272 receipt.button_validate()
273 # Total value of subcontracted product = 60 new price + components (20 + 40)
274 self.assertEqual(self.finished.total_value, 180)
275 self.assertEqual(self.finished.standard_price, 90)
276 amls = self.env['account.move.line'].search([
277 ('product_id', 'in', (self.comp1 | self.comp2 | self.finished).ids)
278 ])
279 self.assertRecordValues(amls, [
280 {'account_id': self.account_production.id, 'debit': 0, 'credit': 60, 'product_id': self.finished.id},
281 {'account_id': self.account_stock_valuation.id, 'debit': 60, 'credit': 0, 'product_id': self.finished.id},
282 {'account_id': self.account_stock_valuation.id, 'debit': 0, 'credit': 20, 'product_id': self.comp1.id},
283 {'account_id': self.account_production.id, 'debit': 20, 'credit': 0, 'product_id': self.comp1.id},
284 {'account_id': self.account_stock_valuation.id, 'debit': 0, 'credit': 40, 'product_id': self.comp2.id},
285 {'account_id': self.account_production.id, 'debit': 40, 'credit': 0, 'product_id': self.comp2.id},
286 {'account_id': self.account_stock_valuation.id, 'debit': 120, 'credit': 0, 'product_id': self.finished.id},
287 ])
288
289 def test_subcontracting_resupply_price_diff(self):
290 """Test that the price difference is correctly computed when a subcontracted
291 product is resupplied.
292 """
293 (self.comp1 | self.comp2 | self.finished).categ_id = self.category_standard_auto
294
295 stock_price_diff_acc_id = self.env['account.account'].create({
296 'name': 'default_account_stock_price_diff',
297 'code': 'STOCKDIFF',
298 'reconcile': True,
299 'account_type': 'asset_current',
300 })
301 self.finished.categ_id.property_price_difference_account_id = stock_price_diff_acc_id
302
303 self.comp1.standard_price = 10.0
304 self.comp2.standard_price = 20.0
305 self.finished.standard_price = 100
306
307 # Create a PO for 1 finished product.
308 po_form = Form(self.env['purchase.order'])
309 po_form.partner_id = self.subcontractor_partner1
310 with po_form.order_line.new() as po_line:
311 po_line.product_id = self.finished
312 po_line.product_qty = 2
313 po_line.price_unit = 50
314 po = po_form.save()
315 po.button_confirm()
316
317 action = po.action_view_subcontracting_resupply()
318 resupply_picking = self.env[action['res_model']].browse(action['res_id'])
319 resupply_picking.move_ids.quantity = 2
320 resupply_picking.move_ids.picked = True
321 resupply_picking.button_validate()
322
323 action = po.action_view_picking()
324 final_picking = self.env[action['res_model']].browse(action['res_id'])
325 final_picking.move_ids.quantity = 2
326 final_picking.move_ids.picked = True
327 final_picking.button_validate()
328
329 action = po.action_create_invoice()
330 invoice = self.env['account.move'].browse(action['res_id'])
331 invoice.invoice_date = Date.today()
332 invoice.invoice_line_ids.quantity = 1
333 invoice.action_post()
334
335 # price diff line should be 50 - 100 + 10 + 20
336 price_diff_line = invoice.line_ids.filtered(lambda m: m.account_id == stock_price_diff_acc_id)
337 self.assertEqual(price_diff_line.credit, 20)
338
339 def test_subcontracting_multi_currency_price_diff(self):
340 """ Ensure the price difference lines are computed correctly when the company
341 currency and invoice currency differ
342 """
343 currency_grp = self.env.ref('base.group_multi_currency')
344 self.env.user.write({'group_ids': [(4, currency_grp.id)]})
345
346 self.env.company.anglo_saxon_accounting = True
347 product_category_all = self.product_category
348 product_category_all.property_cost_method = 'standard'
349 product_category_all.property_valuation = 'real_time'
350 self._setup_category_stock_journals()
351
352 stock_price_diff_acc_id = self.env['account.account'].create({
353 'name': 'default_account_stock_price_diff',
354 'code': 'STOCKDIFF',
355 'reconcile': True,
356 'account_type': 'asset_current',
357 })
358 product_category_all.property_price_difference_account_id = stock_price_diff_acc_id
359
360 self.comp1.standard_price = 10.0
361 self.comp2.standard_price = 20.0
362 self.finished.standard_price = 100
363
364 mock_currency = self.env['res.currency'].create({
365 'name': 'MOCK',
366 'symbol': 'MC',
367 })
368 self.env['res.currency.rate'].create({
369 'name': '2023-01-01',
370 'company_rate': 2.0,
371 'currency_id': mock_currency.id,
372 'company_id': self.env.company.id,
373 })
374
375 # Create a PO for 1 finished product.
376 po_form = Form(self.env['purchase.order'])
377 po_form.partner_id = self.subcontractor_partner1
378 po_form.currency_id = mock_currency
379 with po_form.order_line.new() as po_line:
380 po_line.product_id = self.finished
381 po_line.product_qty = 1
382 # Ideally, 100 - 10 - 20 = 70 USD
383 # We will create a price diff of 10 USD
384 # 60 USD * 2 = 120 MC
385 po_line.price_unit = 120
386 po = po_form.save()
387 po.button_confirm()
388
389 action = po.action_view_picking()
390 final_picking = self.env[action['res_model']].browse(action['res_id'])
391 final_picking.move_ids.quantity = 1
392 final_picking.move_ids.picked = True
393 final_picking.button_validate()
394
395 action = po.action_create_invoice()
396 invoice = self.env['account.move'].browse(action['res_id'])
397 invoice.invoice_date = Date.today()
398 invoice.invoice_line_ids.quantity = 1
399 invoice.action_post()
400
401 # price diff line should be 100 - 60 - 10 - 20
402 price_diff_line = invoice.line_ids.filtered(lambda m: m.account_id == stock_price_diff_acc_id)
403 self.assertEqual(price_diff_line.credit, 10)
404
405 def test_subcontract_product_price_change(self):
406 """ Create a PO for subcontracted product, receive the product (finish MO),
407 create vendor bill and edit the product price, confirm the bill.
408 An extra SVL should be created to correct the valuation of the product
409 Also check account move data for real time inventory
410 """
411 (self.comp1 | self.comp2 | self.finished).categ_id = self.category_fifo_auto
412 purchase = self.env['purchase.order'].create({
413 'partner_id': self.subcontractor_partner1.id,
414 'order_line': [Command.create({
415 'name': self.finished.name,
416 'product_id': self.finished.id,
417 'product_uom_qty': 1,
418 'product_uom_id': self.finished.uom_id.id,
419 'price_unit': 100,
420 })],
421 })
422 purchase.button_confirm()
423 # receive subcontracted product (MO will be done)
424 receipt = purchase.picking_ids
425 receipt.move_ids.picked = True
426 receipt.button_validate()
427 self.assertEqual(self.finished.total_value, 130)
428 # create bill
429 purchase.action_create_invoice()
430 aml = self.env['account.move.line'].search([('purchase_line_id', '=', purchase.order_line.id)])
431 # add 50 per unit ( 50 x 1 ) = 50 extra valuation
432 aml.price_unit = 150
433 aml.move_id.invoice_date = Date.today()
434 aml.move_id.action_post()
435 # Total value of subcontracted product should be updated by the invoice
436 self.assertEqual(self.finished.total_value, 180)
437 self.assertEqual(self.finished.standard_price, 180)
438
439 def test_return_and_decrease_pol_qty(self):
440 """
441 Buy and receive 10 subcontracted products. Return one. Then adapt the
442 demand on the PO to 9.
443 """
444 po = self.env['purchase.order'].create({
445 'partner_id': self.subcontractor_partner1.id,
446 'order_line': [(0, 0, {
447 'name': self.finished2.name,
448 'product_id': self.finished2.id,
449 'product_qty': 10,
450 'product_uom_id': self.finished2.uom_id.id,
451 'price_unit': 1,
452 })],
453 })
454 po.button_confirm()
455
456 receipt = po.picking_ids
457 receipt.move_ids.quantity = 10
458 receipt.button_validate()
459
460 return_form = Form(self.env['stock.return.picking'].with_context(active_id=receipt.id, active_model='stock.picking'))
461 wizard = return_form.save()
462 wizard.product_return_moves.quantity = 1.0
463 return_picking = wizard._create_return()
464 return_picking.move_ids.quantity = 1.0
465 return_picking.button_validate()
466
467 pol = po.order_line
468 pol.product_qty = 9.0
469
470 self.assertEqual(pol.qty_received, 9.0)
471 self.assertEqual(pol.product_qty, 9.0)
472 self.assertEqual(len(po.picking_ids), 2)
473 warehouse = po.picking_ids.move_ids.warehouse_id
474 self.assertRecordValues(po.picking_ids.move_ids, [
475 {'location_dest_id': warehouse.lot_stock_id.id, 'quantity': 10.0, 'state': 'done'},
476 {'location_dest_id': self.company.subcontracting_location_id.id, 'quantity': 1.0, 'state': 'done'},
477 ])
478
479 def test_subcontracting_lead_days(self):
480 """ Test the lead days computation for subcontracting. Subcontracting delay =
481 max(Vendor lead time, Manufacturing lead time + DTPMO) + Days to Purchase
482 """
483 rule = self.env['stock.rule'].search([
484 ('action', '=', 'buy'),
485 ('company_id', '=', self.company.id),
486 ], limit=1)
487
488 self.company.days_to_purchase = 2
489 # Case 1 Vendor lead time >= Manufacturing lead time + DTPMO
490 seller = self.env['product.supplierinfo'].create({
491 'product_tmpl_id': self.finished.product_tmpl_id.id,
492 'partner_id': self.subcontractor_partner1.id,
493 'price': 12.0,
494 'delay': 10,
495 })
496
497 self.bom.produce_delay = 3
498 self.bom.days_to_prepare_mo = 4
499 delays, _ = rule._get_lead_days(self.finished, supplierinfo=seller)
500 self.assertEqual(delays['total_delay'], seller.delay + self.company.days_to_purchase)
501 # Case 2 Vendor lead time < Manufacturing lead time + DTPMO
502 self.bom.produce_delay = 5
503 self.bom.days_to_prepare_mo = 6
504 delays, _ = rule._get_lead_days(self.finished, supplierinfo=seller)
505 self.assertEqual(delays['total_delay'], self.bom.produce_delay + self.bom.days_to_prepare_mo + self.company.days_to_purchase)
506
507 def test_subcontracting_lead_days_on_overview(self):
508 """Test on the BOM overview, the lead days and resupply availability are
509 correctly computed. The dtpmo on the bom should be used for the lead days,
510 while the resupply availability should be based on the calculated dtpmo.
511 """
512 # should be added in all cases
513 self.company.days_to_purchase = 5
514 self.comp2.bom_ids.unlink()
515
516 self.env['product.supplierinfo'].create({
517 'product_tmpl_id': self.finished.product_tmpl_id.id,
518 'partner_id': self.subcontractor_partner1.id,
519 'price': 648.0,
520 'delay': 15
521 })
522 self.env['product.supplierinfo'].create({
523 'product_tmpl_id': self.comp1.product_tmpl_id.id,
524 'partner_id': self.subcontractor_partner1.id,
525 'price': 648.0,
526 'delay': 10
527 })
528 self.env['product.supplierinfo'].create({
529 'product_tmpl_id': self.comp2.product_tmpl_id.id,
530 'partner_id': self.subcontractor_partner1.id,
531 'price': 648.0,
532 'delay': 6
533 })
534 self.bom.produce_delay = 10
535 self.bom.days_to_prepare_mo = 0
536
537 # Case 1: Vendor lead time >= Manufacturing lead time + DTPMO on BOM
538 bom_data = self.env['report.mrp.report_bom_structure']._get_bom_data(self.bom, self.warehouse, self.finished)
539 self.assertEqual(bom_data['lead_time'], 15 + 5 + 0,
540 "Lead time = Purchase lead time(finished) + Days to Purchase + DTPMO on BOM")
541 # Resupply delay = 0 (received from MRP, where route type != "manufacture")
542 # Vendor lead time = 10 (finished product supplier delay)
543 # Manufacture lead time = 10 (BoM.produce_delay)
544 # Max purchase component delay = max delay(comp1, comp2) + days_to_purchase = 20
545 self.assertEqual(bom_data['resupply_avail_delay'], 0 + 10 + 20 + 5,
546 'Resupply avail delay = Resupply delay + Max(Vendor lead time, Manufacture lead time)'
547 ' + Max purchase component delay + Days to Purchase'
548 )
549
550 # Case 2: Vendor lead time < Manufacturing lead time + DTPMO on BOM
551 self.bom.action_compute_bom_days()
552 self.assertEqual(self.bom.days_to_prepare_mo, 10 + 5,
553 "DTPMO = Purchase lead time(comp1) + Days to Purchase")
554
555 self.bom.days_to_prepare_mo = 10
556 # Temp increase BoM.produce_delay, to check if it is now used in the final calculation
557 self.bom.produce_delay = 30
558
559 bom_data = self.env['report.mrp.report_bom_structure']._get_bom_data(self.bom, self.warehouse, self.finished)
560 self.assertEqual(bom_data['lead_time'], 30 + 5 + 10,
561 "Lead time = Manufacturing lead time + Days to Purchase + DTPMO on BOM")
562 # Resupply delay = 0 (received from MRP, where route type != "manufacture")
563 # Vendor lead time = 15 (finished product supplier delay)
564 # Manufacture lead time = 30 (BoM.produce_delay)
565 # Max purchase component delay = max delay(comp1, comp2) + days_to_purchase = 15
566 self.assertEqual(bom_data['resupply_avail_delay'], 0 + 30 + 15 + 5,
567 'Resupply avail delay = Resupply delay + Max(Vendor lead time, Manufacture lead time)'
568 ' + Max purchase component delay + Days to Purchase'
569 )
570 # Continue the test with the original produce_delay
571 self.bom.produce_delay = 10
572
573 # Update stock for components, calculate DTPMO should be 0
574 self.env['stock.quant']._update_available_quantity(self.comp1, self.company.subcontracting_location_id, 100)
575 self.env['stock.quant']._update_available_quantity(self.comp2, self.company.subcontracting_location_id, 100)
576 self.env.invalidate_all() # invalidate cache to get updated qty_available
577 # Case 1: Vendor lead time >= Manufacturing lead time + DTPMO on BOM
578 self.bom.days_to_prepare_mo = 2
579 bom_data = self.env['report.mrp.report_bom_structure']._get_bom_data(self.bom, self.warehouse, self.finished)
580 self.assertEqual(bom_data['lead_time'], 15 + 5,
581 "Lead time = Purchase lead time(finished) + Days to Purchase")
582 for component in bom_data['components']:
583 self.assertEqual(component['availability_state'], 'available')
584 # Case 2: Vendor lead time < Manufacturing lead time + DTPMO on BOM
585 self.bom.action_compute_bom_days()
586 self.assertEqual(self.bom.days_to_prepare_mo, 10 + 5,
587 "DTPMO = Purchase lead time(comp1) + Days to Purchase")
588 bom_data = self.env['report.mrp.report_bom_structure']._get_bom_data(self.bom, self.warehouse, self.finished)
589 self.assertEqual(bom_data['lead_time'], 10 + 5 + 15,
590 "Lead time = Manufacturing lead time + Days to Purchase + DTPMO on BOM")
591 for component in bom_data['components']:
592 self.assertEqual(component['availability_state'], 'available')
593
594 def test_resupply_order_buy_mto(self):
595 """ Test a subcontract component can has resupply on order + buy + mto route"""
596 mto_route = self.env.ref('stock.route_warehouse0_mto')
597 mto_route.active = True
598 resupply_sub_on_order_route = self.env['stock.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
599 self.comp2.bom_ids.unlink()
600 (self.comp1 | self.comp2).write({
601 'route_ids': [
602 Command.link(resupply_sub_on_order_route.id),
603 Command.link(mto_route.id)],
604 'seller_ids': [Command.create({
605 'partner_id': self.vendor.id,
606 })],
607 })
608
609 po = self.env['purchase.order'].create({
610 'partner_id': self.subcontractor_partner1.id,
611 'order_line': [Command.create({
612 'name': 'finished',
613 'product_id': self.finished.id,
614 'product_qty': 1.0,
615 'product_uom_id': self.finished.uom_id.id,
616 'price_unit': 50.0}
617 )],
618 })
619
620 po.picking_type_id.warehouse_id.route_ids = [Command.link(self.env.ref('mrp_subcontracting.route_resupply_subcontractor_mto').id)]
621 po.button_confirm()
622 ressuply_pick = self.env['stock.picking'].search([('location_dest_id', '=', self.company.subcontracting_location_id.id)])
623 self.assertEqual(len(ressuply_pick.move_ids), 2)
624 self.assertEqual(ressuply_pick.move_ids.mapped('product_id'), self.comp1 | self.comp2)
625
626 # should have create a purchase order for the components
627 comp_po = self.env['purchase.order'].search([('partner_id', '=', self.vendor.id)])
628 self.assertEqual(len(comp_po.order_line), 2)
629 self.assertEqual(comp_po.order_line.mapped('product_id'), self.comp1 | self.comp2)
630 # confirm the po should create stock moves linked to the resupply
631 comp_po.button_confirm()
632 comp_receipt = comp_po.picking_ids
633 self.assertEqual(comp_receipt.move_ids.move_dest_ids, ressuply_pick.move_ids)
634
635 # validate the comp receipt should reserve the resupply
636 self.assertEqual(ressuply_pick.state, 'waiting')
637 comp_receipt.move_ids.quantity = 1
638 comp_receipt.move_ids.picked = True
639 comp_receipt.button_validate()
640 self.assertEqual(ressuply_pick.state, 'assigned')
641
642 def test_update_qty_purchased_with_subcontracted_product(self):
643 """
644 Test That we can update the quantity of a purchase order line with a subcontracted product
645 """
646 mto_route = self.env.ref('stock.route_warehouse0_mto')
647 mto_route.active = True
648 self.comp2.bom_ids.unlink()
649 self.finished.route_ids = mto_route.ids
650 self.env['product.supplierinfo'].create({
651 'product_id': self.finished.id,
652 'partner_id': self.vendor.id,
653 'price': 12.0,
654 'delay': 0
655 })
656
657 mo = self.env['mrp.production'].create({
658 'product_id': self.finished2.id,
659 'product_qty': 3.0,
660 'move_raw_ids': [(0, 0, {
661 'product_id': self.finished.id,
662 'product_uom_qty': 3.0,
663 'product_uom': self.finished.uom_id.id,
664 })]
665 })
666 mo.action_confirm()
667 po = self.env['purchase.order.line'].search([('product_id', '=', self.finished.id)]).order_id
668 po.button_confirm()
669 self.assertEqual(len(po.picking_ids), 1)
670 picking = po.picking_ids
671 picking.move_ids.quantity = 2.0
672 # When we validate the picking manually, we create a backorder.
673 Form.from_action(self.env, picking.button_validate()).save().process()
674 self.assertEqual(len(po.picking_ids), 2)
675 picking.backorder_ids.action_cancel()
676 self.assertEqual(picking.backorder_ids.state, 'cancel')
677 po.order_line.product_qty = 2.0
678 self.assertEqual(po.order_line.product_qty, 2.0)
679
680 def test_mrp_report_bom_structure_subcontracting_quantities(self):
681 """Testing quantities and availablility states in subcontracted BoM report
682 1. Create a BoM of a finished product with a single component
683 2. Update the on hand quantity of BoM to 100
684 3. Move 20 components to subcontracting location
685 4. Check that the free/on-hand quantity of component is 100 (sum of warehouse stock and subcontracting location stock)
686 5. Check that producible quantity of 'Product' is equal to only subcontractor location stock
687 6. Check availability states when:
688 6a. Search quantity <= subcontractor quantity: component is available
689 6b. Subcontractor quantity <= search quantity <= total quantity: component is available
690 6c. Total quantity < search quantity: component is unavailable
691 """
692 search_qty_less_than_or_equal_moved = 10
693 moved_quantity_to_subcontractor = 20
694 total_component_quantity = 100
695 search_qty_more_than_total = 110
696
697 resupply_route = self.env['stock.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
698 finished, component = self.env['product.product'].create([{
699 'name': 'Finished Product',
700 'is_storable': True,
701 'seller_ids': [(0, 0, {'partner_id': self.subcontractor_partner1.id})]
702 }, {
703 'name': 'Component',
704 'is_storable': True,
705 'route_ids': [(4, resupply_route.id)],
706 }])
707
708 bom = self.env['mrp.bom'].create({
709 'product_tmpl_id': finished.product_tmpl_id.id,
710 'product_qty': 1.0,
711 'type': 'subcontract',
712 'subcontractor_ids': [(4, self.subcontractor_partner1.id)],
713 'bom_line_ids': [(0, 0, {'product_id': component.id, 'product_qty': 1.0})],
714 })
715
716 self.env['stock.quant']._update_available_quantity(component, self.warehouse.lot_stock_id, total_component_quantity)
717 # Check quantity was updated
718 self.assertEqual(component.virtual_available, total_component_quantity)
719 self.assertEqual(component.qty_available, total_component_quantity)
720
721 quantity_before_move = self.env['stock.quant']._get_available_quantity(component, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
722 picking_form = Form(self.env['stock.picking'])
723 picking_form.picking_type_id = self.warehouse.subcontracting_resupply_type_id
724 picking_form.partner_id = self.subcontractor_partner1
725 with picking_form.move_ids.new() as move:
726 move.product_id = component
727 move.product_uom_qty = moved_quantity_to_subcontractor
728 picking = picking_form.save()
729 picking.action_confirm()
730 picking.move_ids.quantity = moved_quantity_to_subcontractor
731 picking.move_ids.picked = True
732 picking.button_validate()
733 quantity_after_move = self.env['stock.quant']._get_available_quantity(component, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
734 self.assertEqual(quantity_after_move, quantity_before_move + moved_quantity_to_subcontractor)
735
736 report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom.id, searchQty=search_qty_less_than_or_equal_moved, searchVariant=False)
737 self.assertEqual(report_values['lines']['components'][0]['quantity_available'], moved_quantity_to_subcontractor)
738 self.assertEqual(report_values['lines']['components'][0]['quantity_on_hand'], moved_quantity_to_subcontractor)
739 self.assertEqual(report_values['lines']['quantity_available'], 0)
740 self.assertEqual(report_values['lines']['quantity_on_hand'], 0)
741 self.assertEqual(report_values['lines']['producible_qty'], moved_quantity_to_subcontractor)
742 self.assertEqual(report_values['lines']['stock_avail_state'], 'unavailable')
743
744 self.assertEqual(report_values['lines']['components'][0]['stock_avail_state'], 'available')
745
746 report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom.id, searchQty=search_qty_less_than_or_equal_moved, searchVariant=False)
747 self.assertEqual(report_values['lines']['components'][0]['stock_avail_state'], 'available')
748
749 report_values = self.env['report.mrp.report_bom_structure']._get_report_data(bom.id, searchQty=search_qty_more_than_total, searchVariant=False)
750 self.assertEqual(report_values['lines']['components'][0]['stock_avail_state'], 'unavailable')
751
752 # TODO: po_lead doesn't exist anymore, remove?
753 def test_bom_overview_availability_po_lead(self):
754 # Create routes for components and the main product
755 self.comp2.bom_ids.unlink()
756 self.env['product.supplierinfo'].create({
757 'product_tmpl_id': self.finished.product_tmpl_id.id,
758 'partner_id': self.subcontractor_partner1.id,
759 'delay': 10
760 })
761 self.env['product.supplierinfo'].create({
762 'product_tmpl_id': self.comp1.product_tmpl_id.id,
763 'partner_id': self.subcontractor_partner1.id,
764 'delay': 5
765 })
766 self.env['product.supplierinfo'].create({
767 'product_tmpl_id': self.comp2.product_tmpl_id.id,
768 'partner_id': self.subcontractor_partner1.id,
769 'delay': 5
770 })
771
772 self.bom.produce_delay = 1
773 self.bom.days_to_prepare_mo = 3
774
775 # Add 4 units of each component to subcontractor's location
776 subcontractor_location = self.env.company.subcontracting_location_id
777 self.env['stock.quant']._update_available_quantity(self.comp1, subcontractor_location, 4)
778 self.env['stock.quant']._update_available_quantity(self.comp2, subcontractor_location, 4)
779
780 # Generate a report for 3 products: all products should be ready for production
781 bom_data = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, 3)
782
783 self.assertTrue(bom_data['lines']['components_available'])
784 for component in bom_data['lines']['components']:
785 self.assertEqual(component['quantity_on_hand'], 4)
786 self.assertEqual(component['availability_state'], 'available')
787
788 # Generate a report for 5 products: only 4 products should be ready for production
789 bom_data = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, 5)
790
791 self.assertFalse(bom_data['lines']['components_available'])
792 for component in bom_data['lines']['components']:
793 self.assertEqual(component['quantity_on_hand'], 4)
794 self.assertEqual(component['availability_state'], 'estimated')
795
796 def test_location_after_dest_location_update_backorder_production(self):
797 """
798 Buy 2 subcontracted products.
799 Receive 1 product after changing the destination location.
800 Create a backorder.
801 Receive the last one.
802 Check the locations.
803 """
804 grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
805 self.env.user.write({'group_ids': [Command.link(grp_multi_loc.id)]})
806 subcontract_loc = self.env.company.subcontracting_location_id
807 production_loc = self.finished.property_stock_production
808 final_loc = self.env['stock.location'].create({
809 'name': 'Final location',
810 'location_id': self.warehouse.lot_stock_id.id,
811 })
812 # buy 2 subcontracted products
813 po = self.env['purchase.order'].create({
814 'partner_id': self.subcontractor_partner1.id,
815 'order_line': [Command.create({
816 'name': self.finished.name,
817 'product_id': self.finished.id,
818 'product_qty': 2.0,
819 'product_uom_id': self.finished.uom_id.id,
820 'price_unit': 1.0,
821 })],
822 })
823 po.button_confirm()
824
825 receipt = po.picking_ids
826 # receive 1 subcontracted product
827 receipt.move_ids.quantity = 1
828 receipt_form = Form(receipt)
829 # change the destination location
830 receipt_form.location_dest_id = final_loc
831 receipt_form.save()
832 # change the destination location on the move line too
833 receipt.move_line_ids.location_dest_id = final_loc
834 # create the backorder
835 Form.from_action(self.env, receipt.button_validate()).save().process()
836 backorder = receipt.backorder_ids
837 # test the stock quantities after receiving 1 product
838 stock_quants = self.env['stock.quant'].search([('product_id', '=', self.finished.id)])
839 self.assertEqual(len(stock_quants), 3)
840 self.assertEqual(stock_quants.filtered(lambda q: q.location_id == final_loc).quantity, 1.0)
841 self.assertEqual(stock_quants.filtered(lambda q: q.location_id == subcontract_loc).quantity, 0.0)
842 self.assertEqual(stock_quants.filtered(lambda q: q.location_id == production_loc).quantity, -1.0)
843 # receive the last subcontracted product
844 backorder.move_ids.quantity = 1
845 backorder.button_validate()
846 # test the final stock quantities
847 stock_quants = self.env['stock.quant'].search([('product_id', '=', self.finished.id)])
848 self.assertEqual(len(stock_quants), 3)
849 self.assertEqual(stock_quants.filtered(lambda q: q.location_id == final_loc).quantity, 2.0)
850 self.assertEqual(stock_quants.filtered(lambda q: q.location_id == subcontract_loc).quantity, 0.0)
851 self.assertEqual(stock_quants.filtered(lambda q: q.location_id == production_loc).quantity, -2.0)
852
853 def test_return_subcontracted_product_to_supplier_location(self):
854 """
855 Test that we can return subcontracted product to the supplier location.
856 """
857 po = self.env['purchase.order'].create({
858 'partner_id': self.subcontractor_partner1.id,
859 'order_line': [Command.create({
860 'name': self.finished.name,
861 'product_id': self.finished.id,
862 'product_qty': 2.0,
863 'product_uom_id': self.finished.uom_id.id,
864 'price_unit': 10.0,
865 })],
866 })
867
868 po.button_confirm()
869 self.assertEqual(len(po.picking_ids), 1)
870 picking = po.picking_ids
871 picking.button_validate()
872 self.assertEqual(picking.state, 'done')
873 # create a return to the vendor location
874 supplier_location = self.env.ref('stock.stock_location_suppliers')
875 return_form = Form(self.env['stock.return.picking'].with_context(active_id=picking.id, active_model='stock.picking'))
876 wizard = return_form.save()
877 wizard.product_return_moves.quantity = 2.0
878 return_picking = wizard._create_return()
879 return_picking.location_dest_id = supplier_location
880 return_picking.button_validate()
881 self.assertEqual(return_picking.state, 'done')
882
883 def test_global_horizon_days_affect_lead_time(self):
884 """ Don't count global horizon days more than once, make sure a PO generated from
885 replenishment/orderpoint has a sensible planned reception date.
886 """
887 wh = self.warehouse
888 self.finished2.seller_ids = [Command.create({
889 'partner_id': self.subcontractor_partner1.id,
890 'delay': 0,
891 })]
892 final_product = self.finished2
893 orderpoint = self.env['stock.warehouse.orderpoint'].create({'product_id': final_product.id})
894 out_picking = self.env['stock.picking'].create({
895 'picking_type_id': wh.out_type_id.id,
896 'location_id': wh.lot_stock_id.id,
897 'location_dest_id': self.customer_location.id,
898 'move_ids': [Command.create({
899 'product_id': final_product.id,
900 'product_uom_qty': 2,
901 'location_id': wh.lot_stock_id.id,
902 'location_dest_id': self.customer_location.id,
903 })],
904 })
905 out_picking.with_context(global_horizon_days=365).action_assign()
906 r = orderpoint.action_stock_replenishment_info()
907 repl_info = self.env[r['res_model']].browse(r['res_id'])
908 lead_horizon_date = datetime.strptime(
909 loads(repl_info.with_context(global_horizon_days=365).json_lead_days)['lead_horizon_date'], '%m/%d/%Y').date()
910 self.assertEqual(lead_horizon_date, Date.today() + timedelta(days=365))
911
912 orderpoint.action_replenish()
913 purchase_order = self.env['purchase.order'].search([
914 ('order_line', 'any', [
915 ('product_id', '=', self.finished2.id),
916 ]),
917 ], limit=1)
918 self.assertEqual(purchase_order.date_planned.date(), Date.today())
919
920 @freeze_time('2000-05-01')
921 def test_mrp_subcontract_modify_date(self):
922 """ Ensure consistent results when modifying date fields of a weakly-linked reception and
923 manufacturing order. Additionally, modifying `date_start` directly on an MO has a
924 well-defined result.
925 """
926 self.bom_finished2.produce_delay = 35
927 po = self.env['purchase.order'].create({
928 'partner_id': self.subcontractor_partner1.id,
929 'order_line': [Command.create({
930 'name': self.finished2.name,
931 'product_id': self.finished2.id,
932 'product_qty': 10,
933 'product_uom_id': self.finished2.uom_id.id,
934 'price_unit': 1,
935 })],
936 })
937 po.button_confirm()
938 mo = po.picking_ids.move_ids.move_orig_ids.production_id
939 original_mo_start_date = mo.date_start
940 with Form(po.picking_ids[0]) as receipt_form:
941 receipt_form.scheduled_date = '2000-06-01'
942 self.assertEqual(mo.date_start, datetime(year=2000, month=6, day=1) - timedelta(days=self.bom_finished2.produce_delay))
943 with Form(po.picking_ids[0]) as receipt_form:
944 receipt_form.scheduled_date = '2000-05-01'
945 self.assertEqual(mo.date_start, original_mo_start_date)
946
947 with Form(mo) as production_form:
948 production_form.date_start = '2000-03-20'
949 self.assertEqual(mo.date_start.date(), Date.to_date('2000-03-20'))
950 with Form(mo) as production_form:
951 production_form.date_start = original_mo_start_date
952 self.assertEqual(mo.date_start, original_mo_start_date)
953
954 def test_create_invoice_with_subcontracted_tracked_products(self):
955 """ Ensure that invoice creation doesn't trigger an error
956 with subcontracted tracked products."""
957 todo_nb = 5
958 self.finished2.tracking = 'serial'
959 self.finished2.purchase_method = 'purchase'
960 po = self.env['purchase.order'].create({
961 'partner_id': self.subcontractor_partner1.id,
962 'order_line': [(0, 0, {
963 'product_id': self.finished2.id,
964 'product_qty': todo_nb,
965 'price_unit': 50,
966 })],
967 })
968
969 po.button_confirm()
970 picking_receipt = po.picking_ids
971 picking_receipt.do_unreserve()
972
973 serials_finished = []
974 for i in range(todo_nb):
975 serials_finished.append(self.env['stock.lot'].create({
976 'name': 'serial_fin_%s' % i,
977 'product_id': self.finished2.id,
978 }))
979
980 action = picking_receipt.move_ids.action_show_details()
981 with Form(picking_receipt.move_ids.with_context(action['context']), view=action['view_id']) as move_form:
982 for serial in serials_finished:
983 with move_form.move_line_ids.new() as move_line:
984 move_line.lot_id = serial
985 move_line.picked = True
986 move_line.quantity = 1
987 move_form.save()
988
989 picking_receipt.move_ids.picked = True
990 picking_receipt.button_validate()
991 self.assertEqual(picking_receipt.state, 'done')
992
993 po.action_create_invoice()
994 invoice = po.invoice_ids
995 self.assertTrue(invoice)