-- WITH
-- newc AS (
CREATE TABLE rlarp.orphans AS (
    SELECT renamed, rerep, pounds::numeric pounds FROM (VALUES
('MARTIN''S NURSERY INC','10049 - STEVEN STUPPIELLO','160000'),
('BRENTANOS TREE FARM','30053 - SKYE SAWYER','125000'),
('QUALITREE PROPAGATORS','40042 - TOM MORRIS','122256'),
('HSU''S','13027 - STEVE RUSTEBERG','98054'),
('LANCASTER FARM','10040 - RYAN CHITWOOD','88733'),
('NATURALLY BEAUTIFUL PLANT PROD','10043 - CHERISSE GILSTROP','66876'),
('REARDON NURSERY','30053 - SKYE SAWYER','54000'),
('VAN BELLE NURSERY','40042 - TOM MORRIS','52690'),
('DEVAN GREENHOUSES','40042 - TOM MORRIS','50554'),
('STEWARTS GREENHOUSE','10046 - DUSTIN KUYKENDOLL 2','46585'),
('DESERT FOREST NURSERY','30035 - RODNEY RIOS','45292'),
('LINNAEA NURSERIES LTD','40042 - TOM MORRIS','40617'),
('MILLERS BLUE MOUNTAIN GHSE','10043 - CHERISSE GILSTROP','38029'),
('BRIGGS NURSERY','30053 - SKYE SAWYER','38000'),
('VAN KLAVEREN''S NURSERY LLC','30053 - SKYE SAWYER','36000'),
('BLUE HERON FARM','30053 - SKYE SAWYER','36000'),
('GROWERS NURSERY SUPPLY INC','30053 - SKYE SAWYER','33683'),
('DESERT HORIZON NURSERY','30035 - RODNEY RIOS','25834'),
('MEADOWLARK ORNAMENTALS LLC','12028 - JACOB WILKINSON','25350'),
('PHELPS NURSERY','10048 - PHILIP BIEDENBACH','22000'),
('VARGAS NURSERY','10041 - TAMARA RISKEN','21800'),
('MEDFORD NURSERY INC','10043 - CHERISSE GILSTROP','21600'),
('SUNLAND NURSERY','12028 - JACOB WILKINSON','19315'),
('TOM DE SANTO GREENHOUSES','30053 - SKYE SAWYER','18000'),
('LIMA GREENHOUSES','30053 - SKYE SAWYER','18000'),
('JACOBSONS GREENHOUSE','30053 - SKYE SAWYER','18000'),
('GOLD HILL NURSERY','30053 - SKYE SAWYER','18000'),
('ALASKA MILL AND FEED','30053 - SKYE SAWYER','18000'),
('HUIZENGA BRO GREENHOUSE INC','10035 - MATTHEW STAAL','17100'),
('SCHROCK SALES','10048 - PHILIP BIEDENBACH','16146'),
('HEIRLOOM ROSES','30053 - SKYE SAWYER','16000'),
('ASHCOMBE FARM & GREENHOUSE','10048 - PHILIP BIEDENBACH','16000'),
('SUNRISE GREENHOUSES','40039 - DAVE BODO','15770'),
('ALPHA NURSERY','30053 - SKYE SAWYER','15683'),
('BREEZY HILL NURSERY','13027 - STEVE RUSTEBERG','15555'),
('SALGACA CORPORATION','10046 - DUSTIN KUYKENDOLL 2','15268'),
('EDGEWOOD GREENHOUSE','13027 - STEVE RUSTEBERG','15000'),
('DGI','10035 - MATTHEW STAAL','15000'),
('DAYNABROOK GREENHOUSES','10048 - PHILIP BIEDENBACH','15000'),
('RAZBUTON INC','10039 - DUSTIN KUYKENDOLL','14710'),
('GOLD COAST FARMS LLC','30035 - RODNEY RIOS','14560'),
('A&W ANNUALS','10039 - DUSTIN KUYKENDOLL','13866'),
('MESQUITE VALLEY GROWERS','30035 - RODNEY RIOS','13440'),
('MULTIFAB, INC','30053 - SKYE SAWYER','13050'),
('CAAN FLORAL CO INC','13027 - STEVE RUSTEBERG','12661'),
('WEAKLAND GREENHOUSES','12028 - JACOB WILKINSON','11604'),
('BEAVER BARK LTD','30053 - SKYE SAWYER','11107'),
('HONEYMOON ACRES','13027 - STEVE RUSTEBERG','10500'),
('HENRY WHALEN AND SONS GHSE','10043 - CHERISSE GILSTROP','10063'),
('HILLEN NURSERY LTD','40039 - DAVE BODO','10000'),
('HIGHLAND FARMS','12028 - JACOB WILKINSON','10000'),
('WALNUT GROVE NURSERY','40042 - TOM MORRIS','9712'),
('KATOS NURSERY','40042 - TOM MORRIS','9634'),
('BAYVIEW GREENHOUSES','40039 - DAVE BODO','9631'),
('CARPINITO BROTHERS INC','30053 - SKYE SAWYER','9000'),
('AVA NURSERY','10049 - STEVEN STUPPIELLO','8924'),
('BELLE INVESTMENTS','10039 - DUSTIN KUYKENDOLL','8647'),
('SUN NURSERIES','10043 - CHERISSE GILSTROP','8334'),
('GEORGE''S PLANT FARM','10040 - RYAN CHITWOOD','8000'),
('D''ADDIO FAMILY NURSERY','10048 - PHILIP BIEDENBACH','8000'),
('MR GREENJEANS FARM MARKET','10043 - CHERISSE GILSTROP','7817'),
('BOEKESTYN GREENHOUSES LTD','40039 - DAVE BODO','7639'),
('FISHER FARMS','30053 - SKYE SAWYER','7238'),
('PINE VIEW FARM','10048 - PHILIP BIEDENBACH','7000'),
('GILSON FAMILY ENTERPRISE','10042 - JEREMY RHAULT','6763'),
('STARLING NURSERY','10049 - STEVEN STUPPIELLO','6400'),
('MCCALLS NURSERIES INC','30054 - JASON MOTTIN','6000'),
('I & G FARM INC','10043 - CHERISSE GILSTROP','5715'),
('THOMAS BECNEL','10041 - TAMARA RISKEN','5000'),
('MAYS GREENHOUSE','10048 - PHILIP BIEDENBACH','5000'),
('DRY LAND NATIVE GRASSES','10041 - TAMARA RISKEN','5000'),
('CAPOGNA FLOWERS','40039 - DAVE BODO','5000'),
('ANDYS GARDENS','10048 - PHILIP BIEDENBACH','5000'),
('BOBBY MURRAY FARMS','10041 - TAMARA RISKEN','4940'),
('J FRANK GAUDET TREE NURSERY','40040 - TINA PETTIGREW','4909'),
('NORTHWEST PLANT COMPANY','30053 - SKYE SAWYER','4566'),
('KATYDID GREENHOUSE','10040 - RYAN CHITWOOD','4122'),
('MCCALLISTERS LNDSCP SUPPLY','10041 - TAMARA RISKEN','3920'),
('SHANER AVENUE NURSERY','10035 - MATTHEW STAAL','3500'),
('BEAUTIFUL LAND PRODUCTS','13027 - STEVE RUSTEBERG','3368'),
('PARSLEYS PLANT FARM','10041 - TAMARA RISKEN','3000'),
('ALASKA GDN & PET SUPPLY RET','30053 - SKYE SAWYER','2380'),
('MARCUMS NURSERY','10041 - TAMARA RISKEN','2338'),
('UNITED CENTRAL ORCHIDS','13027 - STEVE RUSTEBERG','2298'),
('JEFF PARSLEY PLANT FARM','10041 - TAMARA RISKEN','2000'),
('BEDROCK NURSERY','10041 - TAMARA RISKEN','1955'),
('WAYFAIR LLC','90015 - ANN MARIE FOX','1800'),
('VM INNOVATIONS-NE','90015 - ANN MARIE FOX','1730'),
('DOAN''S NURSERY INC.','10041 - TAMARA RISKEN','1500'),
('KLEIN''S FLORAL AND GREENHOUSE','13027 - STEVE RUSTEBERG','1207'),
('DAHLINGHAUS VENTURES LLC','10048 - PHILIP BIEDENBACH','1051'),
('YC NURSERIES INC','10041 - TAMARA RISKEN','1000'),
('TEJANA NURSERY','10041 - TAMARA RISKEN','1000'),
('TREESEARCH FARMS INC','10041 - TAMARA RISKEN','1000'),
('THOMAS BECNEL CITRUS','10041 - TAMARA RISKEN','1000'),
('SUAREZ PLANT FARM','10041 - TAMARA RISKEN','1000'),
('SMITH NURSERY','10041 - TAMARA RISKEN','1000'),
('OSO GROWERS INC.','10041 - TAMARA RISKEN','1000'),
('LENO PLANT FARM','10041 - TAMARA RISKEN','1000'),
('GIESEL''S GREENHOUSE','10041 - TAMARA RISKEN','1000'),
('CHRIS DOYLE PLANT BROKERAGE','10041 - TAMARA RISKEN','1000')
) x(renamed,rerep,pounds)
) WITH DATA
-- )
-- ,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)
-- )
-- ,profile AS (
--     SELECT * FROM rlarp.osm WHERE shipgrp IN (select distinct renamed FROM newc ) AND oseas >= 2018
-- )
-- -- SELECT * FROM profile
-- ,checkc AS (
-- SELECT shipgrp, min(oseas) oseas FROM profile GROUP BY shipgrp
-- )
-- -- select * from checkc
-- -- SELECT cust, sum(fb_qty) FROM newc LEFT OUTER JOIN profile ON shipgrp = cust GROUP by cust
----grouped prices-------------
,npgrp AS (
	SELECT
		o.bill_dba 
		,o.ship_dba
        ,o.bill_cust
        ,o.ship_cust
        ,o.promo
        ,o.terms
        ,o.dsm
		,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
	 	INNER JOIN "CMS.CUSLG".itemm i ON 
	 		i.item = o.part
        INNER JOIN checkc c ON 
            c.shipgrp = o.customer
            AND c.oseas = o.oseas
	WHERE 
		VERSION = 'Actual' 
		AND o.oseas >= 2018
		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 customer in (select distinct renamed FROM newc )
	GROUP BY 
		o.bill_dba 
		,o.ship_dba
        ,o.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
)
----sequenced for most recent price------------
,nseq AS (
	SELECT 
		 bill_dba 
		,ship_dba
		,part
		,odate
		,qtyord
		,lbs
		,pltq
		,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 
		npgrp
)
-- SELECT * FROM seq WHERE rn = 1
,ngrp AS (
    SELECT 
        sg.fspr
        ,i.dplt
        ,o.promo
        ,o.terms
        ,o.bill_cust
        ,o.ship_cust
        ,o.dsm
        ,o.dsm
        ,null:: director
        ,o.account
        ,o.shipgrp
        ,o.chan
        ,o.chansub
        ,null::channel_retail
        ,i.partgroup
        ,i.pricegroup
        ,o.part
        ,o.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
        ,o.fs_line
        ,o.r_currency
        ,rx.rate r_rate        
        ,pl.curr c_currency    
        ,rx.rate r_rate        
        ,pl.curr c_currency    
        ,cx.rate c_rate        
        ,ROUND(sum(fb_qty * lbs),5) lbs
        ,ROUND(sum(fb_qty),2) qty 
        ,ROUND(sum(fb_val_loc * r_rate),2) sales_usd
        ,ROUND(sum(fb_cst_loc_cur * c_rate),2) cost_curstd_usd
        ,'CLOSED' calc_status
        ,'SHIPMENT' flag
        ,o.odate
        ,o.oseas
        ,o.odate
        ,og.sortmo omon
        ,o.sseas
        ,o.sdate
        ,sg.sortmo smon
        -- ,o.calc_status
    FROM 
        profile o
        LEFT OUTER JOIN rlarp.gld og ON 
            o.odate BETWEEN og.sdat and og.edat
        LEFT OUTER JOIN rlarp.gld sg ON
            o.sdate BETWEEN sg.sdat and sg.edat
        LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
            i.item = o.part
        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'
    WHERE
        true
        -- iter IN ('actuals','actuals_plug','copy')
        AND fs_line = '41010' 
        AND substring(o.glec,1,1) <= '2'
        AND o.calc_status <> 'CANCELED'
        AND o.sseas IS NOT NULL
    GROUP BY 
        o.account
        ,o.shipgrp
        ,o.chan
        ,o.dsm
        ,i.partgroup
        ,i.pricegroup
        ,o.part
        ,o.glec
        ,o.oseas
        ,o.odate 
        ,og.sortmo
        ,o.sseas
        ,o.sdate
        ,sg.sortmo
        -- ,o.calc_status
)
-- SELECT * FROM ngrp
,nguid AS (
    SELECT
         grp.account
        ,grp.shipgrp
        ,grp.chan
        ,r.repp dsm
        ,r.director
        ,grp.shipgrp||'.'||r.repp lu
        -- ,grp.partgroup
        -- ,grp.pricegroup
        ,grp.part
        -- ,grp.glec
        ,2026  oseas
        ,grp.omon 
        ,grp.odate 
        ,(2026- grp.oseas) + grp.sseas sseas
        ,grp.smon
        ,grp.sdate
        ,grp.lbs
        ,grp.qty 
        ,grp.sales_usd
        ,CASE WHEN round(grp.sales_usd/grp.qty,5) = 0 THEN null ELSE round(grp.sales_usd/grp.qty,5) END hist_price
        ,grp.cost_curstd_usd
        ,sum(grp.lbs) OVER (PARTITION BY shipgrp,  dsm) shiplbs
        ,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.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 grp.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
    FROM 
        ngrp grp
        LEFT OUTER JOIN nseq seq ON 
            seq.ship_dba = grp.shipgrp
            AND seq.bill_dba = grp.account
            AND seq.part = grp.part
            AND seq.rn = 1
        LEFT OUTER JOIN rlarp.repc r ON 
            r.rcode = grp.dsm
)
select * from nguid

-- ,orphans AS (
--     SELECT
--          account
--         ,shipgrp
--         ,chan
--         ,dsm
--         ,director
--         ,lu
--         --,partgroup
--         --,pricegroup
--         ,part
--         -- ,glec
--         ,oseas
--         ,omon
--         -- ,odate 
--         ,sseas
--         ,smon
--         -- ,sdate
--         ,lbs
--         ,qty 
--         ,sales_usd
--         ,hist_price
--         ,cost_curstd_usd
--         ,shiplbs
--         ,floor
--         ,ceiling
--         ,uselimits
--         ,price 
--         ,avgprice
--         ,pltq
--         ,guid
--         ,least(hist_price, price, avgprice) lowest_last
--         ,least(hist_price, price, avgprice, floor) lowest_floor
--     FROM 
--         nguid
-- )
-- SELECT * FROM orphans
