WITH
----grouped prices-------------
pgrp AS (
	SELECT
		o.bill_dba 
		,o.ship_dba
        ,c.dsm
        ,i.partgroup
        ,i.pricegroup
		,o.part
		,o.odate
		,o.qtyord
		,i.nwht * CASE WHEN i.nwun = 'KG' THEN 2.2 ELSE 1 END lbs
		,i.mpck pltq
		,ROUND(o.sales_usd / o.qty,5) price
		,(o.pricing->>'guidance_price')::NUMERIC guidance
	    ,(o.pricing->>'floor'  )::numeric(15,5) floor        
	    ,(o.pricing->>'ceiling')::numeric(15,5) ceiling   
	    ,(o.pricing->>'uselimits')::boolean uselimits
	FROM
	 	rlarp.osm_stack o
	 	LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
	 		i.item = o.part
        INNER JOIN rlarp.cust_flag c ON 
            c.shipgrp = o.customer
            AND c.dsm = o.default_rep
	WHERE 
		VERSION = 'Actual' 
		AND o.oseas >= 2025
		AND calc_status <> 'CANCELED' 
		AND o.fs_line = '41010'
		AND o.part <> ''
		AND substring(o.glec,1,1) <= '2'
		AND o.qty <> 0
        AND o.sseas IS NOT NULL
        AND o.sales_usd <> 0
        -- AND customer in (select distinct renamed FROM newc )
	GROUP BY 
		o.bill_dba 
		,o.ship_dba
        ,c.dsm
        ,i.partgroup
        ,i.pricegroup
		,o.part
		,o.odate
		,o.qtyord
		,o.pounds
		,o.pallets
		,ROUND(o.sales_usd / o.qty,5)
		,i.nwht * CASE WHEN i.nwun = 'KG' THEN 2.2 ELSE 1 END
		,i.mpck
		,(o.pricing->>'guidance_price')::NUMERIC
	    ,(o.pricing->>'floor'  )::numeric(15,5)        
	    ,(o.pricing->>'ceiling')::numeric(15,5)
	    ,(o.pricing->>'uselimits')::boolean
)
-- SELECT * FROM pgrp where ship_dba ~ 'MONROVIA'
-- select * from npgrp limit 100
--sequenced for most recent price------------
,seq AS (
	SELECT 
		 bill_dba 
		,ship_dba
		,part
		,odate
		,qtyord
		,lbs
		,pltq
		,price last_price
		,guidance
	    ,floor        
	    ,ceiling   
	    ,uselimits
	    ,row_number() OVER (PARTITION BY bill_dba, ship_dba, part ORDER BY odate desc) rn
	    ,round(avg(price) over (PARTITION BY bill_dba, ship_dba, part),5) avgprice
	FROM 
		pgrp
)
-- SELECT * FROM SEQ WHERE ship_dba = 'MONROVIA' 
-- SELECT * FROM seq WHERE ship_dba like 'COSTA%'
,partlist AS (
    SELECT 
        billto_group
        ,shipto_group
        ,dsm
        ,part
        ,glec
        ,pricegroup
        ----order date as a proxy for order size
        ,order_date
        ,sum(units) qty
        ,round(sum(value_usd)/sum(units),5) hist_price
    FROM 
        rlarp.osm_pool o
        INNER JOIN "CMS.CUSLG".itemm i ON 
            i.item = o.part
    WHERE
        order_season = 2026
    GROUP BY
        billto_group
        ,shipto_group
        ,dsm
        ,part
        ,glec
        ,pricegroup
        ,order_date
    HAVING 
        abs(sum(units)) > 10
)
,combine AS MATERIALIZED (
-- select * from partlist
-- SELECT * FROM seq WHERE rn = 1 LIMIT 1000
-- ,guid AS (
    SELECT
         p.billto_group
        ,p.shipto_group
        ,p.dsm
        ,p.part
        ,p.glec
        ,p.pricegroup
        ,p.order_date
        ,p.qty
        ,p.hist_price
        ,CASE WHEN seq.floor = 0 THEN null else seq.floor END floor
        ,CASE WHEN seq.ceiling = 0 THEN null else seq.ceiling END ceiling
        ,seq.uselimits
        ,seq.last_price 
        ,seq.avgprice
        ,seq.pltq
        ,ROUND(CASE WHEN seq.uselimits THEN 
            CASE 
                WHEN glec = '1NU' THEN
                    --if more than 8/24 pallets, use floor
                    CASE WHEN p.qty >= 24*seq.pltq THEN seq.floor
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  8*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  2*seq.pltq THEN seq.ceiling
                    -- if more than a pallet use the target price 
                    ELSE  seq.ceiling * 1.05
                    END END END
                ELSE
                    CASE WHEN pricegroup ~ '(Hanger|Dish)' THEN
                        --at least 1 pallets is lower limit
                        CASE WHEN qtyord >= 01*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  0.5*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling 
                        END END
                    ELSE 
                        --at least 8 pallets is lower limit
                        CASE WHEN qtyord >= 08*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  2*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --at least 1 pallet is upper range
                        ELSE CASE WHEN qtyord >=  1*seq.pltq THEN seq.ceiling
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling * 1.15
                        END END END
                    END
            END
        ELSE 
            null 
        END,5) guid
        ,least(hist_price, last_price, avgprice) lowest_last
        ,least(hist_price, last_price, avgprice, CASE WHEN uselimits THEN 
         ROUND(CASE WHEN seq.uselimits THEN 
            CASE 
                WHEN glec = '1NU' THEN
                    --if more than 8/24 pallets, use floor
                    CASE WHEN p.qty >= 24*seq.pltq THEN seq.floor
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  8*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                    -- if more than a pallet use the target price 
                    ELSE CASE WHEN qtyord >=  2*seq.pltq THEN seq.ceiling
                    -- if more than a pallet use the target price 
                    ELSE  seq.ceiling * 1.05
                    END END END
                ELSE
                    CASE WHEN pricegroup ~ '(Hanger|Dish)' THEN
                        --at least 1 pallets is lower limit
                        CASE WHEN qtyord >= 01*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  0.5*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling 
                        END END
                    ELSE 
                        --at least 8 pallets is lower limit
                        CASE WHEN qtyord >= 08*seq.pltq THEN seq.floor
                        --at least 2 pallets is mid range
                        ELSE CASE WHEN qtyord >=  2*seq.pltq THEN (seq.ceiling + seq.floor) / 2
                        --at least 1 pallet is upper range
                        ELSE CASE WHEN qtyord >=  1*seq.pltq THEN seq.ceiling
                        --less than a pallet is upper + 15%
                        ELSE  seq.ceiling * 1.15
                        END END END
                    END
            END
        ELSE 
            null 
        END,5) ELSE hist_price END) lowest_guid
        ,c.flag
    FROM 
        partlist p
        INNER JOIN rlarp.cust_flag c ON 
            c.shipgrp = p.shipto_group
            AND substring(c.dsm,1,5) = substring(p.dsm,1,5)
        LEFT OUTER JOIN seq seq ON 
            seq.ship_dba = p.shipto_group
            AND seq.bill_dba = p.billto_group
            AND seq.part = p.part
            AND seq.rn = 1
        LEFT OUTER JOIN rlarp.repc r ON 
            r.rcode = p.dsm
)
-- SELECT * FROM combine where shipto_group = 'MONROVIA'
,choose AS MATERIALIZED (
    SELECT
         billto_group
        ,shipto_group
        ,dsm
        ,part
        ,glec
        ,pricegroup
        ,order_date
        ,qty
        ,hist_price
        ,floor
        ,ceiling
        ,uselimits
        ,last_price 
        ,avgprice
        ,pltq
        ,guid
        ,lowest_last
        ,lowest_guid
        ,flag
        ,CASE flag 
            WHEN 'YoY' THEN lowest_last
            WHEN 'Floor' THEN lowest_guid
            WHEN 'Retail' THEN hist_price
            WHEN 'Warehouse' THEN hist_price
            WHEN 'Orphan' THEN lowest_guid
            ELSE lowest_last 
        END price_choice
    FROM 
        combine
)
-- SELECT * FROM choose where shipto_group = 'MONROVIA' and part = 'NBB005G1BE2B014PYIQX'
-- ,delta_row AS (
--     SELECT
--          o.fspr            
--         ,o.plnt            
--         ,o.promo           
--         ,o.terms           
--         ,o.bill_cust_descr 
--         ,o.ship_cust_descr 
--         ,o.dsm             
--         ,o.quota_rep_descr 
--         ,o.director        
--         ,o.billto_group    
--         ,o.shipto_group    
--         ,o.chan            
--         ,o.chansub         
--         ,o.chan_retail     
--         ,o.part            
--         ,o.part_descr      
--         ,o.part_group      
--         ,o.branding        
--         ,o.majg_descr      
--         ,o.ming_descr      
--         ,o.majs_descr      
--         ,o.mins_descr      
--         ,o.segm            
--         ,o.substance       
--         ,o.fs_line         
--         ,o.r_currency      
--         ,o.r_rate          
--         ,o.c_currency      
--         ,o.c_rate          
--         ,0::numeric units           
--         ,(c.price_choice * o.units - value_usd)/o.r_rate value_loc       
--         ,c.price_choice * o.units - value_usd value_usd       
--         ,0::numeric cost_loc        
--         ,0::numeric cost_usd        
--         ,o.calc_status     
--         ,o.flag            
--         ,o.order_date      
--         ,o.order_month     
--         ,o.order_season    
--         ,o.request_date    
--         ,o.request_month   
--         ,o.request_season  
--         ,o.ship_date       
--         ,o.ship_month      
--         ,o.ship_season     
--         ,o.version         
--         ,'Pricing' iter            
--         ,logload.id logid
--         ,logload.doc->>'tag' tag
--         ,logload.doc->>'message' "comment"
--         ,logload.doc->>'type' module
--         ,0::NUMERIC pounds          
--     FROM 
--         rlarp.osm_pool o
--         CROSS JOIN logload
--         INNER JOIN choose c ON 
--             c.billto_group = o.billto_group
--             AND c.shipto_group = o.shipto_group
--             AND substring(c.dsm,1,5) = substring(o.dsm,1,5)
--             AND c.part = o.part
--             AND c.order_date = o.order_date
--     WHERE 
--         o.order_season = 2026
-- )
-- SELECT billto_group, shipto_group, substring(dsm,1,5), part, order_date, count(*) over (PARTITION BY billto_group, shipto_group, substring(dsm,1,5), part, order_date) cnt
-- FROM 
--     choose 
-- GROUP BY
--     billto_group, shipto_group, substring(dsm,1,5), part, order_date
-- select shipto_group, sum(value_usd) from delta_row group by shipto_group
