Import/calculations improvements
This commit is contained in:
@@ -76,7 +76,9 @@ $function$;
|
||||
|
||||
-- =============================================================================
|
||||
-- get_weighted_avg_cost: Weighted average cost from receivings up to a given date.
|
||||
-- Uses all non-canceled receivings (no row limit) weighted by quantity.
|
||||
-- Prefers receivings from the 365 days before p_date so decade-old costs don't
|
||||
-- weigh equally with recent ones; falls back to the lifetime average when the
|
||||
-- product had no receivings in that window.
|
||||
-- =============================================================================
|
||||
CREATE OR REPLACE FUNCTION public.get_weighted_avg_cost(
|
||||
p_pid bigint,
|
||||
@@ -97,8 +99,21 @@ BEGIN
|
||||
FROM receivings
|
||||
WHERE pid = p_pid
|
||||
AND received_date <= p_date
|
||||
AND received_date > p_date - INTERVAL '365 days'
|
||||
AND status != 'canceled';
|
||||
|
||||
IF weighted_cost IS NULL THEN
|
||||
SELECT
|
||||
CASE
|
||||
WHEN SUM(qty_each) > 0 THEN SUM(cost_each * qty_each) / SUM(qty_each)
|
||||
ELSE NULL
|
||||
END INTO weighted_cost
|
||||
FROM receivings
|
||||
WHERE pid = p_pid
|
||||
AND received_date <= p_date
|
||||
AND status != 'canceled';
|
||||
END IF;
|
||||
|
||||
RETURN weighted_cost;
|
||||
END;
|
||||
$function$;
|
||||
|
||||
Reference in New Issue
Block a user