Fix the pscale adjustment factor when adding month data.

Two things were wrong with this code:
1. The exchange rate conversion was backward. Since we work in USD, I
   removed the conversion and used value_usd instead.
2. The calculation of pscale.factor was incorrect. If the old value is
   1000, and we need to get to 1020, the record to be inserted must have
   a value of 20, thus the value for factor needs to be:
   (1020 - 1000) / 1000  =  (1020 / 1000) - 1  =  0.02
   0.02 * 1000  =  20, which is inserted in the new record.

   The subtraction was missing before, which of course caused WAY wrong
   numbers that should have been caught a long time ago. It was doing:
   1020 / 1000  =  1.02
   1.02 * 1000 = 1020 was inserted, doubling the intended adjustment.
This commit is contained in:
PhilRunninger 2024-03-19 16:24:04 -04:00
parent aa13911c02
commit c7789f868c

View File

@ -399,17 +399,17 @@ WHERE
,pscale AS (
SELECT
CASE
WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 AND (SELECT sum(units) FROM volume) = 0 THEN 'both'
WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 THEN 'cost'
WHEN (SELECT coalesce(sum(value_usd),0) FROM volume) = 0 AND (SELECT sum(units) FROM volume) = 0 THEN 'both'
WHEN (SELECT coalesce(sum(value_usd),0) FROM volume) = 0 THEN 'value'
ELSE 'other'
END zero_values
,CASE
WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 AND (SELECT coalesce(sum(units),0) FROM volume) = 0 -- Split pincr evenly between rows.
WHEN (SELECT coalesce(sum(value_usd),0) FROM volume) = 0 AND (SELECT coalesce(sum(units),0) FROM volume) = 0 -- Split pincr evenly between rows.
THEN (SELECT pincr::numeric FROM target) / (SELECT nullif(count(*),0) FROM volume)
WHEN (SELECT coalesce(sum(value_loc),0) FROM volume) = 0 -- Get a per-unit pincr value
WHEN (SELECT coalesce(sum(value_usd),0) FROM volume) = 0 -- Get a per-unit pincr value
THEN (SELECT pincr::numeric FROM target) / (SELECT nullif(sum(units),0) FROM volume)
ELSE -- Find percent change for existing value_loc
(SELECT pincr::numeric FROM target) / (SELECT nullif(sum(value_loc * r_rate),0) FROM volume)
(SELECT pincr::numeric FROM target) / (SELECT nullif(sum(value_usd),0) FROM volume) - 1
END factor
)
-- select 'pscale', * from pscale
@ -448,12 +448,12 @@ SELECT
,0::numeric units
,round(CASE p.zero_values
WHEN 'both' THEN p.factor / b.r_rate
WHEN 'cost' THEN b.units * p.factor / b.r_rate
WHEN 'value' THEN b.units * p.factor / b.r_rate
WHEN 'other' THEN b.value_loc * p.factor
END, 2) AS value_loc
,round(CASE p.zero_values
WHEN 'both' THEN p.factor
WHEN 'cost' THEN b.units * p.factor
WHEN 'value' THEN b.units * p.factor
WHEN 'other' THEN b.value_usd * p.factor
END, 2) AS value_usd
,0::numeric cost_loc
@ -481,7 +481,7 @@ FROM
CROSS JOIN pscale p
CROSS JOIN log
WHERE
p.factor <> 0
abs(p.factor) > 0.00001
)
-- select 'price', * from price UNION ALL SELECT 'volume', * FROM volume
--