Redo analytics page

This commit is contained in:
2026-02-07 13:44:51 -05:00
parent 8044771301
commit 9b2f9016f6
18 changed files with 1984 additions and 1743 deletions

View File

@@ -21,20 +21,30 @@ BEGIN
RAISE NOTICE 'Running % module. Start Time: %', _module_name, _start_time;
-- 1. Calculate Average Lead Time
-- For each completed PO, find the earliest receiving from the same supplier
-- within 180 days, then average those per-PO lead times per product.
RAISE NOTICE 'Calculating Average Lead Time...';
WITH LeadTimes AS (
WITH po_first_receiving AS (
SELECT
po.pid,
-- Calculate lead time by looking at when items ordered on POs were received
AVG(GREATEST(1, (r.received_date::date - po.date::date))) AS avg_days -- Use GREATEST(1,...) to avoid 0 or negative days
po.po_id,
po.date::date AS po_date,
MIN(r.received_date::date) AS first_receive_date
FROM public.purchase_orders po
-- Join to receivings table to find actual receipts
JOIN public.receivings r ON r.pid = po.pid
WHERE po.status = 'done' -- Only include completed POs
AND r.received_date >= po.date -- Ensure received date is not before order date
-- Optional: add check to make sure receiving is related to PO if you have source_po_id
-- AND (r.source_po_id = po.po_id OR r.source_po_id IS NULL)
GROUP BY po.pid
JOIN public.receivings r
ON r.pid = po.pid
AND r.supplier_id = po.supplier_id -- same supplier
AND r.received_date >= po.date -- received after order
AND r.received_date <= po.date + INTERVAL '180 days' -- within reasonable window
WHERE po.status = 'done'
GROUP BY po.pid, po.po_id, po.date
),
LeadTimes AS (
SELECT
pid,
ROUND(AVG(GREATEST(1, first_receive_date - po_date))) AS avg_days
FROM po_first_receiving
GROUP BY pid
)
UPDATE public.product_metrics pm
SET avg_lead_time_days = lt.avg_days::int