Debian Codegraph @

addons/purchase_stock/tests/test_stockvaluation.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4 import time
5 from datetime import datetime, timedelta
6 from freezegun import freeze_time
7 from unittest import skip
8 from unittest.mock import patch
9
10 import odoo
11 from odoo import fields, Command
12 from odoo.tests import Form
13 from odoo.tests.common import TransactionCase, tagged
14 from odoo.addons.account.tests.common import AccountTestInvoicingCommon
15 from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
16 from odoo.addons.stock.tests.common import TestStockCommon
17
18
19 @tagged('post_install', '-at_install')
20 @skip('Temporary to fast merge new valuation')
21 class TestStockValuationWithCOA(AccountTestInvoicingCommon):
22
23 def test_anglosaxon_valuation_price_total_diff_discount(self):
24 """
25 PO: price unit: 110
26 Inv: price unit: 100
27 discount: 10
28 """
29 self.env.company.anglo_saxon_accounting = True
30 self.product1.categ_id.property_cost_method = 'fifo'
31 self.product1.categ_id.property_valuation = 'real_time'
32
33 # Create PO
34 po_form = Form(self.env['purchase.order'])
35 po_form.partner_id = self.partner_id
36 with po_form.order_line.new() as po_line:
37 po_line.product_id = self.product1
38 po_line.product_qty = 1
39 po_line.price_unit = 110.0
40 order = po_form.save()
41 order.button_confirm()
42
43 # Receive the goods
44 receipt = order.picking_ids[0]
45 receipt.move_ids.quantity = 1
46 receipt.move_ids.picked = True
47 receipt.button_validate()
48
49 # Create an invoice with a different price and a discount
50 invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
51 invoice_form.invoice_date = invoice_form.date
52 invoice_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-order.id)
53 with invoice_form.invoice_line_ids.edit(0) as line_form:
54 line_form.price_unit = 100.0
55 line_form.discount = 10.0
56 invoice = invoice_form.save()
57 invoice.action_post()
58
59 # Check what was posted in the stock valuation account
60 stock_valuation_aml = self.env['account.move.line'].search([('account_id', '=', self.stock_valuation_account.id)])
61 self.assertEqual(
62 len(stock_valuation_aml), 2,
63 "Two lines for the stock valuation account: one from the receipt (debit 110) and one from the bill (credit 20)")
64 self.assertAlmostEqual(sum(stock_valuation_aml.mapped('debit')), 110)
65 self.assertAlmostEqual(sum(stock_valuation_aml.mapped('credit')), 20, msg="Credit of 20 because of the difference between the PO and its invoice")
66
67 # Check what was posted in stock input account
68 input_aml = self.env['account.move.line'].search([('account_id','=', self.stock_input_account.id)])
69 self.assertEqual(len(input_aml), 3, "Only two lines should have been generated in stock input account: one when receiving the product, two when making the invoice.")
70 self.assertAlmostEqual(sum(input_aml.mapped('debit')), 110, msg="Total debit value on stock input account should be equal to the original PO price of the product.")
71 self.assertAlmostEqual(sum(input_aml.mapped('credit')), 110, msg="Total credit value on stock input account should be equal to the original PO price of the product.")
72
73 def test_anglosaxon_valuation_discount(self):
74 """
75 PO: price unit: 100
76 Inv: price unit: 100
77 discount: 10
78 """
79 self.env.company.anglo_saxon_accounting = True
80 self.product1.categ_id.property_cost_method = 'fifo'
81 self.product1.categ_id.property_valuation = 'real_time'
82
83 # Create PO
84 po_form = Form(self.env['purchase.order'])
85 po_form.partner_id = self.partner_id
86 with po_form.order_line.new() as po_line:
87 po_line.product_id = self.product1
88 po_line.product_qty = 1
89 po_line.price_unit = 100.0
90 order = po_form.save()
91 order.button_confirm()
92
93 # Receive the goods
94 receipt = order.picking_ids[0]
95 receipt.move_ids.quantity = 1
96 receipt.move_ids.picked = True
97 receipt.button_validate()
98
99 # Create an invoice with a different price and a discount
100 invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
101 invoice_form.invoice_date = invoice_form.date
102 invoice_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-order.id)
103 with invoice_form.invoice_line_ids.edit(0) as line_form:
104 line_form.tax_ids.clear()
105 line_form.discount = 10.0
106 invoice = invoice_form.save()
107 invoice.action_post()
108
109 # Check what was posted in the stock valuation account
110 stock_valuation_aml = self.env['account.move.line'].search([('account_id', '=', self.stock_valuation_account.id)])
111 self.assertEqual(len(stock_valuation_aml), 2, "Only one line should have been generated in the price difference account.")
112 self.assertAlmostEqual(sum(stock_valuation_aml.mapped('debit')), 100)
113 self.assertAlmostEqual(sum(stock_valuation_aml.mapped('credit')), 10, msg="Credit of 10 because of the 10% discount")
114
115 # Check what was posted in stock input account
116 input_aml = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)])
117 self.assertEqual(len(input_aml), 3, "Three lines generated in stock input account: one when receiving the product, two when making the invoice.")
118 self.assertAlmostEqual(sum(input_aml.mapped('debit')), 100, msg="Total debit value on stock input account should be equal to the original PO price of the product.")
119 self.assertAlmostEqual(sum(input_aml.mapped('credit')), 100, msg="Total credit value on stock input account should be equal to the original PO price of the product.")
120
121 def test_anglosaxon_valuation_price_unit_diff_discount(self):
122 """
123 PO: price unit: 90
124 Inv: price unit: 100
125 discount: 10
126 """
127 self.env.company.anglo_saxon_accounting = True
128 self.product1.categ_id.property_cost_method = 'fifo'
129 self.product1.categ_id.property_valuation = 'real_time'
130
131 # Create PO
132 po_form = Form(self.env['purchase.order'])
133 po_form.partner_id = self.partner_id
134 with po_form.order_line.new() as po_line:
135 po_line.product_id = self.product1
136 po_line.product_qty = 1
137 po_line.price_unit = 90.0
138 order = po_form.save()
139 order.button_confirm()
140
141 # Receive the goods
142 receipt = order.picking_ids[0]
143 receipt.move_ids.quantity = 1
144 receipt.move_ids.picked = True
145 receipt.button_validate()
146
147 # Create an invoice with a different price and a discount
148 invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
149 invoice_form.invoice_date = invoice_form.date
150 invoice_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-order.id)
151 with invoice_form.invoice_line_ids.edit(0) as line_form:
152 line_form.price_unit = 100.0
153 line_form.discount = 10.0
154 invoice = invoice_form.save()
155 invoice.action_post()
156
157 # Check if something was posted in the price difference account
158 price_diff_aml = self.env['account.move.line'].search([('account_id', '=', self.stock_valuation_account.id)])
159 self.assertEqual(price_diff_aml.debit, 90, "Should have only one line in the stock valuation account, created by the receipt.")
160
161 # Check what was posted in stock input account
162 input_aml = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)])
163 self.assertEqual(len(input_aml), 2, "Only two lines should have been generated in stock input account: one when receiving the product, one when making the invoice.")
164 self.assertAlmostEqual(sum(input_aml.mapped('debit')), 90, "Total debit value on stock input account should be equal to the original PO price of the product.")
165 self.assertAlmostEqual(sum(input_aml.mapped('credit')), 90, "Total credit value on stock input account should be equal to the original PO price of the product.")
166
167 def test_anglosaxon_valuation_price_unit_diff_avco(self):
168 """
169 Inv: price unit: 100
170 """
171 self.env.company.anglo_saxon_accounting = True
172 self.product1.categ_id.property_cost_method = 'average'
173 self.product1.categ_id.property_valuation = 'real_time'
174 self.product1.standard_price = 1.01
175
176 invoice = self.env['account.move'].create({
177 'move_type': 'in_invoice',
178 'invoice_date': '2022-03-31',
179 'partner_id': self.partner_id.id,
180 'invoice_line_ids': [
181 (0, 0, {'product_id': self.product1.id, 'quantity': 10.50, 'price_unit': 1.01, 'tax_ids': self.tax_purchase_a.ids})
182 ]
183 })
184
185 # Check if something was posted in the stock valuation account.
186 stock_val_aml = invoice.line_ids.filtered(lambda l: l.account_id == self.stock_valuation_account)
187 self.assertEqual(len(stock_val_aml), 0, "No line should have been generated in the stock valuation account.")
188
189 def test_price_diff_with_partial_bills_and_delivered_qties(self):
190 """
191 Fifo + Real time.
192 Default UoM of the product is Unit.
193 Company in USD. 1 USD = 2 EUR.
194 Receive 10 Hundred @ $50:
195 Receive 7 Hundred (R1)
196 Receive 3 Hundred (R2)
197 Deliver 5 Hundred
198 Bill
199 1 Hundred @ 120€ -> already out
200 3 Hundred @ 120€ -> already out
201 2 Hundred @ 120€ -> one is out, the other is in the stock
202 4 Hundred @ 120€ -> nothing out
203 When billing:
204 - The already-delivered qty should not generate any SVL for the
205 price difference and we should directly post some COGS entries
206 - The in-stock qty should generate an SVL for the price difference,
207 and we should post the journal entries related to that SVL
208 Deliver 2 Hundred
209 The SVL should include:
210 - 2 x 50 (cost by hundred)
211 - 2 x 10 (the price diff from step "Bill 2 Hundred @ 60" and "Bill
212 4 Hundred @ 60")
213 On top of that, make sure that everything will still work if the option
214 "Lock Posted Entries with Hash" is enabled on the stock journal
215 """
216 expected_svl_values = [] # USD
217 warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
218 stock_location = warehouse.lot_stock_id
219 customer_location = self.env.ref('stock.stock_location_customers')
220
221 eur_curr = self.env.ref('base.EUR')
222 self.env['res.currency.rate'].create({
223 'name': fields.Date.today(),
224 'company_id': self.env.company.id,
225 'currency_id': eur_curr.id,
226 'rate': 2,
227 })
228
229 grp_uom = self.env.ref('uom.group_uom')
230 self.env.user.write({'group_ids': [(4, grp_uom.id)]})
231 uom_unit = self.env.ref('uom.product_uom_unit')
232 uom_hundred = self.env['uom.uom'].create({
233 'name': '100 x U',
234 'relative_factor': 100.0,
235 'relative_uom_id': uom_unit.id,
236 })
237 self.product1.write({
238 'uom_id': uom_unit.id,
239 })
240
241 self.product1.categ_id.property_cost_method = 'fifo'
242 self.product1.categ_id.property_valuation = 'real_time'
243 self.product1.categ_id.property_stock_journal.restrict_mode_hash_table = True
244
245 po_form = Form(self.env['purchase.order'])
246 po_form.partner_id = self.partner_id
247 with po_form.order_line.new() as po_line:
248 po_line.product_id = self.product1
249 po_line.product_qty = 10
250 po_line.product_uom_id = uom_hundred
251 po_line.price_unit = 50.0
252 po = po_form.save()
253 po.button_confirm()
254
255 # Receive 7 Hundred
256 receipt01 = po.picking_ids[0]
257 receipt01.move_ids.move_line_ids.quantity = 700
258 receipt01.move_ids.picked = True
259 action = receipt01.button_validate()
260 backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(action['context'])).save()
261 backorder_wizard.process()
262
263 expected_svl_values += [7 * 50]
264 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
265
266 # Receive 3 Hundred
267 receipt02 = receipt01.backorder_ids
268 receipt02.move_ids.picked = True
269 receipt02.button_validate()
270
271 expected_svl_values += [3 * 50]
272 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
273
274 # Delivery 5 Hundred
275 delivery01 = self.env['stock.picking'].create({
276 'location_id': stock_location.id,
277 'location_dest_id': customer_location.id,
278 'picking_type_id': warehouse.out_type_id.id,
279 'move_ids': [(0, 0, {
280 'product_id': self.product1.id,
281 'product_uom_qty': 5,
282 'product_uom': uom_hundred.id,
283 'location_id': stock_location.id,
284 'location_dest_id': customer_location.id,
285 })],
286 'state': 'draft',
287 })
288 delivery01.action_confirm()
289 delivery01.move_ids.picked = True
290 delivery01.button_validate()
291
292 expected_svl_values += [-5 * 50]
293 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
294
295 # We will create a price diff SVL only for the remaining quantities not yet billed
296 # On the bill, price unit is 120€, i.e. $60 -> price diff equal to $10
297 expense_account = self.company_data['default_account_expense']
298 valuation_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_valuation_account.id)])
299 expense_amls = self.env['account.move.line'].search([('account_id', '=', expense_account.id)])
300 input_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)])
301 bills = self.env['account.move']
302 # pylint: disable=bad-whitespace
303 for qty, new_svl_expected, expected_valuations, expected_expenses in [
304 (1, [], [], [10.0]), # 1 hundred already out
305 (3, [], [], [30.0]), # 3 hundred already out
306 (2, [1 * 10.0], [10.0], [10.0]), # 1 hundred already out and 1 hundred in stock (from R1)
307 (4, [1 * 10.0, 3 * 10.0], [3 * 10.0, 1 * 10.0], []), # 4 hundred in stock, 1 from R1 and 3 from R2
308 ]:
309 bill_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
310 bill_form.invoice_date = bill_form.date
311 bill_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-po.id)
312 bill = bill_form.save()
313 bill.invoice_line_ids.quantity = qty
314 bill.invoice_line_ids.price_unit = 120.0
315 bill.invoice_line_ids.product_uom_id = uom_hundred
316 bill.currency_id = eur_curr
317 bill.action_post()
318
319 bills |= bill
320 err_msg = 'Incorrect while billing %s hundred' % qty
321
322 # stock side
323 expected_svl_values += new_svl_expected
324 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values, err_msg)
325
326 # account side
327 new_valuation_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_valuation_account.id), ('id', 'not in', valuation_amls.ids)])
328 new_expense_amls = self.env['account.move.line'].search([('account_id', '=', expense_account.id), ('id', 'not in', expense_amls.ids)])
329 new_input_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id), ('id', 'not in', input_amls.ids)])
330 valuation_amls |= new_valuation_amls
331 expense_amls |= new_expense_amls
332 input_amls |= new_input_amls
333
334 self.assertEqual(new_valuation_amls.mapped('debit'), expected_valuations, err_msg)
335 self.assertEqual(new_expense_amls.mapped('debit'), expected_expenses, err_msg)
336 self.assertEqual(new_input_amls.filtered(lambda aml: aml.credit > 0).mapped('credit'), expected_expenses + expected_valuations, err_msg)
337 self.assertEqual(new_input_amls.filtered(lambda aml: aml.debit > 0).debit, qty * 60, err_msg)
338
339 # All AML of Stock Interim Receipt should be reconciled
340 input_amls = bills.line_ids.filtered(lambda aml: aml.account_id == self.stock_input_account)
341 full_reconcile = input_amls[0].full_reconcile_id
342 self.assertTrue(full_reconcile)
343 self.assertTrue(all(aml.full_reconcile_id == full_reconcile for aml in input_amls))
344
345 # Delivery 2 Hundred
346 delivery02 = self.env['stock.picking'].create({
347 'location_id': stock_location.id,
348 'location_dest_id': customer_location.id,
349 'picking_type_id': warehouse.out_type_id.id,
350 'move_ids': [(0, 0, {
351 'product_id': self.product1.id,
352 'product_uom_qty': 2,
353 'product_uom': uom_hundred.id,
354 'location_id': stock_location.id,
355 'location_dest_id': customer_location.id,
356 })],
357 'state': 'draft',
358 })
359 delivery02.action_confirm()
360 delivery02.move_ids.picked = True
361 delivery02.button_validate()
362
363 expected_svl_values += [-2 * 50 + -2 * 10]
364 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
365
366 svl_r01, svl_r02, _svl_d01, svl_diff_01, svl_diff_02, svl_diff_03, _svl_d02 = self.product1.stock_valuation_layer_ids
367 self.assertEqual(svl_diff_01.stock_valuation_layer_id, svl_r01)
368 self.assertEqual(svl_diff_02.stock_valuation_layer_id, svl_r01)
369 self.assertEqual(svl_diff_03.stock_valuation_layer_id, svl_r02)
370
371 def test_partial_bills_and_reconciliation(self):
372 """
373 Fifo, Auto
374 Receive 5
375 Deliver 5
376 Bill 1 (with price diff)
377 Bill 4 (with price diff)
378 The lines in stock input account should be reconciled
379 """
380 self.product1.categ_id.property_cost_method = 'fifo'
381 self.product1.categ_id.property_valuation = 'real_time'
382
383 warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
384 stock_location = warehouse.lot_stock_id
385 customer_location = self.env.ref('stock.stock_location_customers')
386
387 po_form = Form(self.env['purchase.order'])
388 po_form.partner_id = self.partner_id
389 with po_form.order_line.new() as po_line:
390 po_line.product_id = self.product1
391 po_line.product_qty = 5
392 po_line.price_unit = 50.0
393 po = po_form.save()
394 po.button_confirm()
395
396 receipt = po.picking_ids[0]
397 receipt.move_ids.picked = True
398 receipt.button_validate()
399
400 delivery = self.env['stock.picking'].create({
401 'location_id': stock_location.id,
402 'location_dest_id': customer_location.id,
403 'picking_type_id': warehouse.out_type_id.id,
404 'move_ids': [(0, 0, {
405 'product_id': self.product1.id,
406 'product_uom_qty': 5,
407 'location_id': stock_location.id,
408 'location_dest_id': customer_location.id,
409 })],
410 'state': 'draft',
411 })
412 delivery.action_confirm()
413 delivery.move_ids.picked = True
414 delivery.button_validate()
415
416 bill01_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
417 bill01_form.invoice_date = bill01_form.date
418 bill01_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-po.id)
419 bill01 = bill01_form.save()
420 bill01.invoice_line_ids.quantity = 1
421 bill01.invoice_line_ids.price_unit = 60
422 bill01.action_post()
423
424 bill02_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice'))
425 bill02_form.invoice_date = bill02_form.date
426 bill02_form.purchase_vendor_bill_id = self.env['purchase.bill.union'].browse(-po.id)
427 bill02 = bill02_form.save()
428 bill02.invoice_line_ids.quantity = 4
429 bill02.invoice_line_ids.price_unit = 60
430 bill02.action_post()
431
432 input_amls = (bill01 + bill02).line_ids.filtered(lambda aml: aml.account_id == self.stock_input_account)
433 full_reconcile = input_amls[0].full_reconcile_id
434 self.assertTrue(full_reconcile)
435 self.assertTrue(all(aml.full_reconcile_id == full_reconcile for aml in input_amls))
436
437
438 def test_pdiff_and_credit_notes(self):
439 """
440 Auto FIFO
441 PO 12 @ 10
442 Receive with backorders: 4, 3 and then 5
443 Will generate 3 SVL
444 Bill:
445 BILL01: 3 @ 12
446 BILL02: 2 @ 11
447 BILL03: 1 @ 15
448 BILL04: 4 @ 9
449 BILL05: 2 @ 10
450 -: Refund 1 from BILL01
451 -: Refund all from BILL02
452 -: Refund 2 from BILL04
453 -: Refund 1 from BILL05
454 BILL06: 6 @ 18
455 """
456 self.product1.categ_id.property_cost_method = 'fifo'
457 self.product1.categ_id.property_valuation = 'real_time'
458
459 po_form = Form(self.env['purchase.order'])
460 po_form.partner_id = self.partner_id
461 with po_form.order_line.new() as po_line:
462 po_line.product_id = self.product1
463 po_line.product_qty = 12
464 po_line.price_unit = 10.0
465 po = po_form.save()
466 po.button_confirm()
467
468 receipt01 = po.picking_ids
469 receipt01.move_ids.move_line_ids.quantity = 4
470 receipt01.move_ids.picked = True
471 action = receipt01.button_validate()
472 backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(action['context'])).save()
473 backorder_wizard.process()
474
475 receipt02 = receipt01.backorder_ids
476 receipt02.move_ids.move_line_ids.quantity = 3
477 receipt02.move_ids.picked = True
478 action = receipt02.button_validate()
479 backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(action['context'])).save()
480 backorder_wizard.process()
481
482 receipt03 = receipt02.backorder_ids
483 receipt03.move_ids.move_line_ids.quantity = 5
484 receipt03.move_ids.picked = True
485 receipt03.button_validate()
486
487 expected_svl_values = [40, 30, 50]
488 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_values)
489 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
490
491 # pylint: disable=bad-whitespace
492 for qty, price, expected_svl_values, expected_svl_remaining_values in [
493 (3.0, 12.0, [40.0, 30.0, 50.0, 6.0], [46.0, 30.0, 50.0, 0.0]),
494 (2.0, 11.0, [40.0, 30.0, 50.0, 6.0, 1.0, 1.0], [47.0, 31.0, 50.0, 0.0, 0.0, 0.0]),
495 (1.0, 15.0, [40.0, 30.0, 50.0, 6.0, 1.0, 1.0, 5.0], [47.0, 36.0, 50.0, 0.0, 0.0, 0.0, 0.0]),
496 (4.0, 9.0, [40.0, 30.0, 50.0, 6.0, 1.0, 1.0, 5.0, -1.0, -3.0], [47.0, 35.0, 47.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
497 (2.0, 10.0, [40.0, 30.0, 50.0, 6.0, 1.0, 1.0, 5.0, -1.0, -3.0], [47.0, 35.0, 47.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
498 ]:
499 self._bill(po, qty, price)
500 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values, 'Err while invoicing %s @ %s' % (qty, price))
501 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values, 'Err while invoicing %s @ %s' % (qty, price))
502
503 bill01, bill02, _bill03, bill04, bill05 = po.invoice_ids.sorted('id')
504
505 self._refund(bill01, 1.0)
506 expected_svl_values += [-2.0]
507 expected_svl_remaining_values += [0.0]
508 # should impact the first layer
509 expected_svl_remaining_values[0] -= 2.0
510 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
511 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
512
513 self._refund(bill02)
514 expected_svl_values += [-1.0, -1.0]
515 expected_svl_remaining_values += [0.0, 0.0]
516 # should impact the two first layers
517 expected_svl_remaining_values[0] -= 1.0
518 expected_svl_remaining_values[1] -= 1.0
519 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
520 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
521
522 self._refund(bill04, 2.0)
523 expected_svl_values += [1.0, 1.0]
524 expected_svl_remaining_values += [0.0, 0.0]
525 # should impact the two last layers
526 expected_svl_remaining_values[1] += 1.0
527 expected_svl_remaining_values[2] += 1.0
528 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
529 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
530
531 self._refund(bill05, 1.0)
532 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
533 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
534
535 self._bill(po, price=18.0)
536 expected_svl_values += [16.0, 16.0, 16.0]
537 expected_svl_remaining_values += [0.0, 0.0, 0.0]
538 # should impact all layers
539 expected_svl_remaining_values[0] += 16.0
540 expected_svl_remaining_values[1] += 16.0
541 expected_svl_remaining_values[2] += 16.0
542 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
543 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
544
545 accounts = self.product1.product_tmpl_id._get_product_accounts()
546 stock_in_amls = self.env['account.move.line'].search([('account_id', '=', accounts['stock_input'].id)], order='id')
547 self.assertRecordValues(stock_in_amls, [
548 # Receipts
549 {'debit': 0.0, 'credit': 40.0},
550 {'debit': 0.0, 'credit': 30.0},
551 {'debit': 0.0, 'credit': 50.0},
552 # Bill01 3 @ 12
553 {'debit': 36.0, 'credit': 0.0},
554 {'debit': 0.0, 'credit': 6.0},
555 # Bill02 2 @ 11
556 {'debit': 22.0, 'credit': 0.0},
557 {'debit': 0.0, 'credit': 1.0},
558 {'debit': 0.0, 'credit': 1.0},
559 # Bill03 1 @ 15
560 {'debit': 15.0, 'credit': 0.0},
561 {'debit': 0.0, 'credit': 5.0},
562 # Bill04 4 @ 9
563 {'debit': 36.0, 'credit': 0.0},
564 {'debit': 1.0, 'credit': 0.0},
565 {'debit': 3.0, 'credit': 0.0},
566 # Bill05 2 @ 10
567 {'debit': 20.0, 'credit': 0.0},
568 # Refund 1 from BILL01
569 {'debit': 0.0, 'credit': 12.0},
570 {'debit': 2.0, 'credit': 0.0},
571 # Refund all from BILL02
572 {'debit': 0.0, 'credit': 22.0},
573 {'debit': 1.0, 'credit': 0.0},
574 {'debit': 1.0, 'credit': 0.0},
575 # Refund 2 from BILL04
576 {'debit': 0.0, 'credit': 18.0},
577 {'debit': 0.0, 'credit': 1.0},
578 {'debit': 0.0, 'credit': 1.0},
579 # Refund 1 from BILL05
580 {'debit': 0.0, 'credit': 10.0},
581 # BILL06: 6 @ 18
582 {'debit': 108.0, 'credit': 0.0},
583 {'debit': 0.0, 'credit': 16.0},
584 {'debit': 0.0, 'credit': 16.0},
585 {'debit': 0.0, 'credit': 16.0},
586 ])
587 self.assertTrue(all(aml.full_reconcile_id for aml in stock_in_amls))
588
589 def test_pdiff_with_credit_notes_and_delivered_qties(self):
590 """
591 Auto FIFO
592 IN 10 @ 10
593 Bill 10 @ 12
594 OUT 3
595 Full Refund
596 Bill 10 @ 9
597 OUT 1
598 Full Refund
599 Bill 10 @ 10
600 """
601 self.product1.categ_id.property_cost_method = 'fifo'
602 self.product1.categ_id.property_valuation = 'real_time'
603 expected_svl_values = []
604 expected_svl_remaining_values = []
605
606 warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
607 stock_location = warehouse.lot_stock_id
608 customer_location = self.env.ref('stock.stock_location_customers')
609
610 po_form = Form(self.env['purchase.order'])
611 po_form.partner_id = self.partner_id
612 with po_form.order_line.new() as po_line:
613 po_line.product_id = self.product1
614 po_line.product_qty = 10
615 po_line.price_unit = 10.0
616 po = po_form.save()
617 po.button_confirm()
618
619 receipt = po.picking_ids
620 receipt.move_ids.move_line_ids.quantity = 10
621 receipt.move_ids.picked = True
622 receipt.button_validate()
623 expected_svl_values += [100.0]
624 expected_svl_remaining_values += [100.0]
625 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
626 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
627
628 bill01 = self._bill(po, price=12)
629 expected_svl_values += [20.0]
630 expected_svl_remaining_values += [0.0]
631 expected_svl_remaining_values[0] += 20.0 # should impact the layer of the receipt
632 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
633 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
634
635 delivery = self.env['stock.picking'].create({
636 'location_id': stock_location.id,
637 'location_dest_id': customer_location.id,
638 'picking_type_id': warehouse.out_type_id.id,
639 'move_ids': [(0, 0, {
640 'product_id': self.product1.id,
641 'product_uom_qty': 3,
642 'product_uom': self.product1.uom_id.id,
643 'location_id': stock_location.id,
644 'location_dest_id': customer_location.id,
645 })],
646 })
647 delivery.action_confirm()
648 delivery.move_ids.quantity = 3.0
649 delivery.move_ids.picked = True
650 delivery.button_validate()
651 expected_svl_values += [-36.0]
652 expected_svl_remaining_values += [0.0]
653 expected_svl_remaining_values[0] -= 36.0 # should impact the layer of the receipt
654 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
655 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
656
657 self._refund(bill01)
658 expected_svl_values += [-14.0]
659 expected_svl_remaining_values += [0.0]
660 expected_svl_remaining_values[0] -= 14.0 # should impact the layer of the receipt
661 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
662 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
663
664 bill02 = self._bill(po, price=9)
665 expected_svl_values += [-7.0]
666 expected_svl_remaining_values += [0.0]
667 expected_svl_remaining_values[0] -= 7.0 # should impact the layer of the receipt
668 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
669 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
670
671 delivery = self.env['stock.picking'].create({
672 'location_id': stock_location.id,
673 'location_dest_id': customer_location.id,
674 'picking_type_id': warehouse.out_type_id.id,
675 'move_ids': [(0, 0, {
676 'product_id': self.product1.id,
677 'product_uom_qty': 1,
678 'product_uom': self.product1.uom_id.id,
679 'location_id': stock_location.id,
680 'location_dest_id': customer_location.id,
681 })],
682 })
683 delivery.action_confirm()
684 delivery.move_ids.quantity = 1.0
685 delivery.move_ids.picked = True
686 delivery.button_validate()
687 expected_svl_values += [-9.0]
688 expected_svl_remaining_values += [0.0]
689 expected_svl_remaining_values[0] -= 9.0 # should impact the layer of the receipt
690 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
691 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
692
693 ctx = {'active_ids': bill02.ids, 'active_model': 'account.move'}
694 credit_note_wizard = self.env['account.move.reversal'].with_context(ctx).create({
695 'journal_id': bill02.journal_id.id,
696 })
697 res_id = credit_note_wizard.modify_moves()['res_id']
698 bill03 = self.env['account.move'].browse(res_id)
699 bill03.invoice_date = fields.Date.today()
700 bill03.invoice_line_ids.price_unit = 10.0
701 bill03.action_post()
702 # Impact of the refund (bill03 should not impact the SVLs since the unit price is the one of the POL)
703 expected_svl_values += [6.0]
704 expected_svl_remaining_values += [0.0]
705 expected_svl_remaining_values[0] += 6.0 # should impact the layer of the receipt
706 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
707 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
708
709 accounts = self.product1.product_tmpl_id._get_product_accounts()
710 stock_in_amls = self.env['account.move.line'].search([('account_id', '=', accounts['stock_input'].id)], order='id')
711 self.assertRecordValues(stock_in_amls, [
712 # IN 10 @ 10
713 {'debit': 0.0, 'credit': 100.0},
714 # Bill 10 @ 12
715 {'debit': 120.0, 'credit': 0.0},
716 {'debit': 0.0, 'credit': 20.0},
717 # (OUT 3)
718 # Refund: here, we skip the 3 products delivered in the meantime,
719 # i.e. we only compensate the on-hand quantity (hence the $14
720 # instead of $20)
721 {'debit': 0.0, 'credit': 120.0},
722 {'debit': 14.0, 'credit': 0.0},
723 # Bill 10 @ 9
724 {'debit': 90.0, 'credit': 0.0},
725 {'debit': 3.0, 'credit': 0.0},
726 {'debit': 7.0, 'credit': 0.0},
727 # (OUT 1)
728 # Refund: again, we skip the product delivered in the meantime.
729 # We have $3 which is the reversing entry of the inital bill
730 # and 6$ from the stock valuation correction
731 {'debit': 0.0, 'credit': 90.0},
732 {'debit': 0.0, 'credit': 3.0},
733 {'debit': 0.0, 'credit': 6.0},
734 # Bill 10 @ 10
735 {'debit': 100.0, 'credit': 0},
736 ])
737
738 self.assertEqual(sum(stock_in_amls.mapped('debit')) - sum(stock_in_amls.mapped('credit')), -5,
739 "There should be a difference because of the skipped products while posting the refunds (see "
740 "comments in above `assertRecordValues`). The value is the sum of the price differences of each "
741 "delivery: 3 * $2 + 1 * $-1). The user will have to manually add some account entries to "
742 "balance the accounts")
743
744 def test_pdiff_with_returns_and_credit_notes(self):
745 """
746 Auto FIFO
747 IN 10 @ 10
748 Return 3
749 IN (Return) 3
750 Bill 10 @ 12
751 This step will impact 7 products of the first layer and 3 products
752 of the last one (i.e. the second IN)
753 Return 1
754 Refund 1 (from PO)
755 Return 5
756 Refund 5 (from initial bill)
757 """
758 self.product1.categ_id.property_cost_method = 'fifo'
759 self.product1.categ_id.property_valuation = 'real_time'
760 accounts = self.product1.product_tmpl_id._get_product_accounts()
761 expected_svl_values = []
762 expected_svl_remaining_values = []
763
764 po_form = Form(self.env['purchase.order'])
765 po_form.partner_id = self.partner_id
766 with po_form.order_line.new() as po_line:
767 po_line.product_id = self.product1
768 po_line.product_qty = 10
769 po_line.price_unit = 10.0
770 po = po_form.save()
771 po.button_confirm()
772
773 receipt = po.picking_ids
774 receipt.move_ids.move_line_ids.quantity = 10
775 receipt.move_ids.picked = True
776 receipt.button_validate()
777 expected_svl_values += [100.0]
778 expected_svl_remaining_values += [100.0]
779 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
780 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
781
782 return01 = self._return(receipt, qty=3)
783 expected_svl_values += [-30.0]
784 expected_svl_remaining_values += [0.0]
785 expected_svl_remaining_values[0] -= 30
786 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
787 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
788
789 self._return(return01)
790 expected_svl_values += [30.0]
791 expected_svl_remaining_values += [30.0]
792 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
793 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
794
795 bill = self._bill(po, price=12)
796 # two new layers because we have 7 remaining products in the first in-layer and 3 in the second one
797 expected_svl_values += [14.0, 6.0]
798 expected_svl_remaining_values += [0.0, 0.0]
799 expected_svl_remaining_values[0] += 14.0
800 # `expected_svl_remaining_values[1]` is the return, it does not change
801 expected_svl_remaining_values[2] += 6.0
802 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
803 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
804 stock_in_amls = self.env['account.move.line'].search([('account_id', '=', accounts['stock_input'].id)])
805 self.assertTrue(stock_in_amls)
806 self.assertTrue(all(aml.full_reconcile_id for aml in stock_in_amls))
807
808 self._return(receipt, qty=1)
809 expected_svl_values += [-12.0]
810 expected_svl_remaining_values += [0.0]
811 expected_svl_remaining_values[0] -= 12.0
812 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
813 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
814
815 refund = self._bill(po, price=12)
816 self.assertEqual(refund.move_type, 'in_refund')
817 stock_in_amls = self.env['account.move.line'].search([('account_id', '=', accounts['stock_input'].id)])
818 self.assertTrue(stock_in_amls)
819 self.assertTrue(all(aml.full_reconcile_id for aml in stock_in_amls))
820
821 self._return(receipt, qty=5)
822 expected_svl_values += [-60.0]
823 expected_svl_remaining_values += [0.0]
824 expected_svl_remaining_values[0] -= 60.0
825 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
826 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
827
828 self._refund(bill, qty=5)
829 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('value'), expected_svl_values)
830 self.assertEqual(self.product1.stock_valuation_layer_ids.mapped('remaining_value'), expected_svl_remaining_values)
831 stock_in_amls = self.env['account.move.line'].search([('account_id', '=', accounts['stock_input'].id)], order='id')
832 self.assertRecordValues(stock_in_amls, [
833 # IN 10 @ 10
834 {'debit': 0.0, 'credit': 100.0},
835 # Return 3
836 {'debit': 30.0, 'credit': 0.0},
837 # IN (Return) 3
838 {'debit': 0.0, 'credit': 30.0},
839 # Bill 10 @ 12
840 {'debit': 120, 'credit': 0.0},
841 {'debit': 0.0, 'credit': 14.0},
842 {'debit': 0.0, 'credit': 6.0},
843 # Return 1
844 {'debit': 12.0, 'credit': 0.0},
845 # Refund 1
846 {'debit': 0, 'credit': 12.0},
847 # Return 5
848 {'debit': 60.0, 'credit': 0.0},
849 # Refund 5
850 {'debit': 0.0, 'credit': 60.0},
851 ])
852 self.assertTrue(all(aml.full_reconcile_id for aml in stock_in_amls))
853
854 def _test_pdiff_and_order_between_bills_common(self):
855 self.product1.categ_id.property_cost_method = 'fifo'
856 self.product1.categ_id.property_valuation = 'real_time'
857
858 po_form = Form(self.env['purchase.order'])
859 po_form.partner_id = self.partner_id
860 with po_form.order_line.new() as po_line:
861 po_line.product_id = self.product1
862 po_line.product_qty = 2
863 po_line.price_unit = 10.0
864 po = po_form.save()
865 po.button_confirm()
866
867 receipt01 = po.picking_ids
868 receipt01.move_ids.move_line_ids.quantity = 1
869 receipt01.move_ids.picked = True
870 action = receipt01.button_validate()
871 backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(action['context'])).save()
872 backorder_wizard.process()
873
874 receipt02 = receipt01.backorder_ids
875 receipt02.move_ids.move_line_ids.quantity = 1
876 receipt02.move_ids.picked = True
877 receipt02.button_validate()
878
879 bill01 = self._bill(po, 1.0, 11)
880
881 ctx = {'active_ids': bill01.ids, 'active_model': 'account.move'}
882 credit_note_wizard = self.env['account.move.reversal'].with_context(ctx).create({
883 'journal_id': bill01.journal_id.id,
884 })
885 refund = self.env['account.move'].browse(credit_note_wizard.refund_moves()['res_id'])
886
887 action = po.action_create_invoice()
888 bill02 = self.env["account.move"].browse(action["res_id"])
889 bill02.invoice_date = fields.Date.today()
890 bill02.invoice_line_ids.quantity = 1.0
891 bill02.invoice_line_ids.price_unit = 12
892
893 return po, refund, bill02
894
895 def test_pdiff_and_aml_labels(self):
896 """
897 When posting the bill, if an AML has a pdiff, it should not change any
898 label of the bill
899 """
900 self.product1.type = 'consu'
901 self.product1.categ_id.property_cost_method = 'fifo'
902 self.product1.categ_id.property_valuation = 'real_time'
903
904 po_form = Form(self.env['purchase.order'])
905 po_form.partner_id = self.partner_id
906 with po_form.order_line.new() as po_line:
907 po_line.product_id = self.product1
908 po_line.product_qty = 1
909 po_line.price_unit = 10.0
910 with po_form.order_line.new() as po_line:
911 po_line.product_id = self.product_b
912 po_line.product_qty = 1
913 po_line.price_unit = 10.0
914 po = po_form.save()
915 po.button_confirm()
916
917 receipt01 = po.picking_ids
918 receipt01.move_ids.move_line_ids.quantity = 1
919 receipt01.button_validate()
920
921 action = po.action_create_invoice()
922 bill = self.env["account.move"].browse(action["res_id"])
923 bill.invoice_date = fields.Date.today()
924 label01, label02 = bill.invoice_line_ids.mapped('name')
925 self.assertTrue(label01)
926 self.assertTrue(label02)
927
928 bill.invoice_line_ids.price_unit = 11.0
929 bill.action_post()
930 self.assertEqual(bill.invoice_line_ids.mapped('name'), [label01, label02])
931
932 def test_pdiff_and_order_between_bills_01(self):
933 """
934 Auto fifo
935 IN 1 @ 10 -> SVL01
936 IN 1 @ 10 -> SVL02
937 BILL01 1 @ 11
938 Should impact SVL01
939 Create draft Refund
940 Create draft BILL02 1 @ 12
941 Post Refund
942 Post BILL02
943 Should impact SVL01
944 Bill03 1 @ 13
945 Should impact SVL02
946 """
947 po, refund, bill02 = self._test_pdiff_and_order_between_bills_common()
948 refund.action_post()
949 bill02.action_post()
950 self._bill(po, price=13)
951
952 svls = self.product1.stock_valuation_layer_ids
953 self.assertEqual(svls.mapped('remaining_value'), [12.0, 13.0, 0.0, 0.0, 0.0, 0.0])
954 self.assertEqual(svls.mapped('value'), [10.0, 10.0, 1.0, -1.0, 2.0, 3.0])
955
956 def test_pdiff_and_order_between_bills_02(self):
957 """
958 Auto fifo
959 IN 1 @ 10 -> SVL01
960 IN 1 @ 10 -> SVL02
961 BILL01 1 @ 11
962 Should impact SVL01
963 Create draft Refund
964 Create draft BILL02 1 @ 12
965 Post BILL02
966 Should impact SVL02
967 Post Refund
968 Bill03 1 @ 13
969 Should impact SVL01
970 """
971 po, refund, bill02 = self._test_pdiff_and_order_between_bills_common()
972 bill02.action_post()
973 refund.action_post()
974 self._bill(po, price=13)
975
976 svls = self.product1.stock_valuation_layer_ids
977 self.assertEqual(svls.mapped('remaining_value'), [13.0, 12.0, 0.0, 0.0, 0.0, 0.0])
978 self.assertEqual(svls.mapped('value'), [10.0, 10.0, 1.0, 2.0, -1.0, 3.0])
979
980 def test_pdiff_multi_curr_and_rates(self):
981 """
982 Company in USD.
983 Today: 100 EUR = 150 USD
984 One day ago: 100 EUR = 130 USD
985 Two days ago: 100 EUR = 125 USD
986 Buy and receive one auto-AVCO product at 100 EUR. Bill it with:
987 - Bill date: two days ago (125 USD)
988 - Accounting date: one day ago (130 USD)
989 The value at bill date should be used for both bill value and price
990 diff value.
991 """
992 usd_currency = self.env.ref('base.USD')
993 eur_currency = self.env.ref('base.EUR')
994
995 today = fields.Date.today()
996 one_day_ago = today - timedelta(days=1)
997 two_days_ago = today - timedelta(days=2)
998
999 self.env.company.currency_id = usd_currency.id
1000
1001 self.env['res.currency.rate'].search([]).unlink()
1002 self.env['res.currency.rate'].create([{
1003 'name': day.strftime('%Y-%m-%d'),
1004 'rate': 1 / rate,
1005 'currency_id': eur_currency.id,
1006 'company_id': self.env.company.id,
1007 } for (day, rate) in [
1008 (today, 1.5),
1009 (one_day_ago, 1.3),
1010 (two_days_ago, 1.25),
1011 ]])
1012
1013 self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
1014
1015 po = self.env['purchase.order'].create({
1016 'partner_id': self.partner_id.id,
1017 'currency_id': eur_currency.id,
1018 'order_line': [
1019 (0, 0, {
1020 'name': self.product1.name,
1021 'product_id': self.product1.id,
1022 'product_qty': 1.0,
1023 'product_uom_id': self.product1.uom_id.id,
1024 'price_unit': 100.0,
1025 'tax_ids': False,
1026 }),
1027 ],
1028 })
1029 po.button_confirm()
1030
1031 receipt = po.picking_ids
1032 receipt.move_ids.move_line_ids.quantity = 1.0
1033 receipt.button_validate()
1034
1035 layer = receipt.move_ids.stock_valuation_layer_ids
1036 self.assertEqual(layer.value, 150)
1037
1038 action = po.action_create_invoice()
1039 bill = self.env["account.move"].browse(action["res_id"])
1040 bill.invoice_date = two_days_ago
1041 bill.date = one_day_ago
1042 bill.action_post()
1043
1044 pdiff_layer = layer.stock_valuation_layer_ids
1045 self.assertEqual(pdiff_layer.value, -25)
1046 self.assertEqual(layer.remaining_value, 125)
1047
1048 in_stock_amls = self.env['account.move.line'].search([
1049 ('product_id', '=', self.product1.id),
1050 ('account_id', '=', self.stock_input_account.id),
1051 ], order='id')
1052 self.assertRecordValues(in_stock_amls, [
1053 # pylint: disable=bad-whitespace
1054 {'date': today, 'debit': 0, 'credit': 150, 'reconciled': True},
1055 {'date': one_day_ago, 'debit': 125, 'credit': 0, 'reconciled': True},
1056 {'date': one_day_ago, 'debit': 25, 'credit': 0, 'reconciled': True},
1057 ])
1058
1059 def test_pdiff_lot_valuation(self):
1060 """
1061 use a product valuated by lot.
1062 Receipt some lots in the same purchase order, validate the picking
1063 create the bill with a price different from the PO. Check every layers
1064 for the lots have their own price difference correction layer.
1065 """
1066
1067 self.cat.property_cost_method = 'average'
1068 product = self.env['product.product'].create({
1069 'name': 'product1',
1070 'is_storable': True,
1071 'tracking': 'serial',
1072 'categ_id': self.cat.id,
1073 'lot_valuated': True,
1074 })
1075
1076 po = self.env['purchase.order'].create({
1077 'partner_id': self.partner_id.id,
1078 'order_line': [
1079 (0, 0, {
1080 'name': product.name,
1081 'product_id': product.id,
1082 'product_qty': 3.0,
1083 'product_uom_id': product.uom_id.id,
1084 'price_unit': 100.0,
1085 'tax_ids': False,
1086 }),
1087 ],
1088 })
1089 po.button_confirm()
1090
1091 receipt = po.picking_ids
1092 i = 1
1093 for line in receipt.move_ids.move_line_ids:
1094 line.write({
1095 'lot_name': 'lot_' + str(i),
1096 'quantity': 1,
1097 })
1098 i += 1
1099 receipt.move_ids.picked = True
1100 receipt.button_validate()
1101 lots = receipt.move_line_ids.lot_id
1102 self.assertEqual(receipt.state, 'done')
1103
1104 for lot in lots:
1105 self.assertEqual(lot.standard_price, 100)
1106
1107 layers = receipt.move_ids.stock_valuation_layer_ids
1108 self.assertEqual(layers.mapped('value'), [100, 100, 100])
1109
1110 action = po.action_create_invoice()
1111 bill = self.env["account.move"].browse(action["res_id"])
1112 bill.line_ids.price_unit = 150
1113 bill.invoice_date = fields.Date.today()
1114 bill.action_post()
1115 for lot in lots:
1116 self.assertEqual(lot.standard_price, 150)
1117
1118 pdiff_layers = layers.stock_valuation_layer_ids
1119 self.assertRecordValues(pdiff_layers, [
1120 # pylint: disable=bad-whitespace
1121 {'quantity': 0, 'lot_id': lots[0].id, 'value': 50},
1122 {'quantity': 0, 'lot_id': lots[1].id, 'value': 50},
1123 {'quantity': 0, 'lot_id': lots[2].id, 'value': 50},
1124 ])
1125
1126 def test_purchase_with_backorders_and_return_and_price_changes(self):
1127 """
1128 When you have multiples receipts associated to a Purchase Order, with 1 bill for each receipt,
1129 then each bill has an impact on its own receipt only, hence if I modify the price on Bill01,
1130 it will not have an effect on Receipt02.
1131 However, if we create a return for a portion of a receipt,
1132 the invoiced_qty will be higher than the received_qty. This could be iterpreted has the bill
1133 being done before the receipt, which is not the case.
1134 In this test, we ensure that if the Control Policy is 'On received quantities' (procure_method = 'receive'),
1135 we keep using the purchase price for the svl unit_cost even when invoiced_qty > received_qty.
1136 """
1137 self.product1.categ_id.property_cost_method = 'average'
1138 self.product1.categ_id.property_valuation = 'real_time'
1139 self.product1.purchase_method = 'receive' # ControlPolicy
1140
1141 po_form = Form(self.env['purchase.order'])
1142 po_form.partner_id = self.partner_id
1143 with po_form.order_line.new() as po_line:
1144 po_line.product_id = self.product1
1145 po_line.product_qty = 100
1146 po_line.price_unit = 10.0
1147 po = po_form.save()
1148 po.button_confirm()
1149
1150 def _validate_backorder(po, qty):
1151 picking = po.picking_ids.filtered(lambda p: p.state not in ['done', 'draft', 'cancel']).ensure_one()
1152 picking.move_ids.move_line_ids.quantity = qty
1153 picking.button_validate()
1154 # Validate picking with backorder
1155 res_dict = picking.button_validate()
1156 wizard = self.env[(res_dict.get('res_model'))].browse(res_dict.get('res_id')).with_context(res_dict['context'])
1157 wizard.process()
1158 return picking
1159
1160 receipt01 = _validate_backorder(po, 30)
1161 self.assertEqual(receipt01.move_ids.stock_valuation_layer_ids.ensure_one().value, 300.0)
1162 bill01 = self._bill(po, price=12)
1163 self.assertEqual(bill01.invoice_line_ids.stock_valuation_layer_ids.ensure_one().value, 60.0)
1164
1165 receipt02 = _validate_backorder(po, 30)
1166 # Even though Bill01 updated the price for Receipt01, the layers of Receipt02 are not impacted.
1167 self.assertEqual(receipt02.move_ids.stock_valuation_layer_ids.ensure_one().value, 300.0)
1168 bill02 = self._bill(po, price=13)
1169 self.assertEqual(bill02.invoice_line_ids.stock_valuation_layer_ids.ensure_one().value, 90.0)
1170
1171 # With the return, the invoiced qty > received qty,
1172 # this must NOT be interpreted as the invoice done before the picking (purchase_method = 'purchase')
1173 self._return(receipt02, qty=10)
1174
1175 receipt03 = _validate_backorder(po, 30)
1176 # Like Receipt02 layers, Receipt03 layers should not be impacted by the previous price changes.
1177 self.assertEqual(receipt03.move_ids.stock_valuation_layer_ids.ensure_one().value, 300.0)
1178
1179 def test_invoice_on_ordered_qty_with_backorder_and_different_currency_automated(self):
1180 """Create a PO with currency different from the company currency. Set the
1181 product to be invoiced on ordered quantities. Receive partially the products
1182 and create a backorder. Create an invoice for the ordered quantity. Then
1183 receive the backorder. Check if the valuation layer is correctly created.
1184 """
1185 usd_currency = self.env.ref('base.USD')
1186 self.env.company.currency_id = usd_currency.id
1187 self.product1.categ_id.property_cost_method = 'fifo'
1188 self.product1.categ_id.property_valuation = 'real_time'
1189 self.product1.purchase_method = 'purchase'
1190
1191 price_unit_EUR = 100
1192 price_unit_USD = self.env.ref('base.EUR')._convert(price_unit_EUR, usd_currency, self.env.company, fields.Date.today(), round=False)
1193 po = self.env['purchase.order'].create({
1194 'partner_id': self.partner_id.id,
1195 'currency_id': self.env.ref('base.EUR').id,
1196 'order_line': [
1197 (0, 0, {
1198 'name': self.product1.name,
1199 'product_id': self.product1.id,
1200 'product_qty': 12.0,
1201 'product_uom_id': self.product1.uom_id.id,
1202 'price_unit': 100.0,
1203 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
1204 }),
1205 ],
1206 })
1207 po.button_confirm()
1208 picking = po.picking_ids[0]
1209 move = picking.move_ids[0]
1210 move.quantity = 10
1211 move.picked = True
1212 res_dict = picking.button_validate()
1213 self.assertEqual(res_dict['res_model'], 'stock.backorder.confirmation')
1214 wizard = self.env[(res_dict.get('res_model'))].browse(res_dict.get('res_id')).with_context(res_dict['context'])
1215 wizard.process()
1216 self.assertAlmostEqual(move.stock_valuation_layer_ids.unit_cost, price_unit_USD)
1217
1218 po.action_create_invoice()
1219
1220 picking2 = po.picking_ids.filtered(lambda p: p.backorder_id)
1221 move2 = picking2.move_ids[0]
1222 move2.quantity = 2
1223 move2.picked = True
1224 picking2.button_validate()
1225 self.assertAlmostEqual(move2.stock_valuation_layer_ids.unit_cost, price_unit_USD)
1226
1227 def test_invoice_on_ordered_qty_with_backorder_and_different_currency_manual(self):
1228 """Same test as test_invoice_on_ordered_qty_with_backorder_and_different_currency_automated with manual_periodic valuation
1229 Ensure that the absence of account_move_id on the layers does not generate an Exception
1230 """
1231 usd_currency = self.env.ref('base.USD')
1232 self.env.company.currency_id = usd_currency.id
1233 self.product1.categ_id.property_cost_method = 'fifo'
1234 self.product1.categ_id.property_valuation = 'periodic'
1235 self.product1.purchase_method = 'purchase'
1236
1237 price_unit_EUR = 100
1238 price_unit_USD = self.env.ref('base.EUR')._convert(price_unit_EUR, usd_currency, self.env.company, fields.Date.today(), round=False)
1239 po = self.env['purchase.order'].create({
1240 'partner_id': self.partner_id.id,
1241 'currency_id': self.env.ref('base.EUR').id,
1242 'order_line': [
1243 (0, 0, {
1244 'name': self.product1.name,
1245 'product_id': self.product1.id,
1246 'product_qty': 12.0,
1247 'product_uom_id': self.product1.uom_id.id,
1248 'price_unit': 100.0,
1249 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
1250 }),
1251 ],
1252 })
1253 po.button_confirm()
1254 picking = po.picking_ids[0]
1255 move = picking.move_ids[0]
1256 move.quantity = 10
1257 move.picked = True
1258 res_dict = picking.button_validate()
1259 self.assertEqual(res_dict['res_model'], 'stock.backorder.confirmation')
1260 wizard = self.env[(res_dict.get('res_model'))].browse(res_dict.get('res_id')).with_context(res_dict['context'])
1261 wizard.process()
1262 self.assertAlmostEqual(move.stock_valuation_layer_ids.unit_cost, price_unit_USD)
1263
1264 po.action_create_invoice()
1265
1266 picking2 = po.picking_ids.filtered(lambda p: p.backorder_id)
1267 move2 = picking2.move_ids[0]
1268 move2.quantity = 2
1269 move2.picked = True
1270 picking2.button_validate()
1271 self.assertAlmostEqual(move2.stock_valuation_layer_ids.unit_cost, price_unit_USD)
1272
1273 def test_pdiff_date(self):
1274 """
1275 Test pdiff operations complete without errors.
1276 The created bill should have the date of today.
1277 """
1278 self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
1279
1280 po = self.env['purchase.order'].create({
1281 'partner_id': self.partner_id.id,
1282 'order_line': [
1283 (0, 0, {
1284 'name': self.product1.name,
1285 'product_id': self.product1.id,
1286 'product_qty': 1.0,
1287 'product_uom_id': self.product1.uom_id.id,
1288 'price_unit': 100.0,
1289 'tax_ids': False,
1290 }),
1291 ],
1292 })
1293 po.button_confirm()
1294
1295 receipt = po.picking_ids
1296 receipt.move_ids.move_line_ids.quantity = 1.0
1297 receipt.button_validate()
1298
1299 action = po.action_create_invoice()
1300 bill = self.env["account.move"].browse(action["res_id"])
1301 bill.action_post()
1302 self.assertEqual(bill.invoice_date, fields.Date.context_today(bill))
1303
1304 def test_bill_date_exchange_rate_for_price_diff_amls(self):
1305 """Ensure sure that the amls for price difference uses the bill date exchange rate. They originally used today's rate
1306 which meant that their value depended on the day the bill was posted (as it is when the price diff amls are created).
1307 """
1308 company = self.env.user.company_id
1309 company.anglo_saxon_accounting = True
1310 company.currency_id = self.usd_currency
1311
1312 self.product1.categ_id.property_cost_method = 'fifo'
1313 self.product1.categ_id.property_valuation = 'real_time'
1314
1315 po_date = '2023-10-01'
1316 bill_date = '2023-11-01'
1317 today = fields.Date.today()
1318
1319 po_rate = 2.0
1320 bill_rate = 3.0
1321 today_rate = 4.0
1322
1323 self.env['res.currency.rate'].search([]).unlink()
1324 self.env['res.currency.rate'].create([
1325 {
1326 'name': po_date,
1327 'rate': po_rate,
1328 'currency_id': self.eur_currency.id,
1329 'company_id': company.id,
1330 },
1331 {
1332 'name': bill_date,
1333 'rate': bill_rate,
1334 'currency_id': self.eur_currency.id,
1335 'company_id': company.id,
1336 },
1337 {
1338 'name': today,
1339 'rate': today_rate,
1340 'currency_id': self.eur_currency.id,
1341 'company_id': company.id,
1342 },
1343 ])
1344
1345 with freeze_time(po_date):
1346 purchase_price = 90
1347 po = self.env['purchase.order'].create({
1348 'partner_id': self.partner_id.id,
1349 'currency_id': self.eur_currency.id,
1350 'order_line': [
1351 Command.create({
1352 'product_id': self.product1.id,
1353 'product_qty': 1.0,
1354 'price_unit': purchase_price,
1355 'tax_ids': False,
1356 }),
1357 ]
1358 })
1359 po.button_confirm()
1360
1361 receipt = po.picking_ids
1362 receipt.move_line_ids.quantity = 1
1363 receipt.button_validate()
1364
1365 warehouse = self.env['stock.warehouse'].search([('company_id', '=', company.id)], limit=1)
1366 stock_location = warehouse.lot_stock_id
1367 customer_location = self.env.ref('stock.stock_location_customers')
1368 delivery = self.env['stock.picking'].create({
1369 'location_id': stock_location.id,
1370 'location_dest_id': customer_location.id,
1371 'picking_type_id': warehouse.out_type_id.id,
1372 'move_ids': [
1373 Command.create({
1374 'product_id': self.product1.id,
1375 'product_uom_qty': 1.0,
1376 'location_id': stock_location.id,
1377 'location_dest_id': customer_location.id,
1378 })
1379 ]
1380 })
1381 delivery.action_confirm()
1382 delivery.move_ids.quantity = 1.0
1383 delivery.button_validate()
1384
1385 po.action_create_invoice()
1386 bill = po.invoice_ids
1387 bill.invoice_date = bill_date
1388 bill.action_post()
1389
1390 product_accounts = self.product1.product_tmpl_id.get_product_accounts()
1391 payable_id = self.company_data['default_account_payable'].id
1392 stock_in_id = product_accounts['stock_input'].id
1393 expense_id = product_accounts['expense'].id
1394 self.assertRecordValues(bill.line_ids, [
1395 # pylint: disable=bad-whitespace
1396 {'debit': 30, 'credit': 0, 'account_id': stock_in_id, 'reconciled': True, 'amount_currency': 90},
1397 {'debit': 0, 'credit': 30, 'account_id': payable_id, 'reconciled': False, 'amount_currency': -90},
1398 {'debit': 0, 'credit': 15, 'account_id': expense_id, 'reconciled': False, 'amount_currency': 0},
1399 {'debit': 15, 'credit': 0, 'account_id': stock_in_id, 'reconciled': True, 'amount_currency': 0},
1400 ])
1401
1402 stock_amls = self.env['account.move.line'].search([('account_id', '=', stock_in_id)])
1403 self.assertRecordValues(stock_amls, [
1404 # pylint: disable=bad-whitespace
1405 {'debit': 30, 'credit': 0, 'account_id': stock_in_id, 'reconciled': True, 'amount_currency': 90},
1406 {'debit': 15, 'credit': 0, 'account_id': stock_in_id, 'reconciled': True, 'amount_currency': 0},
1407 {'debit': 0, 'credit': 45, 'account_id': stock_in_id, 'reconciled': True, 'amount_currency': -90},
1408 ])
1409
1410 def test_invoice_first_receipt_later_with_multicurrency_different_dates(self):
1411 """Ensure sure that use currency rate at bill date rather than the current date when invoice before receipt"""
1412 company = self.env.user.company_id
1413 company.anglo_saxon_accounting = True
1414 company.currency_id = self.usd_currency
1415
1416 self.product1.is_storable = True
1417 self.product1.purchase_method = 'purchase'
1418
1419 self.product1.with_company(company).categ_id.property_cost_method = 'fifo'
1420 self.product1.with_company(company).categ_id.property_valuation = 'real_time'
1421
1422 po_date = '2023-10-01'
1423 bill_date = '2023-10-15'
1424 receipt_date = '2023-10-31'
1425
1426 po_rate = 0.8
1427 bill_rate = 2.0
1428 receipt_rate = 2.2
1429
1430 self.env['res.currency.rate'].search([]).unlink()
1431 self.env['res.currency.rate'].create([
1432 {
1433 'name': po_date,
1434 'rate': po_rate,
1435 'currency_id': self.eur_currency.id,
1436 'company_id': company.id,
1437 },
1438 {
1439 'name': bill_date,
1440 'rate': bill_rate,
1441 'currency_id': self.eur_currency.id,
1442 'company_id': company.id,
1443 },
1444 {
1445 'name': receipt_date,
1446 'rate': receipt_rate,
1447 'currency_id': self.eur_currency.id,
1448 'company_id': company.id,
1449 },
1450 ])
1451
1452 with freeze_time(po_date):
1453 purchase_price = 100
1454 po = self.env['purchase.order'].create({
1455 'partner_id': self.partner_id.id,
1456 'currency_id': self.eur_currency.id,
1457 'order_line': [
1458 Command.create({
1459 'product_id': self.product1.id,
1460 'product_qty': 1.0,
1461 'price_unit': purchase_price,
1462 'tax_ids': False,
1463 }),
1464 ]
1465 })
1466 po.button_confirm()
1467
1468 with freeze_time(bill_date):
1469 po.action_create_invoice()
1470 bill = po.invoice_ids
1471 bill.invoice_date = bill_date
1472 bill.action_post()
1473
1474 with freeze_time(receipt_date):
1475 receipt = po.picking_ids
1476 receipt.move_ids.write({'quantity': 1.0})
1477 receipt.button_validate()
1478
1479 payable_id = self.company_data['default_account_payable'].id
1480 stock_in_id = self.stock_input_account.id
1481 stock_valuation = self.stock_valuation_account.id
1482
1483 # 1 Units invoiced at rate 2 and unit price 100 = 50
1484 amls = self.env["account.move.line"].search([('parent_state', '=', 'posted')], order="id asc")
1485 self.assertRecordValues(amls, [
1486 # pylint: disable=bad-whitespace
1487 # Bill Lines
1488 {'debit': 50.0, 'credit': 0, 'reconciled': True, 'amount_currency': 100.0, 'account_id': stock_in_id},
1489 {'debit': 0, 'credit': 50.0, 'reconciled': False, 'amount_currency': -100.0, 'account_id': payable_id},
1490 # Receipt Lines
1491 {'debit': 0, 'credit': 50.0, 'reconciled': True, 'amount_currency': -100.0, 'account_id': stock_in_id},
1492 {'debit': 50.0, 'credit': 0, 'reconciled': False, 'amount_currency': 100.0, 'account_id': stock_valuation},
1493 ])
1494
1495 def test_analytic_distribution_propagation_with_exchange_difference(self):
1496 # Create 2 rates in order to generate an exchange difference later.
1497 eur = self.env.ref('base.EUR')
1498 eur.write({
1499 'rate_ids': [
1500 Command.clear(),
1501 Command.create({
1502 'name': fields.Date.from_string('2023-01-01'),
1503 'company_rate': 2.0,
1504 }),
1505 Command.create({
1506 'name': fields.Date.from_string('2023-12-01'),
1507 'company_rate': 3.0,
1508 }),
1509 ],
1510 'active': True,
1511 })
1512
1513 # Create a mandatory analytic account.
1514 analytic_plan = self.env['account.analytic.plan'].create({
1515 'name': 'Analytic Plan',
1516 'default_applicability': 'mandatory',
1517 })
1518 analytic_account = self.env['account.analytic.account'].create({
1519 'name': 'Analytic Account',
1520 'plan_id': analytic_plan.id},
1521 )
1522
1523 # Create a storable product with FIFO costing method and automated inventory valuation.
1524 analytic_product_category = self.env['product.category'].create({
1525 'name': 'Analytic Product Category',
1526 'property_cost_method': 'fifo',
1527 'property_valuation': 'real_time',
1528 })
1529 analytic_product = self.env['product.product'].create({
1530 'name': 'Analytic Product',
1531 'is_storable': True,
1532 'categ_id': analytic_product_category.id,
1533 'lst_price': 100.0,
1534 'standard_price': 25.0,
1535 })
1536
1537 # Create and confirm a Purchase Order using aforementioned product and currency.
1538 purchase_order = self.env['purchase.order'].create({
1539 'date_order': fields.Date.from_string('2023-12-04'),
1540 'currency_id': eur.id,
1541 'partner_id': self.partner_a.id,
1542 'order_line': [
1543 Command.create({
1544 'product_id': analytic_product.id,
1545 'product_qty': 10.0,
1546 'analytic_distribution': {analytic_account.id: 100},
1547 }),
1548 ],
1549 })
1550 purchase_order.button_confirm()
1551
1552 # Make sure a stock move has been created to replenish the product.
1553 self.assertEqual(len(purchase_order.picking_ids.move_ids), 1)
1554
1555 stock_move = purchase_order.picking_ids.move_ids
1556 stock_move.quantity = stock_move.product_uom_qty
1557
1558 purchase_order.picking_ids.button_validate()
1559 purchase_order.action_create_invoice()
1560
1561 # Make sure a first Journal Entry has been created (to account for the stock move).
1562 self.assertEqual(len(stock_move.account_move_ids), 1)
1563 stock_account_move = stock_move.account_move_ids
1564
1565 # Make sure the Vendor Bill has been created,
1566 # and confirm it at an earlier date (to generate the exchange difference).
1567 self.assertEqual(len(purchase_order.invoice_ids), 1)
1568
1569 vendor_bill = purchase_order.invoice_ids
1570 vendor_bill.invoice_date = fields.Date.from_string('2023-11-01')
1571 vendor_bill.action_post()
1572
1573 # Make sure a second Journal Entry has been created (to account for the exchange difference).
1574 self.assertEqual(len(stock_move.account_move_ids), 2)
1575 exchange_account_move = stock_move.account_move_ids - stock_account_move
1576
1577 # Make sure both exchange Journal Items have the correct analytic distribution.
1578 self.assertEqual(len(exchange_account_move.line_ids), 2)
1579 for line in exchange_account_move.line_ids:
1580 self.assertTrue(line.analytic_distribution)
1581 self.assertEqual(line.analytic_distribution[str(analytic_account.id)], 100)
1582
1583 def test_curr_rates_and_out_qty(self):
1584 """
1585 Company in USD
1586 Yesterday: 1000 EUR = 4335.1 USD
1587 Today: 1000 EUR = 4348.0 USD
1588
1589 Yesterday: Buy and receive one auto-AVCO product at 1000 EUR
1590 Today:
1591 - Deliver the product
1592 - Bill the PO
1593
1594 When posting the bill, we should generate an exchange diff compensation
1595 """
1596 usd_currency = self.env.ref('base.USD')
1597 eur_currency = self.env.ref('base.EUR')
1598
1599 warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
1600 customer_location = self.env.ref('stock.stock_location_customers')
1601 stock_location = warehouse.lot_stock_id
1602
1603 today = fields.Date.today()
1604 yesterday = today - timedelta(days=1)
1605
1606 self.env.company.currency_id = usd_currency.id
1607
1608 self.env['res.currency.rate'].search([]).unlink()
1609 self.env['res.currency.rate'].create([{
1610 'name': day.strftime('%Y-%m-%d'),
1611 'rate': 1 / rate,
1612 'currency_id': eur_currency.id,
1613 'company_id': self.env.company.id,
1614 } for (day, rate) in [
1615 (yesterday, 4.3351),
1616 (today, 4.3480),
1617 ]])
1618
1619 self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
1620
1621 with freeze_time(yesterday):
1622 po = self.env['purchase.order'].create({
1623 'partner_id': self.partner_id.id,
1624 'currency_id': eur_currency.id,
1625 'order_line': [
1626 (0, 0, {
1627 'name': self.product1.name,
1628 'product_id': self.product1.id,
1629 'product_qty': 1.0,
1630 'product_uom_id': self.product1.uom_id.id,
1631 'price_unit': 1000.0,
1632 'tax_ids': False,
1633 }),
1634 ],
1635 })
1636 po.button_confirm()
1637
1638 receipt = po.picking_ids
1639 receipt.move_ids.move_line_ids.quantity = 1.0
1640 receipt.button_validate()
1641
1642 delivery = self.env['stock.picking'].create({
1643 'location_id': stock_location.id,
1644 'location_dest_id': customer_location.id,
1645 'picking_type_id': warehouse.out_type_id.id,
1646 'move_ids': [(0, 0, {
1647 'product_id': self.product1.id,
1648 'product_uom_qty': 1.0,
1649 'location_id': stock_location.id,
1650 'location_dest_id': customer_location.id,
1651 })]
1652 })
1653 delivery.action_confirm()
1654 delivery.move_ids.quantity = 1.0
1655 delivery.button_validate()
1656
1657 action = po.action_create_invoice()
1658 bill = self.env["account.move"].browse(action["res_id"])
1659 bill.invoice_date = bill.date = today
1660 bill.action_post()
1661
1662 in_stock_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)], order='id')
1663 self.assertRecordValues(in_stock_amls, [
1664 # pylint: disable=bad-whitespace
1665 {'debit': 0, 'credit': 4335.1, 'reconciled': True},
1666 {'debit': 4348, 'credit': 0, 'reconciled': True},
1667 {'debit': 0, 'credit': 12.9, 'reconciled': True},
1668 ])
1669
1670 def test_bill_with_zero_qty(self):
1671 """
1672 FIFO standard
1673 Receive two different product
1674 Bill them, but:
1675 Set the quantity of the first AML to zero
1676 Bill again the PO (for the "canceled" line in the first bill)
1677 """
1678 product1 = self.product1
1679 product2 = self.product1_copy
1680
1681 self.cat.property_valuation = 'real_time'
1682
1683 po_form = Form(self.env['purchase.order'])
1684 po_form.partner_id = self.partner_id
1685 with po_form.order_line.new() as po_line:
1686 po_line.product_id = product1
1687 po_line.product_qty = 1
1688 po_line.price_unit = 10.0
1689 with po_form.order_line.new() as po_line:
1690 po_line.product_id = product2
1691 po_line.product_qty = 1
1692 po_line.price_unit = 20.0
1693 po = po_form.save()
1694 po.button_confirm()
1695
1696 receipt = po.picking_ids
1697 receipt.move_ids.move_line_ids.quantity = 1
1698 receipt.button_validate()
1699
1700 action = po.action_create_invoice()
1701 bill01 = self.env["account.move"].browse(action["res_id"])
1702 bill01.invoice_date = fields.Date.today()
1703 bill01.invoice_line_ids.filtered(lambda l: l.product_id == product2).quantity = 0
1704 bill01.action_post()
1705
1706 self.assertEqual(bill01.state, 'posted')
1707 self.assertRecordValues(po.order_line, [
1708 {'product_id': product1.id, 'qty_invoiced': 1.0},
1709 {'product_id': product2.id, 'qty_invoiced': 0.0},
1710 ])
1711
1712 bill02 = self._bill(po)
1713 self.assertEqual(bill02.state, 'posted')
1714 self.assertRecordValues(po.order_line, [
1715 {'product_id': product1.id, 'qty_invoiced': 1.0},
1716 {'product_id': product2.id, 'qty_invoiced': 1.0},
1717 ])
1718
1719 stock_in_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id), ('balance', '!=', 0)], order='id')
1720 self.assertRecordValues(stock_in_amls, [
1721 {'product_id': product1.id, 'debit': 10.0, 'credit': 0.0},
1722 {'product_id': product1.id, 'debit': 0.0, 'credit': 10.0},
1723 {'product_id': product2.id, 'debit': 20.0, 'credit': 0.0},
1724 {'product_id': product2.id, 'debit': 0.0, 'credit': 20.0},
1725 ])
1726 self.assertTrue(all(aml.full_reconcile_id for aml in stock_in_amls))
1727
1728 def _test_fifo_and_returns_common(self):
1729 """
1730 FIFO auto
1731 Receive & Bill 1 @ 10
1732 """
1733 self.product1.categ_id.property_cost_method = 'fifo'
1734 self.product1.categ_id.property_valuation = 'real_time'
1735
1736 po_form = Form(self.env['purchase.order'])
1737 po_form.partner_id = self.partner_id
1738 with po_form.order_line.new() as po_line:
1739 po_line.product_id = self.product1
1740 po_line.product_qty = 1
1741 po_line.price_unit = 10.0
1742 po = po_form.save()
1743 po.button_confirm()
1744
1745 receipt = po.picking_ids
1746 receipt.move_ids.move_line_ids.quantity = 1
1747 receipt.button_validate()
1748
1749 self._bill(po)
1750
1751 def test_fifo_return_and_receive_all_on_backorder(self):
1752 """
1753 FIFO auto
1754 Receive & Bill 1 @ 10
1755 PO 4 @ 25
1756 Receive one with backorder
1757 Return it
1758 Receive 4 thanks to the backorder
1759 Bill them
1760 """
1761 self._test_fifo_and_returns_common()
1762
1763 po_form = Form(self.env['purchase.order'])
1764 po_form.partner_id = self.partner_id
1765 with po_form.order_line.new() as po_line:
1766 po_line.product_id = self.product1
1767 po_line.product_qty = 4
1768 po_line.price_unit = 25.0
1769 po = po_form.save()
1770 po.button_confirm()
1771
1772 receipt01 = po.picking_ids
1773 receipt01.move_ids.quantity = 1
1774 action = receipt01.button_validate()
1775 backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(action['context'])).save()
1776 backorder_wizard.process()
1777
1778 self._return(receipt01)
1779
1780 receipt02 = receipt01.backorder_ids
1781 receipt02.move_ids.quantity = 4
1782 receipt02.button_validate()
1783
1784 self._bill(po)
1785
1786 in_stock_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)], order='id')
1787 self.assertRecordValues(in_stock_amls, [
1788 # Receive and bill 1 @ 10
1789 {'debit': 0.0, 'credit': 10.0, 'reconciled': True},
1790 {'debit': 10.0, 'credit': 0.0, 'reconciled': True},
1791 # Receive 1 @ 25
1792 {'debit': 0.0, 'credit': 25.0, 'reconciled': True},
1793 # Return it (10 with valo, 15 with expense)
1794 {'debit': 10.0, 'credit': 0.0, 'reconciled': True},
1795 {'debit': 15.0, 'credit': 0.0, 'reconciled': True},
1796 # Receive all on the backorder (-> all based on PO price, we will not get the value of the returned one)
1797 {'debit': 0.0, 'credit': 100.0, 'reconciled': True},
1798 # Bill it
1799 {'debit': 100.0, 'credit': 0.0, 'reconciled': True},
1800 ])
1801 self.assertTrue(all(aml.full_reconcile_id for aml in in_stock_amls))
1802
1803 def test_fifo_return_twice_and_bill(self):
1804 """
1805 FIFO auto
1806 Receive & Bill 1 @ 10
1807 Receive 1 @ 25
1808 Return
1809 Receive it again
1810 Bill
1811 """
1812 self._test_fifo_and_returns_common()
1813
1814 po_form = Form(self.env['purchase.order'])
1815 po_form.partner_id = self.partner_id
1816 with po_form.order_line.new() as po_line:
1817 po_line.product_id = self.product1
1818 po_line.product_qty = 1
1819 po_line.price_unit = 25.0
1820 po = po_form.save()
1821 po.button_confirm()
1822
1823 receipt01 = po.picking_ids
1824 receipt01.move_ids.quantity = 1
1825 receipt01.button_validate()
1826
1827 receipt01_return = self._return(receipt01)
1828 self._return(receipt01_return)
1829 self._bill(po)
1830
1831 in_stock_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)], order='id')
1832 self.assertRecordValues(in_stock_amls, [
1833 # Receive and bill 1 @ 10
1834 {'debit': 0.0, 'credit': 10.0, 'reconciled': True},
1835 {'debit': 10.0, 'credit': 0.0, 'reconciled': True},
1836 # Receive 1 @ 25
1837 {'debit': 0.0, 'credit': 25.0, 'reconciled': True},
1838 # Return it (10 with valo, 15 with expense)
1839 {'debit': 10.0, 'credit': 0.0, 'reconciled': True},
1840 {'debit': 15.0, 'credit': 0.0, 'reconciled': True},
1841 # Receive it again
1842 # The "return of a return" ignores the POL price and uses the value of the returned product
1843 # So, same: 10 with valo, 15 with expense
1844 {'debit': 0.0, 'credit': 10.0, 'reconciled': True},
1845 {'debit': 0.0, 'credit': 15.0, 'reconciled': True},
1846 # Bill it
1847 {'debit': 25.0, 'credit': 0.0, 'reconciled': True},
1848 ])
1849 self.assertTrue(all(aml.full_reconcile_id for aml in in_stock_amls))
1850
1851 def test_fifo_bill_return_refund(self):
1852 """
1853 FIFO auto
1854 Receive & Bill 1 @ 10
1855 Receive 1 @ 25
1856 Bill
1857 Return
1858 Refund
1859 """
1860 self._test_fifo_and_returns_common()
1861
1862 po_form = Form(self.env['purchase.order'])
1863 po_form.partner_id = self.partner_id
1864 with po_form.order_line.new() as po_line:
1865 po_line.product_id = self.product1
1866 po_line.product_qty = 1
1867 po_line.price_unit = 25.0
1868 po = po_form.save()
1869 po.button_confirm()
1870
1871 receipt01 = po.picking_ids
1872 receipt01.move_ids.quantity = 1
1873 receipt01.button_validate()
1874
1875 self._bill(po)
1876 self._return(receipt01)
1877 self._bill(po) # Refund
1878
1879 in_stock_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)], order='id')
1880 self.assertRecordValues(in_stock_amls, [
1881 # Receive and bill 1 @ 10
1882 {'debit': 0.0, 'credit': 10.0, 'reconciled': True},
1883 {'debit': 10.0, 'credit': 0.0, 'reconciled': True},
1884 # Receive 1 @ 25
1885 {'debit': 0.0, 'credit': 25.0, 'reconciled': True},
1886 # Bill
1887 {'debit': 25.0, 'credit': 0.0, 'reconciled': True},
1888 # Return (10 with valo, 15 with expense)
1889 {'debit': 10.0, 'credit': 0.0, 'reconciled': True},
1890 {'debit': 15.0, 'credit': 0.0, 'reconciled': True},
1891 # Refund
1892 {'debit': 0.0, 'credit': 25.0, 'reconciled': True},
1893 ])
1894 self.assertTrue(all(aml.full_reconcile_id for aml in in_stock_amls))
1895
1896 def test_incoming_with_negative_qty(self):
1897 """
1898 FIFO/AVCO Auto
1899 Purchase one Product with negative qty
1900 Conform PO,
1901 It will create outgoing shipment
1902 this transfer is neither returned nor received but it will be a delivery(outgoing).
1903 """
1904 product1 = self.product1
1905 self.cat.property_valuation = 'real_time'
1906 shipping_partner = self.env["res.partner"].create({
1907 'name': "Shipping Partner",
1908 'street': "234 W 18th Ave",
1909 'city': "Columbus",
1910 'state_id': self.env.ref("base.state_us_30").id, # Ohio
1911 'country_id': self.env.ref("base.us").id,
1912 'zip': "43210",
1913 })
1914 po_form = Form(self.env['purchase.order'])
1915 po_form.partner_id = self.partner_id
1916 with po_form.order_line.new() as po_line:
1917 po_line.product_id = product1
1918 po_line.product_qty = -2
1919 po_line.price_unit = 10.0
1920 po = po_form.save()
1921 po.button_confirm()
1922 delivery = po.picking_ids
1923 # it is negative qty transfer so Odoo will create delivery instead of receipt.
1924 delivery.partner_id = shipping_partner
1925 move_line_vals = delivery.move_ids._prepare_move_line_vals()
1926 move_line = self.env['stock.move.line'].create(move_line_vals)
1927 move_line.quantity = 2.
1928 delivery.button_validate()
1929 self.assertEqual(delivery.state, 'done')
1930
1931 def test_return_a_return_avco_prod_with_exchange_diff(self):
1932 """ When there is some return of a return, we expect `_generate_price_difference_vals` to
1933 assume any pdiff existing in the relevant transfers' SVL records has already been
1934 compensated for. This should remain true in the case where the underlying purchase order
1935 has some currency exchange diff.
1936 """
1937 self.product1.categ_id.property_cost_method = 'average'
1938 avco_prod = self.product1
1939 (self.env.ref('base.EUR') + self.env.ref('base.CHF')).active = True
1940 euro_id = self.env.ref('base.EUR').id
1941 franc_id = self.env.ref('base.CHF').id
1942 self.env['res.currency.rate'].create([
1943 {'currency_id': euro_id, 'rate': 0.95},
1944 {'currency_id': franc_id, 'rate': 0.8},
1945 ])
1946 purchase_order = self.env['purchase.order'].create({
1947 'partner_id': self.partner_a.id,
1948 'currency_id': euro_id,
1949 'order_line': [Command.create({
1950 'product_id': avco_prod.id,
1951 'product_uom_qty': 5,
1952 'price_unit': 10,
1953 })],
1954 })
1955 purchase_order.button_confirm()
1956 receipt1 = purchase_order.picking_ids
1957 receipt1.button_validate()
1958
1959 purchase_order = self.env['purchase.order'].create({
1960 'partner_id': self.partner_b.id,
1961 'currency_id': franc_id,
1962 'order_line': [Command.create({
1963 'product_id': avco_prod.id,
1964 'product_uom_qty': 5,
1965 })],
1966 })
1967 purchase_order.button_confirm()
1968 receipt2 = purchase_order.picking_ids
1969 receipt2.button_validate()
1970
1971 receipt2_return1 = self._return(receipt2)
1972 # return the initial return
1973 self._return(receipt2_return1)
1974 pre_bill_cost = avco_prod.standard_price
1975 purchase_order.action_create_invoice()
1976 bill = purchase_order.invoice_ids
1977 bill.invoice_date = fields.Date.today()
1978 bill.action_post()
1979 self.assertEqual(avco_prod.standard_price, pre_bill_cost)
1980
1981 def test_manual_non_standard_cost_bill_post(self):
1982 """ With manual valuation (+ continental accounting), receiving some product with a
1983 non-standard cost method, consuming the available qty, and then invoicing that product at
1984 different `price_unit` than the receipt should not create pdiff AccountMoveLines.
1985 """
1986 self.env.company.anglo_saxon_accounting = False
1987 self.product1.categ_id.write({
1988 'property_valuation': 'periodic',
1989 'property_cost_method': 'average',
1990 })
1991 product = self.product1
1992 purchase_order = self.env['purchase.order'].create({
1993 'partner_id': self.partner_a.id,
1994 'order_line': [Command.create({
1995 'product_id': product.id,
1996 'product_qty': 10,
1997 'price_unit': 100,
1998 })],
1999 })
2000 purchase_order.button_confirm()
2001 purchase_order.picking_ids.button_validate()
2002 with Form(self.env['stock.scrap']) as scrap_form:
2003 scrap_form.product_id = product
2004 scrap_form.scrap_qty = 10
2005 scrap = scrap_form.save()
2006 scrap.action_validate()
2007 purchase_order.action_create_invoice()
2008 bill = purchase_order.invoice_ids
2009 bill.invoice_line_ids.price_unit = 120
2010 bill.invoice_date = fields.Date.today()
2011 bill.action_post()
2012 expense_account, tax_paid_account, account_payable_account = (
2013 self.company_data['default_account_expense'],
2014 self.company_data['default_account_tax_purchase'],
2015 self.company_data['default_account_payable'],
2016 )
2017 self.assertRecordValues(
2018 bill.line_ids,
2019 [
2020 {'account_id': expense_account.id, 'debit': 1200.0, 'credit': 0.0},
2021 {'account_id': tax_paid_account.id, 'debit': 180.0, 'credit': 0.0},
2022 {'account_id': account_payable_account.id, 'debit': 0.0, 'credit': 1380.0},
2023 ]
2024 )
2025
2026 def test_100_percent_discount(self):
2027 product = self.product_a
2028 product.categ_id.write({'property_cost_method': 'average', 'property_valuation': 'real_time'})
2029 purchase_order = self.env['purchase.order'].create({
2030 'partner_id': self.partner_a.id,
2031 'order_line': [Command.create({
2032 'product_id': product.id,
2033 'product_qty': 2,
2034 'discount': 100,
2035 })],
2036 })
2037 purchase_order.button_confirm()
2038 receipt = purchase_order.picking_ids
2039 receipt.button_validate()
2040 purchase_order.action_create_invoice()
2041 bill = purchase_order.invoice_ids
2042 bill.invoice_date = fields.Date.today()
2043 bill.action_post()
2044 svls = self.env['stock.valuation.layer'].search([])
2045 self.assertRecordValues(svls, [{'value': 0, 'quantity': 2}])
2046
2047 def test_standard_valuation_return_credit_note(self):
2048 self.env.company.anglo_saxon_accounting = True
2049 self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
2050 self.product1.product_tmpl_id.categ_id.property_valuation = 'real_time'
2051
2052 po = self.env['purchase.order'].create({
2053 'partner_id': self.partner_id.id,
2054 'order_line': [
2055 Command.create({
2056 'name': self.product1.name,
2057 'product_id': self.product1.id,
2058 'product_qty': 1.0,
2059 'price_unit': 100.0,
2060 'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
2061 }),
2062 ],
2063 })
2064 po.button_confirm()
2065 receipt_po = po.picking_ids[0]
2066 receipt_po.button_validate()
2067
2068 self._bill(po) # Bill
2069 self._return(receipt_po)
2070 self._bill(po) # Refund
2071
2072 in_stock_amls = self.env['account.move.line'].search([('account_id', '=', self.stock_input_account.id)], order='id')
2073 self.assertRecordValues(in_stock_amls, [
2074 # Receive and Vendor Bill 1 @ 100
2075 {'debit': 100.0, 'credit': 0.0, 'reconciled': True},
2076 {'debit': 0.0, 'credit': 100.0, 'reconciled': True},
2077 # Return and Vendor Credit Note 1 @ 100
2078 {'debit': 0.0, 'credit': 100.0, 'reconciled': True},
2079 {'debit': 100.0, 'credit': 0.0, 'reconciled': True},
2080 ])