-- BEGIN;

--only do this when starting fresh
-- TRUNCATE TABLE rlarp.osm_pool;
-- TRUNCATE TABLE rlarp.osm_log CASCADE;
-- ALTER SEQUENCE rlarp.osm_log_id_seq RESTART 1;
--
--
-- DROP TABLE IF EXISTS rlarp.osm_pool_stage;

-- CREATE TABLE rlarp.osm_pool_stage AS (
WITH
-- ,orphans AS (
--     SELECT 
--          renamed
--         ,rerep
--         ,pounds
--     FROM 
--
-- )
profile AS (
    SELECT * FROM rlarp.osm WHERE shipgrp IN (select distinct renamed FROM rlarp.orphans ) AND oseas >= 2018
)
-- SELECT * FROM profile
,checkc AS (
    SELECT shipgrp, min(oseas) oseas FROM profile GROUP BY shipgrp
)
-- SELECT * FROM checkc
,repc AS (
    SELECT
		LTRIM(RTRIM(C.A9)) RCODE
		,C.A30 REPP
		,COALESCE(Q.DIR,'Other') DIRECTOR
	FROM
		LGDAT.CODE C
		LEFT OUTER JOIN RLARP.QRH Q ON
			Q.QR = LTRIM(RTRIM(C.A9))
	WHERE
		C.A2 = 'MM'
)
--select * from repc
,SEG AS (
    SELECT
        GLEC
        ,SEGM
    FROM
        (
            VALUES
            ('1CU','Sustainable'),
            ('1SU','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)
)
--select * from seg
----------------------------------------------------sales major codes----------------------------------------------------------------------------------------------------------------------------------
-- ,SJ AS (
--     SELECT * FROM LGDAT.MMSL WHERE COALESCE(BSMNCD,'') = ''
-- )
-- --select * from sj
-- ----------------------------------------------------sales minor codes----------------------------------------------------------------------------------------------------------------------------------
-- ,SI AS (
--     SELECT * FROM LGDAT.MMSL WHERE COALESCE(BSMNCD,'') <> ''
-- )
--select * from si
,logload AS (
    INSERT INTO rlarp.osm_log (doc) SELECT jsonb_build_object('user',current_user,'tag','New Cust','type','orphans','stamp',current_timestamp,'source','top level','message','New Customer') RETURNING *
)
--select * from logload 
,loadset AS (
SELECT
    o.fspr
    ,o.plnt
    ,o.promo
    ,o.terms
    ,o.bill_cust||' - '||bc.bvname bill_cust_descr
    ,o.ship_cust||' - '||sc.bvname ship_cust_descr
    ,o.dsm
    ,coalesce(repc.repp,dsm) quota_rep_descr
    ,repc.director
    ,o.account billto_group
    ,o.shipgrp shipto_group
    ,chan
    ,chansub
    ,CASE seg.segm
        --for 1RE coded product
        WHEN 'Retail' THEN
            CASE o.bill_class
                WHEN 'RONL' THEN 'Online' 
                WHEN 'RNAT' THEN 'National' 
                WHEN 'RMAS' THEN 'National' 
                ELSE 
                    ------ ship-to class ---------------------
                    CASE o.chan
                        WHEN 'GDIS' THEN 'Distribution'
                        WHEN 'NDIS' THEN 'Distribution'
                        WHEN 'RDIS' THEN 'Distribution'
                        WHEN 'GDRP' THEN 'Grower'
                        WHEN 'NDRP' THEN 'Grower'
                        WHEN 'RDRP' THEN 'Distribution'
                        WHEN 'GDIR' THEN 'Grower'
                        WHEN 'NDIR' THEN 'Grower'
                        -------this will probably need reviewed--------
                        WHEN 'RDIR' THEN 'Distribution'
                        WHEN 'NDIR' THEN 'Grower'
                        WHEN 'GDIR' THEN 'Grower'
                        ELSE 'Distribution'
                    END
            END
        --for 1SU 1CU coded product
        WHEN 'Sustainable' THEN
            CASE SUBSTRING(o.coltier,1,1)
                --anything with a bio color tier is bio on the channel
                WHEN 'R' THEN 'Bio'
                ELSE    
                    CASE o.glec 
                        --any 1SU that is not bio is fiber
                        WHEN '1SU' THEN 'Fiber'
                        --any 1CU that is not bio is commercial
                        WHEN '1CU' THEN 'Commercial'
                        ELSE o.chan
                    END
            END
        ELSE o.chan
    END chan_retail
    ,part
    ,part||coalesce(' - '||i.descr,'') part_descr
    ,stlcd part_group
    ,brnd branding
    ,o.majg||' - '||i.majgd majg_descr
    ,o.ming||' - '||i.mingd ming_descr
    ,o.majs||' - '||i.majsd majs_descr
    ,o.mins||' - '||i.minsd mins_descr
    ,seg.segm
    ,CASE WHEN o.majg = '610' THEN 'Fiber' ELSE 'Plastic' END substance
    ,fs_line
    ,r_currency
    ,r_rate
    ,c_currency
    ,c_rate
    ,round(fb_qty,2) units
    ,round(fb_val_loc,2) value_loc
    ,round(fb_val_loc * r_rate,2) value_usd
    ,round(fb_qty * i.curstd,2) cost_loc
    ,round(fb_qty * i.curstdus,2) cost_usd
    ,sum(fb_qty * i.nwht * case i.nwun WHEN 'KG' THEN 2.2046 ELSE 1 END) OVER (partition by o.shipgrp)  cust_lbs
    ,fb_qty * i.nwht * case i.nwun WHEN 'KG' THEN 2.2046 ELSE 1 END                                     line_lbs
    ,calc_status
    ,flag
    ,(odate + ((2026 - o.oseas)||' years')::interval)::date order_date
    ,to_char(CASE WHEN extract(month FROM o.odate) >= 6 THEN -5 ELSE 7 END + extract(month FROM o.odate),'FM00')||' - '||to_char(o.odate,'TMMon') order_month
    ,2026 order_season
    ,(rdate + ((2026 - o.oseas)||' years')::interval)::date request_date
    ,to_char(CASE WHEN extract(month FROM o.rdate) >= 6 THEN -5 ELSE 7 END + extract(month FROM o.rdate),'FM00')||' - '||to_char(o.rdate,'TMMon') request_month
    ,rseas + (2026 - o.oseas) request_season
    ,(sdate + ((2026 - o.oseas)||' years')::interval)::date ship_date
    ,to_char(CASE WHEN extract(month FROM o.sdate) >= 6 THEN -5 ELSE 7 END + extract(month FROM o.sdate),'FM00')||' - '||to_char(o.sdate,'TMMon') ship_month
    ,sseas + (2026 - o.oseas) ship_season
    ,'b26' version
    ,'fc orphans' iter
    ,logload.id logid
    ,logload.doc->>'tag' tag
    ,logload.doc->>'message' "comment"
    ,logload.doc->>'type' module
    -- ,round(o.fb_qty * o.lbs) pounds
FROM
    checkc p
    INNER JOIN rlarp.osm o ON 
        p.shipgrp = o.shipgrp
        AND p.oseas = o.oseas
    CROSS JOIN logload
    LEFT OUTER JOIN lgdat.cust bc ON
        bc.bvcust = o.bill_cust
    LEFT OUTER JOIN lgdat.cust sc ON
        sc.bvcust = o.ship_cust
    LEFT OUTER JOIN repc ON
        repc.rcode = o.dsm
    /*
    LEFT OUTER JOIN lgdat.majg ON
        bqgrp = o.majg
    LEFT OUTER JOIN lgdat.mmgp ON
        brmgrp = o.ming
        AND BRGRP = o.majg
    LEFT OUTER JOIN si ON
        si.bsmjcd = o.majs
        AND si.bsmncd = o.mins
    LEFT OUTER JOIN sj ON
        sj.bsmjcd = o.majs
    */
    LEFT OUTER JOIN seg ON
        seg.glec = o.glec
    LEFT OUTER JOIN "CMS.CUSLG".itemm i ON
        i.item = o.part
WHERE 
    iter NOT IN ('py carryover','short ship','bad date')
    AND sseas  IS NOT NULL
    AND odate <= sdate
    AND fs_line = '41010'
    AND calc_status <> 'CANCELLED'
)
,scale 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          
    ,round(units           * pounds/cust_lbs,2) units    
    ,round(value_loc       * pounds/cust_lbs,2) value_loc
    ,round(value_usd       * pounds/cust_lbs,2) value_usd
    ,round(cost_loc        * pounds/cust_lbs,2) cost_loc 
    ,round(cost_usd        * pounds/cust_lbs,2) cost_usd 
    ,calc_status     
    ,flag            
    ,order_date      
    ,order_month     
    ,order_season    
    ,request_date    
    ,request_month   
    ,request_season  
    ,ship_date       
    ,ship_month      
    ,ship_season     
    ,version         
    ,iter            
    -- ,cust_lbs
    ,logid           
    ,tag             
    ,comment         
    ,module
    ,round(line_lbs       * pounds/cust_lbs,5) pounds
    -- ,pounds/cust_lbs factor
FROM 
    rlarp.orphans o
    INNER JOIN loadset l ON 
        l.shipto_group = o.renamed
WHERE 
    cust_lbs >= 1000
) 
----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
INSERT INTO rlarp.osm_pool SELECT * FROM scale;
-- select * from scale) WITH DATA;

-- INSERT INTO rlarp.osm_pool SELECT * FROM rlarp.osm_pool_stage;

-- SELECT * FROM loadset WHERE iter NOT IN ('py carryover','short ship','bad date')
-- ) WITH DATA;



--CREATE INDEX osm_qr ON rlarp.osm_pool(quota_rep_descr, bill_cust_descr, ship_cust_descr);
--ALTER TABLE rlarp.osm_pool ADD CONSTRAINT logfk FOREIGN KEY (logid) REFERENCES rlarp.osm_log(id);
--CREATE INDEX osm_pool_logid ON rlarp.osm_pool(logid);
--GRANT ALL ON TABLE rlarp.osm_log TO api;
--GRANT ALL ON TABLE rlarp.osm_pool TO api;

-- COMMIT;
