11# Copyright 2020 ForgeFlow <http://www.forgeflow.com>
2+ # Copyright 2021 Andrii Skrypka
23# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
34from openupgradelib import openupgrade
45
@@ -15,9 +16,56 @@ def fill_account_move_line_is_landed_costs_line(env):
1516 )
1617
1718
19+ def _generate_stock_valuation_layer (env ):
20+ """Insert a svl record per landed cost line, indicating the cost."""
21+ openupgrade .logged_query (
22+ env .cr , """
23+ INSERT INTO stock_valuation_layer (value, unit_cost, quantity, remaining_qty,
24+ stock_valuation_layer_id, description, stock_move_id, product_id,
25+ stock_landed_cost_id, company_id, account_move_id, create_date, create_uid,
26+ write_date, write_uid)
27+ SELECT sval.additional_landed_cost, 0.0, 0.0, 0.0,
28+ svl.id, slc.name, sm.id, sm.product_id,
29+ slc.id, am.company_id, am.id, am.create_date, am.create_uid,
30+ am.write_date, am.write_uid
31+ FROM stock_landed_cost slc
32+ JOIN account_move am ON am.id = slc.account_move_id
33+ JOIN stock_valuation_adjustment_lines sval ON sval.cost_id = slc.id
34+ JOIN stock_move sm ON sm.id = sval.move_id
35+ LEFT JOIN (
36+ SELECT MIN(id) as id, stock_move_id
37+ FROM stock_valuation_layer
38+ GROUP BY stock_move_id
39+ ) svl ON svl.stock_move_id = sval.move_id
40+ WHERE slc.state = 'done'
41+ """ ,
42+ )
43+
44+
45+ def _fix_value_for_svl (env ):
46+ """As previous stock move price unit contains the landed cost price, the
47+ svl were created counting with this price, so we have to substract it now.
48+ """
49+ openupgrade .logged_query (
50+ env .cr , """
51+ UPDATE stock_valuation_layer svl
52+ SET value = svl.value - svl_value.diff
53+ FROM (
54+ SELECT stock_valuation_layer_id as id, SUM(value) as diff
55+ FROM stock_valuation_layer
56+ WHERE stock_valuation_layer_id IS NOT NULL
57+ GROUP BY stock_valuation_layer_id
58+ ) svl_value
59+ WHERE svl_value.id = svl.id
60+ """ ,
61+ )
62+
63+
1864@openupgrade .migrate ()
1965def migrate (env , version ):
2066 fill_account_move_line_is_landed_costs_line (env )
2167 openupgrade .load_data (
2268 env .cr , "stock_landed_costs" ,
2369 "migrations/13.0.1.1/noupdate_changes.xml" )
70+ _generate_stock_valuation_layer (env )
71+ _fix_value_for_svl (env )
0 commit comments