WITH
customers AS (
    SELECT shipgrp,dsm,pounds::numeric pounds FROM (VALUES
    ('AL PAR PEAT CO','10035 - MATTHEW STAAL','20000'),
    ('AMA PLASTICS','40040 - TINA PETTIGREW','10000'),
    ('AMERICAN FARMS','10039 - DUSTIN KUYKENDOLL','50000'),
    ('ARMSTRONG GROWERS','30035 - RODNEY RIOS','50000'),
    ('AUBIN NURSERIES LTD','40040 - TINA PETTIGREW','5000'),
    ('BRADFORD CO-OP STORAGE LTD','40040 - TINA PETTIGREW','5000'),
    ('BRADFORD GREENHOUSES','40040 - TINA PETTIGREW','50000'),
    ('CAL COLOR','30054 - JASON MOTTIN','15000'),
    ('CONROE GREENHOUSES INC','10041 - TAMARA RISKEN','13438'),
    ('CY GROWERS SUPPLIES LTD','40042 - TOM MORRIS','18710'),
    ('DAN & JERRYS GREENHOUSE','13027 - STEVE RUSTEBERG','50000'),
    ('DEVRY GREENHOUSES','40042 - TOM MORRIS','24957'),
    ('DREAM WITH COLORS','30035 - RODNEY RIOS','50000'),
    ('ENCHANTED GARDENS','10041 - TAMARA RISKEN','2396'),
    ('FREEMAN HERBS','40039 - DAVE BODO','20000'),
    ('GARDEN STATE GROWERS','10043 - CHERISSE GILSTROP','60000'),
    ('GREAT LAKES GREENHOUSES','13025 - JAMES REGER','2000'),
    ('GREEN LAKE NURSERY','10041 - TAMARA RISKEN','11218'),
    ('HALIFAX SEED CO INC','40040 - TINA PETTIGREW','5000'),
    ('HARTS NURSERY','30053 - SKYE SAWYER','15000'),
    ('HEARTLAND GROWERS','10048 - PHILIP BIEDENBACH','67000'),
    ('HJS WHOLESALE LTD','40040 - TINA PETTIGREW','10000'),
    ('HYDROGARDEN SUPPLY SERVICES','40040 - TINA PETTIGREW','10000'),
    ('IRRIGATION PLUS INC','40040 - TINA PETTIGREW','3000'),
    ('IWASAKI BROS INC','30053 - SKYE SAWYER','14000'),
    ('JEFFRIES NURSERIES','40040 - TINA PETTIGREW','5000'),
    ('JOHNSON GARDEN CENTER','10041 - TAMARA RISKEN','1240'),
    ('KAW VALLEY GREENHOUSES','10041 - TAMARA RISKEN','6100'),
    ('KAWAHARA NURSERY','30054 - JASON MOTTIN','25000'),
    ('LA FERME GROVER INC','40043 - JEFFREY SCHAEFER','4000'),
    ('LUCAS GREENHOUSE','10043 - CHERISSE GILSTROP','22500'),
    ('MARIA GARDENS','10048 - PHILIP BIEDENBACH','9000'),
    ('MARTINSON''S GARDEN WORKS','10049 - STEVEN STUPPIELLO','50000'),
    ('MEYERS FRUIT FARM','70011 - DNU-SUSAN MURTAUGH','20000'),
    ('NOEL WILSON INC','40043 - JEFFREY SCHAEFER','20000'),
    ('NUTRIEN AG SOLUTIONS','40042 - TOM MORRIS','8993'),
    ('OELSCHIG NURSERY INC','10040 - RYAN CHITWOOD','56924'),
    ('OLSONS GREENHOUSE GARDENS','12028 - JACOB WILKINSON','20000'),
    ('PACIFIC GROWER','30053 - SKYE SAWYER','88000'),
    ('PARKS BROTHERS FARMS','10041 - TAMARA RISKEN','10380'),
    ('PETERSON NURSERY LLC','10041 - TAMARA RISKEN','2396'),
    ('PINEAE GREENHOUSES & DIST INC','12028 - JACOB WILKINSON','50000'),
    ('PLEASANT VALLEY FARM INC','10041 - TAMARA RISKEN','54666'),
    ('PLEASANT VIEW GARDENS','13028 - RICHARD MEULE','28000'),
    ('RAINBOW GREENHOUSES','40042 - TOM MORRIS','7929'),
    ('REKKER GARDENS INC','40040 - TINA PETTIGREW','2500'),
    ('RICHARDSON BROS GREENHOUSE INC','13027 - STEVE RUSTEBERG','90000'),
    ('ROWE PLANT FARM','10041 - TAMARA RISKEN','4096'),
    ('SEDAN FLORAL','10041 - TAMARA RISKEN','27744'),
    ('SHERIDAN NURSERIES','40039 - DAVE BODO','18816'),
    ('SMITH GARDENS INC','30053 - SKYE SAWYER','44000'),
    ('STOKLEY NURSERY','10049 - STEVEN STUPPIELLO','80000'),
    ('TERIS SUPPLY SERVICES','40043 - JEFFREY SCHAEFER','12000'),
    ('TIDAL CREEK GROWERS','10043 - CHERISSE GILSTROP','20623'),
    ('UNCLE JOHN''S PLANT FARM','10048 - PHILIP BIEDENBACH','10000'),
    ('WELBY GARDENS','12028 - JACOB WILKINSON','4507')
) x(shipgrp,dsm,pounds)
)
,parts AS (
    SELECT part,units::numeric units,price::numeric price,pounds::numeric pounds FROM (VALUES
('KEP010P0G18B524','43378',0.04,956.4849,0.02205),
('KET12P10G18B027','3615',0.54,1075.8963,0.29762),
('KEP010Q0G18B281','28919',0.072,1275.03871,0.04409),
('KET08Q11G18B019','3615',0.6785,914.595,0.253),
('KEP015P0G18B316','36149',0.05506,956.50254,0.02646),
('KET10P15G18B030','3615',0.5488,1075.8963,0.29762),
('KEP020Q0G18B170','28919',0.105,1912.70266,0.06614),
('KET08Q21G18B019','3615',0.9132,1753.3473,0.48502)
) x(part,units,price,pounds,weight)
)
,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)
)
,keystone AS (
    select 
         c.shipgrp 
        ,c.dsm 
        ,c.pounds
        ,p.part 
        ,p.units
        ,p.price
        ,p.pounds
        ,c.pounds/10000 scale
        ,round((c.pounds/10000)*p.units,0) fc_units
        ,round((c.pounds/10000)*p.units,0)*(p.pounds/p.units) fc_lbs
    FROM 
        customers  c
        CROSS JOIN parts p
)
,alldates AS (
    SELECT
        bill_cust_descr
        ,ship_cust_descr
        ,shipto_group
        ,promo
        ,terms
        ,r_currency
        -- ,order_month
        -- ,mseq.s seq
        ,order_date
        -- ,request_date
        ,ship_date
        -- ,ship_month
        -- ,sum(value_usd) value_usd_net
        ,sum(pounds) pounds_net
        -- ,sum(value_usd) FILTER (WHERE iter IN ('copy','actuals','actuals_plug')) value_usd_baseline
        ,sum(pounds)    FILTER (WHERE iter IN ('copy','actuals','actuals_plug')) pounds_baseline
    FROM
        rlarp.osm_pool
    WHERE
        shipto_group IN (select distinct shipgrp FROM customers)
        -----------------scenario----------------------------
        -- AND version IN ('b26')
        AND order_season = 2026
        AND ship_season = 2026
        -----------------additional params-------------------
        AND calc_status||flag <> 'CLOSEDREMAINDER' --exclude short ships when building order adjustments
        AND order_date <= ship_date
    GROUP BY
        bill_cust_descr
        ,ship_cust_descr
        ,shipto_group
        ,promo
        ,terms
        ,r_currency
        -- ,order_month
        -- ,mseq.s seq
        ,order_date
        -- ,request_date
        ,ship_date
        -- ,ship_month
    -- HAVING
    --     sum(value_usd) <> 0
)
,date_rank as (
    SELECT 
        bill_cust_descr
        ,ship_cust_descr
        ,shipto_group
        ,promo
        ,terms
        ,r_currency
        ,order_date
        ,ship_date
        ,row_number() over (partition by shipto_group order by pounds_baseline desc) rn
        ,COALESCE(pounds_baseline ,pounds_net) pounds
        -- ,CASE WHEN sum(pounds_net) OVER ()      = 0 THEN 0 ELSE round(pounds_net      / sum(pounds_net)      OVER (),5) END fc_mix
        -- ,CASE WHEN sum(pounds_baseline) OVER () = 0 THEN 0 ELSE round(pounds_baseline / sum(pounds_baseline) OVER (),5) END baseline_mix
    FROM 
        alldates
    ORDER BY 
        order_date ASC
        ,ship_date ASC
)
,date_mix  as (
    SELECT 
        bill_cust_descr
        ,ship_cust_descr
        ,shipto_group
        ,promo
        ,terms
        ,r_currency
        ,order_date
        ,ship_date
        ,rn
        ,pounds/sum(pounds) over (partition by shipto_group) mix
        -- ,CASE WHEN sum(pounds_net) OVER ()      = 0 THEN 0 ELSE round(pounds_net      / sum(pounds_net)      OVER (),5) END fc_mix
        -- ,CASE WHEN sum(pounds_baseline) OVER () = 0 THEN 0 ELSE round(pounds_baseline / sum(pounds_baseline) OVER (),5) END baseline_mix
    FROM 
        date_rank
    WHERE 
        rn <= 3
    ORDER BY 
        order_date ASC
        ,ship_date ASC
)
,combine AS (
    SELECT 
        k.*
        ,d.*
        ,k.scale * d.mix factor
        ,d.mix * k.scale * k.fc_lbs split_pounds
        ,d.mix * k.scale * k.units split_units
    FROM 
        keystone k 
        LEFT OUTER JOIN date_mix d ON 
            d.shipto_group = k.shipgrp
)
-- SELECT * FROM date_mix where shipto_group ~ 'SHERIDAN'
-- select * from combine
,basemix AS (
SELECT 
     od.fspr
    ,c.promo
    ,c.terms
    ,c.r_currency
    ,c.bill_cust_descr
    ,c.ship_cust_descr
    ,c.dsm quota_rep_descr
    ,c.part
    ,round(c.factor * c.units,0) units
    ,round(c.factor * c.fc_lbs,0) pounds
    ,round(c.factor * c.units,0)* c.price value_usd --assume that target dollars are USD
    ,c.order_date
    ,od.sortmo order_month
    ,od.ssyr order_season
    ,c.ship_date request_date
    ,sd.sortmo request_month
    ,sd.ssyr request_season
    ,c.ship_date
    ,sd.sortmo ship_month
    ,sd.ssyr ship_season
    ,c.factor
    ,c.split_pounds
FROM
    combine c
    LEFT OUTER JOIN rlarp.gld sd ON 
        c.ship_date <@ sd.drange
    LEFT OUTER JOIN rlarp.gld od ON 
        c.order_date <@ od.drange
)
,log AS (
    INSERT INTO rlarp.osm_log (doc) SELECT jsonb_build_object('user',current_user,'tag','Keystone Incr','type','Keystone Incr','stamp',current_timestamp,'source','top level','message','Keystone Incr') RETURNING *
)
,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
    ,'b26' "version"
    ,'Keystone Incr'  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
    -- ,i.nwht * CASE i.nwun WHEN 'KG' THEN 2.2046 ELSE 1 END weight
    -- ,b.pounds ref_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'
)
INSERT INTO rlarp.osm_pool SELECT * FROM final;
-- select * from final
