----primarliy used for retail forcast---
WITH 
targ AS (
    SELECT
        account 
        ,targv::numeric targv
        ,targm::numeric targm
        ,targv::numeric - targm::numeric targc
    FROM (VALUES
        ('THE HOME DEPOT','17000000',0.180869108049054,'3074775'),
        ('L&L NURSERY SUPPLY INC','2350000',0.563253626935247,'1323646'),
        ('WAL-MART','0',0.253163216091017,'0'),
        ('FRED MEYER','2000000',0.428001050124866,'856002'),
        ('AMAZON.COM','1640000',0.628251012584489,'1030332'),
        ('BFG SUPPLY','1500000',0.557715153718382,'836573'),
        ('MENARDS','1638401',0.371183129119907,'608147'),
        ('ARETT SALES','1241808',0.534946705934419,'664301'),
        ('VM INNOVATIONS-NE','1000000',0.550614145444113,'550614'),
        ('CANADIAN TIRE CORP LTD','1000000',7.1071607800234802,'71072'),
        ('ALLIANCE INTERNATIONAL LLC','500000',0.41320498613211,'206602'),
        ('OCEAN STATE JOBBERS','300000',0.519592592494997,'155878'),
        ('GRIFFIN','258240',0.459350079411253,'118623'),
        ('DO IT BEST','297067',0.598819925741005,'177889'),
        ('BWI','249061',0.471267420367251,'117374'),
        ('BRADLEY CALDWELL INC','226211',0.594840340158987,'134560'),
        ('PHILLIPS PET FOOD & SUPPLIES','194414',0.585623594407928,'113853'),
        ('ACE HARDWARE','195043',0.658624729218799,'128460'),
        ('EDDIS WHOLESALE GDN SUPPLIES','156305',0.492445750074503,'76972'),
        ('GARD N WISE','154657',0.538554281692573,'83291'),
        ('FOSTERS INC','154278',0.544753621190595,'84043'),
        ('GARDEN CENTRE GROUP CO-OP','148400',0.536654631402229,'79640'),
        ('TRUE VALUE','125272',0.533535971254213,'66837'),
        ('RONA INC (PICK UP)ACE CANADA','125154',0.392502596997768,'49123'),
        ('HB DAVIS SEED CO','103990',0.584667552206486,'60800'),
        ('BOMGAARS SUPPLY INC.    RETAIL','96550',0.571735536677834,'55201'),
        ('CANAC MARQUIS GRENIER','84336',0.311660052989262,'26284'),
        ('LOWES','82640',0.404702398184799,'33445'),
        ('JENSEN DISTRIBUTION','79189',0.600674562921357,'47567'),
        ('EARL MAY SEED','77321',0.583078139217855,'45084'),
        ('INTERMOUNTAIN FARMERS ASSN','71161',0.363909518632671,'25896'),
        ('PEAVEY INDUSTRIES LP       RET','63755',0.597135536225184,'38070'),
        ('SRC CORPORATION','62610',0.544747977551784,'34107'),
        ('HORIZON DISTRIBUTION INC','52200',0.573814286557659,'29953'),
        ('HALIFAX SEED CO INC','47859',0.488214843600939,'23365'),
        ('JAVIC STEIN GARDEN CENTER  RET','47332',0.630242306115199,'29831'),
        ('TERIS SUPPLY SERVICES','46454',0.47092608297219,'21876'),
        ('LITTLE MOUNTAIN GREENHOUSES','0',0.618549785089707,'0'),
        ('WYATT QUARLES','45961',0.43093386297766,'19806'),
        ('KROGER ACCOUNTING SERVICES','0',0.44059506522642,'0'),
        ('AURORA WHOLESALERS, LLC','39005',0.05,'1950'),
        ('CIMARRON LUMBER CO','41255',0.710738991111474,'29321'),
        ('SKH WHOLESALE DIST','39498',0.557039866089005,'22002'),
        ('GREENHOUSE MEGASTORE','38481',0.576006787390623,'22165'),
        ('MEYER SEED CO.OF BALTIMORE INC','36907',0.575920515687234,'21255'),
        ('GREEN ISLAND DISTRIBUTORS INC.','36335',0.456804427057109,'16598'),
        ('ALASKA GDN & PET SUPPLY RET','34416',0.51350131612571,'17673'),
        ('CY GROWERS SUPPLIES LTD','33516',0.515228915496354,'17268'),
        ('PL ROHRER & BRO INC     RET','32682',0.5728291738311,'18721'),
        ('CISCO COMPANIES (THE)','31294',0.541898179358204,'16958'),
        ('EXACTA SALES','29985',0.566851139029652,'16997'),
        ('CARLIN HORTICULTURAL SUPP','29766',0.602236367122854,'17926'),
        ('LEON KOROL COMPANY','27634',0.743284803218813,'-20540'),
        ('FAMILY TREE NURSERY','26732',0.533201536839096,'14253'),
        ('GREENHOUSE & GARDEN SUPPLY INC','28432',0.569077841320063,'16180'),
        ('MIKES GARDEN CENTER','24804',0.35,'8682'),
        ('HORTMARK','24148',0.590534795378758,'14260'),
        ('FLORIDA HARDWARE COMPANY','22952',0.584540312012481,'13416'),
        ('EARL''S FARM & GARDEN INC','20856',0.560015239964639,'11680'),
        ('MIZE FARM & GARDEN SUPPLY','20317',0.545315931222579,'11079'),
        ('HUMMERT INTERNATIONAL','19214',0.551774005627846,'10602'),
        ('BAYERS GARDEN SHOP','18177',0.618732293603234,'11247'),
        ('FEDERATED CO-OPERATIVES LTD','16347',0.57320462397634,'9370'),
        ('VANDENBERG BULB CO INC','15895',0.536805989854345,'8533'),
        ('RS GROWERS SUPPLY','15676',0.554424403728287,'8691'),
        ('PLANTERS SEED & SPICE      RET','15395',0.553402994429341,'8520'),
        ('UNITED GARDEN CENTER','15303',0.530437452248006,'8117'),
        ('NORTH 40 OUTFITTERS','13975',0.650681606349669,'9093'),
        ('ERVA TOOL & DIE CO','13102',0.77194498381877,'10114'),
        ('NITRO-PHOS FERTILIZERS','12772',0.579101021208437,'7397'),
        ('OTTEN BROS','12390',0.529120693814904,'6556'),
        ('GROSOUTH','12229',0.472902730308864,'5783'),
        ('WAYFAIR LLC','10894',0.629842861478861,'6861'),
        ('PRINCE CORPORATION','10627',0.60961110919305,'6478'),
        ('BLISH-MIZE CO','10502',0.58855406150138,'6181'),
        ('UNITED GARDEN CENTERS      RET','10323',0.569618377072865,'5880'),
        ('KC SCHAEFER SUPPLY','10176',0.556059424402277,'5658'),
        ('LIFOAM INDUSTRIES LLC','9922',0.144817968696581,'1437'),
        ('CARL BREHOB & SON','9909',0.490703914367658,'4862'),
        ('GPF CORPORATION','8497',0.577518582216107,'4907'),
        ('APACHE SEEDS LTD','7524',0.640989162803091,'4823'),
        ('PRO GROWER SUPPLY','7160',0.626847725532073,'4488'),
        ('ALTON GREENHOUSES','6282',0.72757677788011,'4571'),
        ('VG SUPPLY CO INC','6170',0.535115688020424,'3302'),
        ('PATRICK MORIN','5550',0.754110342865499,'4185'),
        ('PROFESSIONAL GARDENER CO','5534',0.683089614852672,'3780'),
        ('PREMIUM HORTICULTURAL SUPPLY','5260',0.561352920789087,'2953'),
        ('SCHROTH WHOLESALE SUPPLY CO.','4886',0.581467907541787,'2841'),
        ('WALDO & ASSOCIATES','4848',0.549115597293131,'2662'),
        ('SERRES STE-ELIE','4554',0.486746530391766,'2217'),
        ('JEAN H HENLE INC         RET','4390',0.59124007783322,'2596'),
        ('GOLDCREST DIST','4203',0.631010290556901,'2652'),
        ('KEN VAN WINGERDEN GREENHOUSES','3934',0.691649231813846,'2721'),
        ('PASTANCH LLC','3558',0.646557455289712,'2300'),
        ('TESSMAN SEED','3490',0.526463930114026,'1837'),
        ('GEMMELLS GARDEN CENTRE INC','3356',0.732614797457948,'2459'),
        ('BELLE INVESTMENTS INC','2969',0.640282280523858,'1901'),
        ('BLUE STAR WHOLESALE','2870',0.460127920377161,'1321'),
        ('GLEN ECHO NURSERIES INC','2856',0.475371840926624,'1358'),
        ('Distribution','2856',0.35,'1000'),
        ('EZ GRO GARDEN','2770',0.35,'970'),
        ('ENVIROGREENERY PLANTS LLC','2759',0.560239996772843,'1546'),
        ('GERTENS GREENHOUSE','2669',0.35,'934'),
        ('KROGER (KRG LLC)','2363',0.454740287124271,'1074'),
        ('CINNABAR VALLEY','1873',0.646249752802887,'1210'),
        ('EDWARDS GREENHOUSE INC','1842',0.639898469505178,'1179'),
        ('DIRECT DISTRIBUTORS INC','1732',0.658284195044688,'1140'),
        ('YODERS PRODUCE','1295',0.39639861227028,'514'),
        ('ABC NURSERY LANDSCAPEMAIN','556',0.548465631971323,'305'),
        ('DUNN SALES & MARKETING, INC.','385',0.510810215763981,'197'),
        ('GARDENERS SUPPLY CO','375',0.700292682926829,'263'),
        ('FARMERS COOP','355',0.378703902613677,'135'),
        ('CROP PROD SERVICES INC','351',0.568089371980676,'199'),
        ('ARNOLDS GREENHOUSES','309',0.803142487392462,'249'),
        ('GEORGE''S FLOWERS','287',0.460093805309734,'132'),
        ('HJS WHOLESALE LTD','162',0.723774463631607,'117'),
        ('HOLMBERG FARMS INC','101',0.711558080808081,'72'),
        ('KINNEY BONDED','93',0.520260909090909,'49'),
        ('IRRIGATION PLUS INC','35',0.608262111104002,'21'),
        ('GLENKIRK ASSOCIATES INC','0',CAST(NULL AS NUMERIC),'0'),
        ('MILITARY PRODUCE GROUP LLC','0',CAST(NULL AS NUMERIC),'0'),
        ('WONDER SOIL','0',CAST(NULL AS NUMERIC),'0'),
        ('CHUCK BECK','0',CAST(NULL AS NUMERIC),'0'),
        ('MENARDS INC STORE 3256     RET','0',CAST(NULL AS NUMERIC),'0'),
        ('GREENSTAR PLANT-MANCHESTER','0',CAST(NULL AS NUMERIC),'0'),
        ('MAIN LINE POTTERY','0',CAST(NULL AS NUMERIC),'0'),
        ('PSR SALES INC','0',CAST(NULL AS NUMERIC),'0'),
        ('CLEVELAND FLORAL PRODUCTS INC','0',CAST(NULL AS NUMERIC),'0'),
        ('RACHEL BOWMAN','0',CAST(NULL AS NUMERIC),'0'),
        ('ENG SVCS & PROD','0',CAST(NULL AS NUMERIC),'0'),
        ('RITCHIE FEED & SEED','0',CAST(NULL AS NUMERIC),'0'),
        ('PARK SEED (DBA JPPA)','0',CAST(NULL AS NUMERIC),'0'),
        ('ART KNAPP','0',CAST(NULL AS NUMERIC),'0'),
        ('VARIETY WHOLESALE (9001)','0',CAST(NULL AS NUMERIC),'0'),
        ('ROY SIEMENS','0',CAST(NULL AS NUMERIC),'0'),
        ('MARC DESROSIERS','0',CAST(NULL AS NUMERIC),'0'),
        ('JIM REGER','0',CAST(NULL AS NUMERIC),'0'),
        ('MARK WILKINSON','0',CAST(NULL AS NUMERIC),'0'),
        ('SAN MARCOS GROWERS','0',CAST(NULL AS NUMERIC),'0'),
        ('GRANBYS GREENHOUSE','0',CAST(NULL AS NUMERIC),'0'),
        ('GIANT TIGERE STORES LIMITED','0',CAST(NULL AS NUMERIC),'0'),
        ('INTEGRITY SALES & DISTRIBUTION','0',CAST(NULL AS NUMERIC),'0'),
        ('GLOECKNER & CO. INC.','0',CAST(NULL AS NUMERIC),'0'),
        ('DORAN MARABLE','0',CAST(NULL AS NUMERIC),'0'),
        ('SEVEN OAKS PLANT SHOP INC','0',CAST(NULL AS NUMERIC),'0'),
        ('BURPEE GARDEN PRODUCTS     RET','0',CAST(NULL AS NUMERIC),'0'),
        ('SHERRILL INC','0',CAST(NULL AS NUMERIC),'0'),
        ('PARKWAY GARDENS','0',CAST(NULL AS NUMERIC),'0'),
        ('GS DISTRIBUTION','0',CAST(NULL AS NUMERIC),'0'),
        ('GALES GARDEN CENTER','0',CAST(NULL AS NUMERIC),'0'),
        ('DAVE BODO','0',CAST(NULL AS NUMERIC),'0'),
        ('FLOWERLAND GARDEN CTR OF CLEVE','0',CAST(NULL AS NUMERIC),'0'),
        ('STACK-A-POTS','0',CAST(NULL AS NUMERIC),'0'),
        ('BEAUTIFUL LAND PRODUCTS','0',CAST(NULL AS NUMERIC),'0'),
        ('STRADERS','0',CAST(NULL AS NUMERIC),'0'),
        ('WESTLAND GREENHOUSES','0',CAST(NULL AS NUMERIC),'0'),
        ('SUNNYSIDE GREENHOUSES LTD. RET','0',CAST(NULL AS NUMERIC),'0'),
        ('DM COLOR EXPRESS','0',CAST(NULL AS NUMERIC),'0'),
        ('TERIS SVSC D''''APPROVISIONNEMNT','0',CAST(NULL AS NUMERIC),'0'),
        ('YONAS GREENHOUSES','0',CAST(NULL AS NUMERIC),'0'),
        ('FLORALIES JOUVENCE','0',CAST(NULL AS NUMERIC),'0'),
        ('ALECIA LATINI','0',CAST(NULL AS NUMERIC),'0'),
        ('AL PAR PEAT CO','0',CAST(NULL AS NUMERIC),'0'),
        ('IVAN VANDERDEEN','0',CAST(NULL AS NUMERIC),'0'),
        ('TIDBURY CREEK FARMS','0',CAST(NULL AS NUMERIC),'0'),
        ('AGRO PRODUCTS LIMITED','0',CAST(NULL AS NUMERIC),'0'),
        ('ALDI','0',CAST(NULL AS NUMERIC),'0'),
        ('MISC ACCT -        (US )','0',CAST(NULL AS NUMERIC),'0'),
        ('TIMBERS MARKETING LLC','0',CAST(NULL AS NUMERIC),'0'),
        ('ALLEN STERLING AND LOTHROP','0',CAST(NULL AS NUMERIC),'0'),
        ('TINA PETTIGREW','0',CAST(NULL AS NUMERIC),'0'),
        ('TONY LANDINO','0',CAST(NULL AS NUMERIC),'0'),
        ('TRICIA PRICE','0',CAST(NULL AS NUMERIC),'0'),
        ('PEAK DISTRIBUTION LLC','0',CAST(NULL AS NUMERIC),'0'),
        ('DILLON SEED & SUPPLY','0',CAST(NULL AS NUMERIC),'0'),
        ('MENARDS INC STORE 3510     RET','0',CAST(NULL AS NUMERIC),'0'),
        ('PLANT BEST','0',CAST(NULL AS NUMERIC),'0'),
        ('DENVER WHOLESALE FLORISTS CO','0',CAST(NULL AS NUMERIC),'0'),
        ('TSC STORES LIMITED','0',CAST(NULL AS NUMERIC),'0'),
        ('CENTRAL GARDEN & PET','0',CAST(NULL AS NUMERIC),'0'),
        ('ESERRO','0',CAST(NULL AS NUMERIC),'0'),
        ('AMA PLASTICS','0',CAST(NULL AS NUMERIC),'0'),
        ('LITTLE MOUNTAIN GREENHOUSES U','0',CAST(NULL AS NUMERIC),'0'),
        ('PATAPSCO VALLEY SALES','0',CAST(NULL AS NUMERIC),'0'),
        ('UNITED HARDWARE','0',CAST(NULL AS NUMERIC),'0'),
        ('COLOUR PARADISE GRHS LTD','0',CAST(NULL AS NUMERIC),'0'),
        ('GARDEN RIDGE CORP','0',CAST(NULL AS NUMERIC),'0'),
        ('VARIETY DISTRIBUTORS INC','0',CAST(NULL AS NUMERIC),'0'),
        ('BLUE WATER BALTIMORE','0',CAST(NULL AS NUMERIC),'0'),
        ('LEE VALLEY TOOLS','0',CAST(NULL AS NUMERIC),'0')
    ) x(account,targv,marginp,targm)
)
,factor AS (
SELECT
    account
    ,targv
    ,targm
    ,targc
    ,sum(value_usd) value_usd
    ,sum(units) units
    ,sum(cost_usd) cost_usd
    ,round(CASE WHEN sum(value_usd) = 0 THEN 0 ELSE targv::numeric/sum(value_usd) END,5) vfactor
    ,round(CASE WHEN sum(cost_usd) = 0 THEN 0 ELSE targc::numeric/sum(cost_usd) END,5) cfactor
FROM
    targ t
    LEFT OUTER JOIN rlarp.osm_pool o ON
        o.billto_group = t.account
        AND o.segm = 'Retail'
        AND o.order_season = 2022
GROUP BY
    account
    ,targv
    ,targm
    ,targc
)
--SELECT * FROM agg_curr
----------------create a log entry--------------------
--,log AS (
--    INSERT INTO
--           rlarp.osm_log(doc)
--    SELECT 
--        $${
--            "message":"adjust select retail customers to targets sales and margin",
--            "tag":"retail",
--            "type":"build" 
--        }$$::jsonb doc 
--    RETURNING *
--)
-------build adjustment rows collapsed for all iterations----------
,dv AS (
    SELECT
         o.fspr
        ,o.plnt          ---master data 
        ,o.promo          --history date mix
        ,o.terms
        ,o.bill_cust_descr          --history cust mix
        ,o.ship_cust_descr          --history cust mix
        ,o.dsm
        ,o.quota_rep_descr          --master data 
        ,o.director
        ,o.billto_group          --master data 
        ,o.shipto_group
        ,o.chan          --master data 
        ,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          --master data 
        ,o.r_currency          --history cust mix
        ,o.r_rate          --master data 
        ,o.c_currency          --master data 
        ,o.c_rate          --master data 
        ,round(sum(o.units*s.cfactor      - o.units     ),2) units
        ,round(sum(o.value_loc*s.vfactor  - o.value_loc ),2) value_loc
        ,round(sum(o.value_usd*s.vfactor  - o.value_usd ),2) value_usd
        ,round(sum(o.cost_loc*s.cfactor   - o.cost_loc  ),2) cost_loc
        ,round(sum(o.cost_usd*s.cfactor   - o.cost_usd  ),2) cost_usd
        ,o.calc_status          --0 
        ,o.flag          --0 
        ,o.order_date          --history date mix
        ,o.order_month
        ,o.order_season
        ,o.request_date          --history date mix
        ,o.request_month
        ,o.request_season
        ,o.ship_date          --history date mix
        ,o.ship_month
        ,o.ship_season
        ,'b22' aS version
        ,'upload volume' iter
        --,log.id
        --,coalescE(log.doc->>'tag','') "tag"
        --,log.doc->>'message' "comment"
        --,log.doc->>'type' module
    FROM
        rlarp.osm_pool o
        INNER JOIN factor s ON
            s.account = o.billto_group
        --cross joIN log
    WHERE
        order_season = 2022
        AND segm = 'Retail'
    GROUP BY
         o.fspr
        ,o.plnt          ---master data 
        ,o.promo          --history date mix
        ,o.terms
        ,o.bill_cust_descr          --history cust mix
        ,o.ship_cust_descr          --history cust mix
        ,o.dsm
        ,o.quota_rep_descr          --master data 
        ,o.director
        ,o.billto_group          --master data 
        ,o.shipto_group
        ,o.chan          --master data 
        ,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          --master data 
        ,o.r_currency          --history cust mix
        ,o.r_rate          --master data 
        ,o.c_currency          --master data 
        ,o.c_rate          --master data 
        ,o.calc_status          --0 
        ,o.flag          --0 
        ,o.order_date          --history date mix
        ,o.order_month
        ,o.order_season
        ,o.request_date          --history date mix
        ,o.request_month
        ,o.request_season
        ,o.ship_date          --history date mix
        ,o.ship_month
        ,o.ship_season
        --,log.id
        --,coalescE(log.doc->>'tag','') "tag"
        --,log.doc->>'message' "comment"
        --,log.doc->>'type' module
)
SELECT
    billto_group
    ,sum(value_usd) val
    ,sum(cost_usd) AS cost
    ,sum(units) units
FROM
    dv
GROUP BY
    billto_group
