WITH
/*
the volume must be expressed in terms of units, since that is what it will be scaling
*/
target AS (select $$replace_request$$::json def)
,seg AS (
    SELECT
        x.GLEC glec
        ,x.SEGM segm
    FROM
        (
            VALUES
            ('1SU','Sustainable'),
            ('1CU','Sustainable'),
            ('1GR','Greenhouse'),
            ('1NU','Nursery'),
            ('1RE','Retail'),
            ('2WI','Greenhouse'),
            ('3BM','Other'),
            ('3CO','Other'),
            ('3PE','Other'),
            ('3PP','Other'),
            ('4CO','Other'),
            ('4RA','Other'),
            ('9MI','Other'),
            ('9SA','Other'),
            ('9TO','Other')
        ) X(GLEC, SEGM)
)
,copr AS (
    SELECT
        LTRIM(RTRIM(A9)) AS COMP,
        A30 AS DESCR,
        SUBSTR(C.A249,242,2) CURR,
        SUBSTR(C.A249,32,4) AS GL,
        SUBSTR(C.A249,190,4) AS AR,
        SUBSTR(C.A249,182,4) AS AP,
        SUBSTR(C.A249,198,4) AS FA,
        SUBSTR(C.A249,238,4) AS IC ,
        SUBSTR(D.A249,9,5) CONS_FUNC
    FROM
        LGDAT.CODE
        LEFT OUTER JOIN LGDAT.NAME C ON
            'C0000'||LTRIM(RTRIM(A9)) = C.A7
        LEFT OUTER JOIN LGDAT.NAME D ON
            'D0000'||LTRIM(RTRIM(A9)) = D.A7
    WHERE
        A2 = 'AA' OR A2 IS NULL
)
,parts AS (
    SELECT 
        jr.*
    FROM 
        target
        JOIN LATERAL json_array_elements(def->'parts') as ae(e) ON true
        JOIN LATERAL json_to_record(ae.e) as jr(part text, qty numeric, price numeric, pounds numeric) ON true
)
-- SELECT * FROM parts
,dates AS (
    SELECT 
        jr.*
        ,def->'scenario'->>'quota_rep_descr' quota_rep_descr
    FROM 
        target
        JOIN LATERAL json_array_elements(def->'dates') as ae(e) ON true
        JOIN LATERAL json_to_record(ae.e) as jr(
             bill_cust_descr	text
            ,ship_cust_descr	text
            ,promo	            text
            ,terms	            text
            ,r_currency	        text
            ,order_date	        date
            ,ship_date	        date
            ,fc_mix	            numeric
            ,baseline_mix       numeric
        ) ON true
)
-- SELECT * FROM dates
,basemix AS (
    SELECT
         od.fspr
        ,d.promo
        ,d.terms
        ,d.r_currency
        ,d.bill_cust_descr
        ,d.ship_cust_descr
        ,d.quota_rep_descr
        ,p.part
        ,round(d.fc_mix * p.qty,0) units
        ,round(d.fc_mix * p.qty,0)* p.price value_usd --assume that target dollars are USD
        ,d.order_date
        ,od.sortmo order_month
        ,od.ssyr order_season
        ,d.ship_date request_date
        ,sd.sortmo request_month
        ,sd.ssyr request_season
        ,d.ship_date
        ,sd.sortmo ship_month
        ,sd.ssyr ship_season
    FROM
        dates d
        CROSS JOIN parts p
        LEFT OUTER JOIN rlarp.gld sd ON 
            d.ship_date <@ sd.drange
        LEFT OUTER JOIN rlarp.gld od ON 
            d.order_date <@ od.drange
)
,log AS (
    INSERT INTO rlarp.osm_log(doc) SELECT $$replace_iterdef$$::jsonb doc RETURNING *
)
-- SELECT * FROM basemix
,final AS (
SELECT
    b.fspr
    ,i.dplt plnt
    ,b.promo
    ,b.terms
    ,b.bill_cust_descr
    ,b.ship_cust_descr
    ,r.rcode
    ,b.quota_rep_descr
    ,r.director
    ,bc.dba billto_group
    ,sc.dba shipto_group
    ,CASE SUBSTRING(bc.cclass,2,3)
        --if the bill to class is ditsributor, then it's either warehouse or drop
        WHEN 'DIS' THEN
            --if the ship-to is a different name than the bill-to then it's drop, otherwise it's warehouse
            CASE SUBSTRING(sc.cclass,2,3)
                WHEN 'DIS' THEN 'WHS'
                ELSE 'DRP'
            END
            --CASE WHEN RTRIM(SUBSTRING(LTRIM(SC.BVADR7)||SC.BVNAME,1,30)) = RTRIM(SUBSTRING(LTRIM(BC.BVADR7)||BC.BVNAME,1,30)) THEN 'DIS' ELSE 'DRP' END
        --everything else does not involve a distributor and is considered direct
        ELSE 'DIR'
    END chan
    ,CASE SUBSTRING(bc.cclass,2,3)
        WHEN 'DIS' THEN
            --if the ship-to is a different name than the bill-to then it's drop, otherwise it's warehouse
            CASE SUBSTRING(sc.cclass,2,3)
                WHEN 'DIS' THEN 'WHS'
                ELSE CASE SUBSTRING(sc.cclass,1,1) WHEN 'R' THEN 'RDP' ELSE 'DRP' END
            END
        WHEN 'MAS' THEN 'RMN'
        WHEN 'NAT' THEN 'RMN'
        ELSE CASE SUBSTRING(sc.cclass,1,1) WHEN 'R' THEN 'RDI' ELSE 'DIR' END
    END chansub
    ,null::text chan_retail
    ,b.part
    ,b.part || ' - ' || i.descr
    ,i.partgroup
    ,i.branding
    ,i.majgd majg_descr
    ,i.mingd ming_descr
    ,i.majsd majs_descr
    ,i.minsd mins_descr
    ,seg.segm
    ,CASE WHEN i.majg = '610' THEN 'Fiber' ELSE 'Plastic' END substance
    ,'41010' fs_line          --master data
    ,b.r_currency          --history cust mix
    ,rx.rate r_rate          --master data
    ,pl.curr c_currency          --master data
    ,cx.rate c_rate          --master data
    ,round(b.units                                                            ,2) units
    ,round((b.value_usd / COALESCE(rx.rate,1))::numeric                       ,2) value_loc --b.value is denominated in USD, need to apply currency to get to local, assume 1 if using a fake customer
    ,round(b.value_usd                                                        ,2) value_usd --b.value is already denominated in usd
    ,round((i.futstd*b.units)::numeric        ,2) cost_loc
    ,round((i.futstdus*b.units)::numeric,2) cost_usd
    ,'CLOSED' calc_status
    ,'SHIPMENT' flag
    ,b.order_date
    ,b.order_month
    ,b.order_season
    ,b.request_date
    ,b.request_month
    ,b.request_season
    ,b.ship_date
    ,b.ship_month
    ,b.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(b.units * i.nwht * CASE i.nwun WHEN 'KG' THEN 2.2046 ELSE 1 END, 2) pounds
FROM 
    basemix b
    CROSS JOIN log
    LEFT OUTER JOIN rlarp.repc r ON 
        r.repp = b.quota_rep_descr
    LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
        i.item = b.part
    LEFT OUTER JOIN rlarp.cust bc ON 
        bc.code = rtrim(substring(b.bill_cust_descr,1,8))
    LEFT OUTER JOIN rlarp.cust sc ON 
        sc.code = rtrim(substring(b.ship_cust_descr,1,8))
    LEFT OUTER JOIN seg ON 
        seg.glec = i.glec
    LEFT OUTER JOIN rlarp.plpr pl ON 
        pl.plnt = i.dplt
    LEFT OUTER JOIN rlarp.ffcret cx ON
        cx.perd = pl.gl AND
        cx.rtyp = 'MA' AND
        cx.fcur = pl.curr AND
        cx.tcur = 'US'
    LEFT OUTER JOIN rlarp.ffcret rx ON
        rx.perd = pl.gl AND
        rx.rtyp = 'MA' AND
        rx.fcur = b.r_currency AND
        rx.tcur = 'US'
)
, 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
