-- Connection: usmidsap02.ubm
WITH
/*
the volume must be expressed in terms of units, since that is what it will be scaling
*/
input AS (
    select $$replace_request$$::json spec
)
-- select 'input', * from input
--
,target as (
    select
        ship_season, ship_month, pct
    from
        input i,
        json_to_recordset(i.spec->'distributions') AS x(ship_season int, ship_month text, pct numeric)
)
-- select 'target', * from target
--
,mseq AS (
    SELECT * FROM
    (
        VALUES
         ('01 - Jun',  1,  6, -1)
        ,('02 - Jul',  2,  7, -1)
        ,('03 - Aug',  3,  8, -1)
        ,('04 - Sep',  4,  9, -1)
        ,('05 - Oct',  5, 10, -1)
        ,('06 - Nov',  6, 11, -1)
        ,('07 - Dec',  7, 12, -1)
        ,('08 - Jan',  8,  1,  0)
        ,('09 - Feb',  9,  2,  0)
        ,('10 - Mar', 10,  3,  0)
        ,('11 - Apr', 11,  4,  0)
        ,('12 - May', 12,  5,  0)
    ) x(m,s,cal,yr)
)
-- select 'mseq', * from mseq
--
,basemix AS (
    SELECT
         fspr
        ,plnt
        ,promo
        ,terms
        ,bill_cust_descr
        ,ship_cust_descr
        ,dsm
        ,quota_rep_descr
        ,director
        ,billto_group
        ,shipto_group
        ,chan
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line
        ,r_currency
        ,coalesce(r_rate,1) as r_rate
        ,c_currency
        ,coalesce(c_rate,1) as c_rate
        ,sum(coalesce(units,0)) units
        ,sum(coalesce(value_loc,0)) value_loc
        ,sum(coalesce(value_usd,0)) value_usd
        ,sum(coalesce(cost_loc,0)) cost_loc
        ,sum(coalesce(cost_usd,0)) cost_usd
        ,sum(coalesce(pounds,0)) pounds
        ,calc_status
        ,flag
        ,order_date
        ,order_month
        ,order_season
        ,request_date
        ,request_month
        ,request_season
        ,ship_date
        ,ship_month
        ,ship_season
    FROM
        rlarp.osm_pool
    WHERE
        -----------------scenario----------------------------
        where_clause
        -----------------additional params-------------------
        AND order_date <= ship_date
    GROUP BY
        fspr
        ,plnt
        ,promo
        ,terms
        ,bill_cust_descr
        ,ship_cust_descr
        ,dsm
        ,quota_rep_descr
        ,director
        ,billto_group
        ,shipto_group
        ,chan
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line
        ,r_currency
        ,r_rate
        ,c_currency
        ,c_rate
        ,calc_status
        ,flag
        ,order_date
        ,order_month
        ,order_season
        ,request_date
        ,request_month
        ,request_season
        ,ship_date
        ,ship_month
        ,ship_season
)
-- select 'basemix', * from basemix
--
,subtractions AS (
    SELECT
         fspr
        ,plnt
        ,promo
        ,terms
        ,bill_cust_descr
        ,ship_cust_descr
        ,dsm
        ,quota_rep_descr
        ,director
        ,billto_group
        ,shipto_group
        ,chan
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line
        ,r_currency
        ,r_rate
        ,c_currency
        ,c_rate
        ,-(1 - target.pct) * units as units
        ,-(1 - target.pct) * value_loc as value_loc
        ,-(1 - target.pct) * value_usd as value_usd
        ,-(1 - target.pct) * cost_loc as cost_loc
        ,-(1 - target.pct) * cost_usd as cost_usd
        ,-(1 - target.pct) * pounds as pounds
        ,calc_status
        ,flag
        ,order_date
        ,order_month
        ,order_season
        ,request_date
        ,request_month
        ,request_season
        ,ship_date
        ,basemix.ship_month
        ,basemix.ship_season
    FROM basemix
    INNER JOIN target ON
        basemix.ship_season = target.ship_season AND
        basemix.ship_month = target.ship_month
)
-- select 'subtraction', * from subtraction
--
,additions AS (
    SELECT
         fspr
        ,plnt
        ,promo
        ,terms
        ,bill_cust_descr
        ,ship_cust_descr
        ,dsm
        ,quota_rep_descr
        ,director
        ,billto_group
        ,shipto_group
        ,chan
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line
        ,r_currency
        ,r_rate
        ,c_currency
        ,c_rate
        ,t.pct * coalesce(units) as units
        ,t.pct * coalesce(value_loc) as value_loc
        ,t.pct * coalesce(value_usd) as value_usd
        ,t.pct * coalesce(cost_loc) as cost_loc
        ,t.pct * coalesce(cost_usd) as cost_usd
        ,t.pct * coalesce(pounds) as pounds
        ,calc_status
        ,flag
        ,order_date
        ,order_month
        ,order_season
        ,request_date
        ,request_month
        ,request_season
        -- These case statements fix the situation where a ship date was specified that is earlier than
        -- the order date. If that happens, the new ship date becomes order date + 15 days. The case
        -- statements also handle rolling over to the next month or season.
        ,case
        when t.ship_season <= b.order_season AND t.ship_month < b.order_month then b.order_date + 15
        else make_date(t.ship_season, tMonths.cal, 1)
        end as ship_date
        ,case
        when t.ship_season <= b.order_season AND t.ship_month < b.order_month then bMonths.m
        else t.ship_month
        end as ship_month
        ,case
        when t.ship_season <= b.order_season AND t.ship_month < b.order_month then
            case
            when b.order_month > bMonths.m then b.order_season + 1 -- May-to-June rollover
            else b.order_season
            end
        else t.ship_season
        end as ship_season
    FROM basemix b
    LEFT OUTER JOIN target t ON
        b.ship_season <> t.ship_season OR
        b.ship_month <> t.ship_month
    INNER JOIN mseq bMonths ON
        EXTRACT (month FROM (b.order_date + 15)) = bMonths.cal
    INNER JOIN mseq tMonths ON
        t.ship_month = tMonths.m
)
-- select 'additions', * from additions
--
,log AS (
    INSERT INTO rlarp.osm_log(doc) SELECT $$replace_iterdef$$::jsonb doc RETURNING *
)
-- select 'log', * from log
--
,final AS (
    SELECT
        fspr
        ,plnt
        ,promo
        ,terms
        ,bill_cust_descr
        ,ship_cust_descr
        ,dsm
        ,quota_rep_descr
        ,director
        ,billto_group
        ,shipto_group
        ,chan
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line
        ,r_currency
        ,r_rate
        ,c_currency
        ,c_rate
        ,units
        ,value_loc
        ,value_usd
        ,cost_loc
        ,cost_usd
        ,calc_status
        ,flag
        ,order_date
        ,order_month
        ,order_season
        ,request_date
        ,request_month
        ,request_season
        ,ship_date
        ,ship_month
        ,ship_season
        ,'replace_version' "version"
        ,'replace_source' iter
        ,log.id
        ,COALESCE(log.doc->>'tag','Volume') "tag"
        ,log.doc->>'message' "comment"
        ,log.doc->>'type' module
        ,pounds
FROM subtractions
CROSS JOIN log
UNION ALL
    SELECT
        fspr
        ,plnt
        ,promo
        ,terms
        ,bill_cust_descr
        ,ship_cust_descr
        ,dsm
        ,quota_rep_descr
        ,director
        ,billto_group
        ,shipto_group
        ,chan
        ,chansub
        ,chan_retail
        ,part
        ,part_descr
        ,part_group
        ,branding
        ,majg_descr
        ,ming_descr
        ,majs_descr
        ,mins_descr
        ,segm
        ,substance
        ,fs_line
        ,r_currency
        ,r_rate
        ,c_currency
        ,c_rate
        ,units
        ,value_loc
        ,value_usd
        ,cost_loc
        ,cost_usd
        ,calc_status
        ,flag
        ,order_date
        ,order_month
        ,order_season
        ,request_date
        ,request_month
        ,request_season
        ,ship_date
        ,ship_month
        ,ship_season
        ,'replace_version' "version"
        ,'replace_source' iter
        ,log.id
        ,COALESCE(log.doc->>'tag','Volume') "tag"
        ,log.doc->>'message' "comment"
        ,log.doc->>'type' module
        ,pounds
FROM additions
CROSS JOIN log
)
-- select 'final', * from final
--
, ins AS (
    INSERT INTO rlarp.osm_pool SELECT * FROM final 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 'insagg', * from insagg
--
SELECT json_agg(row_to_json(insagg)) x from insagg
