-- CREATE TABLE IF NOT EXISTS pricequote.price_queue (
-- 	id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY
--     ,bill    TEXT    
--     ,ship    TEXT    
--     ,part    TEXT    
--     ,stlc    TEXT    
--     ,v1ds    TEXT    
--     ,vol     NUMERIC 
--     ,chan    TEXT
--     ,tier    TEXT
--     ,pltq	 NUMERIC
--     ,price   NUMERIC 
--     ,expl    JSONB   
-- );

DELETE FROM pricequote.price_queue;

INSERT INTO pricequote.price_queue (bill, ship, part, stlc, v1ds, vol) SELECT 'GRIF0001','GRIF0001','XNS0T1G3G18B096','XNS0T1G3','v1:L..PLT..',9600;

SELECT * FROM pricequote.process_queue()

-- --------------------------------------------------------------------------------
-- ---------------------set channel, tier, & pallet quantitiy----------------------
-- --------------------------------------------------------------------------------
-- UPDATE 
--     pricequote.price_queue s
-- SET
--     chan = cr.chan,
--     tier = cr.tier,
--     pltq = cr.mpck
-- FROM (
--     SELECT 
--          q.bill
--         ,q.ship
-- 		,q.part
-- 		,i.mpck
--         ,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(SUBSTR(LTRIM(SC.BVADR7)||SC.BVNAME,1,30)) = RTRIM(SUBSTR(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 AS chan
-- 		,CASE substring(bc.cclass,2,3) 
-- 			WHEN 'DIR' THEN bc.tier
-- 		    -------------some orders do not have a ship-to---------------
-- 			ELSE COALESCE(sc.tier,bc.tier)
-- 		END AS tier
--     FROM 
--         pricequote.price_queue q
--         LEFT OUTER JOIN rlarp.cust bc ON 
--             bc.code = q.bill 
--         LEFT OUTER JOIN rlarp.cust sc ON 
--             sc.code = q.ship
--         LEFT OUTER JOIN "CMS.CUSLG".itemm i ON 
--         	i.item = q.part
-- ) cr
-- WHERE
--     cr.bill = s.bill
--     AND COALESCE(cr.ship, '') = COALESCE(s.ship, '');
--
-- UPDATE 
-- 	pricequote.price_queue q
-- SET
--     price = tp.price
--     ,expl = jsonb_build_object(
--         'source', 'target price',
--         'calculated_pallets', FLOOR(q.vol / NULLIF(q.pltq, 0))::INT,
--         'exact_pallets', ROUND(q.vol / NULLIF(q.pltq, 0),5),
--         'volume range',tp.vol
--     )
-- FROM 
-- 	pricequote.target_prices tp
-- WHERE
--     q.stlc = tp.stlc
--     AND q.v1ds = tp.ds
--     AND q.chan = tp.chan
--     AND q.tier = tp.tier
--     AND tp.vol @> FLOOR(q.vol/q.pltq)::INT;
--
-- SELECT * FROM pricequote.price_queue

