WITH
req AS  (SELECT $$app_req$$::jsonb j)
,target AS (
    SELECT
        (req.j->>'app_vincr')::numeric vincr   --volume
        ,(req.j->>'app_pincr')::numeric pincr  --price
    FROM
        req
)
-----this block is supposed to test for new products that might not be in baseline etc-------
,test AS (
    SELECT
        sum(app_units) FILTER (WHERE app_iter <> 'ACTUALS') total
        ,sum(app_units) FILTER (WHERE app_iter = 'baseline') base
    FROM
        tpsv.dcard o 
    WHERE
        app_where
)
,ilog AS (
    INSERT INTO
        fc.log (doc)
    SELECT
        req.j 
    FROM
        req
    RETURNING *
)
------need to group basemix and forego any detail iterations
,basemix AS (
SELECT
    o.id
    ,o.logid
    ,o."Trans. Date"
    ,o."Post Date"
    ,o."Description"
    ,sum(o."Amount") AS "Amount"
    ,o."Category"
    ,o."Party"
    ,o."Reason"
    ,'app_forecast_name' AS app_version
    ,'scale' AS app_iter
    ,0::bigint AS app_logid
    ,sum(o.app_units) AS app_units
FROM
    tpsv.dcard o 
WHERE
    app_where
GROUP BY
    o.id
    ,o.logid
    ,o."Trans. Date"
    ,o."Post Date"
    ,o."Description"
    ,o."Category"
    ,o."Party"
    ,o."Reason"
),
vscale AS (
    SELECT
        (SELECT vincr FROM target) AS target_increment
        ,sum(app_units) AS units
        ,CASE WHEN sum(app_units) = 0 THEN 0 ELSE (SELECT vincr FROM target)/sum(app_units) END AS factor
    FROM
        basemix
)
,volume_only AS (
SELECT
    o.id
    ,o.logid
    ,o."Trans. Date"
    ,o."Post Date"
    ,o."Description"
    ,o."Amount" * vscale.factor AS "Amount"
    ,o."Category"
    ,o."Party"
    ,o."Reason"
    ,'app_forecast_name' AS app_version
    ,'scale volume' AS app_iter
    ,(SELECT id FROM ilog) AS app_logid
    ,o.app_units * vscale.factor AS app_units
FROM
    basemix o
    CROSS JOIN vscale
WHERE
    vscale.factor <> 0
)
,volume AS (
    SELECT * FROM volume_only
    UNION ALL
    SELECT * FROM baseline WHERE (SELECT COUNT(*) FROM volume_only) = 0
)
,pscale AS (
    ----what if the selection has several value columns, which one to use?-----
    SELECT
        (SELECT pincr FROM target) AS target_increment
        ,sum("Amount") AS value
        ,CASE WHEN (SELECT sum("Amount") FROM volume) = 0 THEN 0 ELSE (SELECT pincr FROM target)/sum("Amount") FROM volume END factor
    FROM
        volume
)
,pricing AS (
SELECT
    o.id
    ,o.logid
    ,o."Trans. Date"
    ,o."Post Date"
    ,o."Description"
    ,(CASE WHEN pscale.factor = 0 THEN o.app_units * pscale.mod_price ELSE o."Amount" * pscale.factor END)::numeric AS "Amount"
    ,o."Category"
    ,o."Party"
    ,o."Reason"
    ,'app_forecast_name' AS app_version
    ,'scale volume' AS app_iter
    ,(SELECT id FROM ilog) AS app_logid
    ,0::numeric AS app_units
FROM
    volume o
    CROSS JOIN pscale
WHERE
    pscale.factor <> 0 or pscale.mod_price <> 0
)
INSERT INTO
    tpsv.dcard
SELECT 
    * 
FROM 
    volume 
UNION ALL 
SELECT 
    * 
FROM 
    pricing

