WITH
target AS (select target_vol vincr, target_prc pincr)
,testv AS (
    SELECT
        sum(units) tot
        ,sum(units) FILTER (WHERE iter IN ('plan','diff','copy')) base
        ,sum(units) FILTER (WHERE module = 'new basket') newpart
    FROM
        rlarp.osm_pool
    WHERE
        -----------------scenario----------------------------
        where_clause
        -----------------additional params-------------------
        AND calc_status||flag <> 'CLOSEDREMAINDER' --exclude short ships when building order adjustments
        AND order_date <= ship_date
)
-- select * from testv
--
,flagv AS (
    SELECT
        tot
        ,base
        ,newpart
        ,CASE WHEN tot = 0 THEN
            CASE WHEN base = 0 THEN
                CASE WHEN newpart = 0 THEN
                    'unclean data. tested -> does not exist'
                ELSE
                    'scale new part'
                END
            ELSE
                'scale copy'
            END
        ELSE
            'scale all'
        END flag
    FROM
        testv
)
-- select * from flagv
--
,basemix AS (
    SELECT
        fspr
        ,plnt          ---master data
        ,promo          --history date mix
        ,terms
        ,bill_cust_descr          --history cust mix
        ,ship_cust_descr          --history cust mix
        ,dsm
        ,quota_rep_descr          --master data
        ,director
        ,billto_group          --master data
        ,shipto_group
        ,chan          --master data
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line          --master data
        ,r_currency          --history cust mix
        ,coalesce(r_rate,1) as r_rate         --master data
        ,c_currency          --master data
        ,coalesce(c_rate,1) as c_rate          --master data
        ,sum(coalesce(units,0)) units          --history value
        ,sum(coalesce(value_loc,0)) value_loc          --history value
        ,sum(coalesce(value_usd,0)) value_usd          --0
        ,sum(coalesce(cost_loc,0)) cost_loc          --history part mix
        ,sum(coalesce(cost_usd,0)) cost_usd
        ,sum(coalesce(pounds,0)) pounds
        ,calc_status          --0
        ,flag          --0
        ,order_date          --history date mix
        ,order_month
        ,order_season
        ,request_date          --history date mix
        ,request_month
        ,request_season
        ,ship_date          --history date mix
        ,ship_month
        ,ship_season
    FROM
        rlarp.osm_pool
    WHERE
        -----------------scenario----------------------------
        where_clause
        -----------------additional params-------------------
        AND CASE (SELECT flag FROM flagv)
                WHEN 'scale all' THEN true
                WHEN 'scale copy' THEN iter IN ('plan','diff','copy')
                WHEN 'scale new part' THEN module = 'new basket'
            END
        AND calc_status||flag <> 'CLOSEDREMAINDER' --exclude short ships when building order adjustments
        AND order_date <= ship_date
    GROUP BY
        fspr
        ,plnt          ---master data
        ,promo          --history date mix
        ,terms
        ,bill_cust_descr          --history cust mix
        ,ship_cust_descr          --history cust mix
        ,dsm
        ,quota_rep_descr          --master data
        ,director
        ,billto_group          --master data
        ,shipto_group
        ,chan          --master data
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line          --master data
        ,r_currency          --history cust mix
        ,r_rate          --master data
        ,c_currency          --master data
        ,c_rate          --master data
        ,calc_status          --0
        ,flag          --0
        ,order_date          --history date mix
        ,order_month
        ,order_season
        ,request_date          --history date mix
        ,request_month
        ,request_season
        ,ship_date          --history date mix
        ,ship_month
        ,ship_season
)
-- select * from basemix
--
,vscale AS (
    SELECT
        (SELECT vincr::numeric FROM target) incr
        ,(SELECT sum(units)::numeric FROM basemix) base
        -- If sum(units) = 0, then we're likely working with a single row. We can't
        -- scale 0, no matter how we try, so we just use mod_volume to set the value we want.
        -- When sum(units) <> 0, then we use factor to scale units.
        ,CASE
         WHEN (SELECT sum(units)::numeric FROM basemix) = 0
         THEN 0
         ELSE (SELECT vincr::numeric FROM target)/(SELECT sum(units)::numeric FROM basemix)
         END AS factor
        ,CASE
         WHEN (SELECT sum(units)::numeric FROM basemix) = 0
         THEN (SELECT vincr::numeric FROM target)
         ELSE 0
         END AS mod_volume
)
-- select * from vscale
--
,log AS (
    INSERT INTO rlarp.osm_log(doc) SELECT $$replace_iterdef$$::jsonb doc RETURNING *
)
,volume AS (
    SELECT
        fspr
        ,plnt          ---master data
        ,promo          --history date mix
        ,terms
        ,bill_cust_descr          --history cust mix
        ,ship_cust_descr          --history cust mix
        ,dsm
        ,quota_rep_descr          --master data
        ,director
        ,billto_group          --master data
        ,shipto_group
        ,chan          --master data
        ,chansub
        ,chan_retail
        ,b.part
        ,part_descr
        ,part_group
        ,b.branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line          --master data
        ,r_currency          --history cust mix
        ,r_rate          --master data
        ,c_currency          --master data
        ,c_rate          --master data
        ,round(CASE WHEN s.factor = 0 THEN s.mod_volume ELSE units*s.factor END, 2) units
        ,round(value_loc*s.factor, 2) value_loc
        ,round(value_usd*s.factor, 2) value_usd
        ,round(cost_loc*s.factor,  2) cost_loc
        ,round(cost_usd*s.factor,  2) cost_usd
        ,calc_status          --0
        ,flag          --0
        ,order_date          --history date mix
        ,order_month
        ,order_season
        ,request_date          --history date mix
        ,request_month
        ,request_season
        ,ship_date          --history date mix
        ,ship_month
        ,ship_season
        ,'replace_version' "version"
        ,'replace_source'||' volume'  iter
        ,log.id
        ,COALESCE(log.doc->>'tag','') "tag"
        ,log.doc->>'message' "comment"
        ,log.doc->>'type' module
        ,round(CASE
               WHEN s.factor = 0 THEN s.mod_volume * i.nwht * (CASE i.nwun
                                                               WHEN 'KG' THEN 2.2046
                                                               ELSE 1 END)
               ELSE pounds*s.factor END, 2) pounds
FROM
    basemix b
    CROSS JOIN vscale s
    CROSS JOIN log
    LEFT OUTER JOIN "CMS.CUSLG".itemm i ON i.item = b.part
)
-- select * from volume
--
,pscale AS (
    SELECT
        CASE
        WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 AND (SELECT sum(units) FROM volume) = 0 THEN 'both'
        WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 THEN 'cost'
        ELSE 'other'
        END zero_values
        ,CASE
        WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 AND (SELECT coalesce(sum(units),0) FROM volume) = 0 -- Split pincr evenly between rows.
            THEN (SELECT pincr::numeric FROM target) / (SELECT nullif(count(*),0) FROM volume)
        WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0   -- Get a per-unit pincr value
            THEN (SELECT pincr::numeric FROM target) / (SELECT nullif(sum(units),0) FROM volume)
        ELSE  -- Find percent change for existing value_loc
            (SELECT pincr::numeric FROM target) / (SELECT nullif(sum(value_loc),0) FROM volume) - 1
        END factor
)
-- select * from pscale
--
,pricing AS (
    SELECT
        fspr
        ,plnt          ---master data
        ,promo          --history date mix
        ,terms
        ,bill_cust_descr          --history cust mix
        ,ship_cust_descr          --history cust mix
        ,dsm
        ,quota_rep_descr          --master data
        ,director
        ,billto_group          --master data
        ,shipto_group
        ,chan          --master data
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line          --master data
        ,r_currency          --history cust mix
        ,r_rate          --master data
        ,c_currency          --master data
        ,c_rate          --master data
        ,0::numeric units
        ,round(CASE s.zero_values
                WHEN 'both' THEN s.factor / b.r_rate
                WHEN 'cost' THEN b.units * s.factor / b.r_rate
                WHEN 'other' THEN b.value_loc * s.factor
                END, 2) AS value_loc
        ,round(CASE s.zero_values
                WHEN 'both' THEN s.factor
                WHEN 'cost' THEN b.units * s.factor
                WHEN 'other' THEN b.value_usd * s.factor
                END, 2) AS value_usd
        ,0::numeric cost_loc
        ,0::numeric cost_usd
        ,calc_status          --0
        ,flag          --0
        ,order_date          --history date mix
        ,order_month
        ,order_season
        ,request_date          --history date mix
        ,request_month
        ,request_season
        ,ship_date          --history date mix
        ,ship_month
        ,ship_season
        ,'replace_version' "version"
        ,'replace_source'||' price'  iter
        ,log.id
        ,COALESCE(log.doc->>'tag','') "tag"
        ,log.doc->>'message' "comment"
        ,log.doc->>'type' module
        ,0::numeric pounds
    FROM
        volume b
        CROSS JOIN pscale s
        CROSS JOIN log
    WHERE
        s.factor <> 0
)
-- SELECT * FROM pricing UNION ALL SELECT * FROM volume
--
, ins AS (
    INSERT INTO rlarp.osm_pool (SELECT * FROM pricing UNION ALL SELECT * FROM volume) RETURNING *
)
,insagg AS (
    SELECT
        ---------customer info-----------------
        bill_cust_descr
        ,billto_group
        ,ship_cust_descr
        ,shipto_group
        ,quota_rep_descr
        ,director
        ,segm
        ,substance
        ,chan
        ,chansub
        ---------product info------------------
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        --,brand
        --,part_family
        ,part_group
        ,branding
        --,color
        ,part_descr
        ---------dates-------------------------
        ,order_season
        ,order_month
        ,ship_season
        ,ship_month
        ,request_season
        ,request_month
        ,promo
        ,version
        ,iter
        ,logid
        ,tag
        ,comment
        --------values-------------------------
        ,sum(value_loc) value_loc
        ,sum(value_usd) value_usd
        ,sum(cost_loc) cost_loc
        ,sum(cost_usd) cost_usd
        ,sum(units) units
        ,sum(pounds) pounds
    FROM
        ins
    GROUP BY
        ---------customer info-----------------
        bill_cust_descr
        ,billto_group
        ,ship_cust_descr
        ,shipto_group
        ,quota_rep_descr
        ,director
        ,segm
        ,substance
        ,chan
        ,chansub
        ---------product info------------------
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        --,brand
        --,part_family
        ,part_group
        ,branding
        --,color
        ,part_descr
        ---------dates-------------------------
        ,order_season
        ,order_month
        ,ship_season
        ,ship_month
        ,request_season
        ,request_month
        ,promo
        ,version
        ,iter
        ,logid
        ,tag
        ,comment
)
-- select * from insagg
--
SELECT json_agg(row_to_json(insagg)) x from insagg
