Fix calculate script regressions

This commit is contained in:
2025-02-02 09:27:06 -05:00
parent 06b0f1251e
commit 12cab7473a
6 changed files with 86 additions and 34 deletions

View File

@@ -66,6 +66,13 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount,
SUM(COALESCE(p.cost_price, 0) * o.quantity) as total_cost,
COUNT(DISTINCT o.order_number) as order_count,
AVG(o.price - COALESCE(o.discount, 0)) as avg_price,
CASE
WHEN SUM((o.price - COALESCE(o.discount, 0)) * o.quantity) > 0
THEN ((SUM((o.price - COALESCE(o.discount, 0)) * o.quantity) - SUM(COALESCE(p.cost_price, 0) * o.quantity))
/ SUM((o.price - COALESCE(o.discount, 0)) * o.quantity)) * 100
ELSE 0
END as profit_margin,
p.cost_price * p.stock_quantity as inventory_value,
COUNT(DISTINCT DATE(o.date)) as active_days
FROM orders o
JOIN products p ON o.pid = p.pid
@@ -90,8 +97,8 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount,
s.total_revenue,
s.total_cost,
s.order_count,
COALESCE(p.stock_received, 0) as stock_received,
COALESCE(p.stock_ordered, 0) as stock_ordered,
COALESCE(ms.stock_received, 0) as stock_received,
COALESCE(ms.stock_ordered, 0) as stock_ordered,
s.avg_price,
s.profit_margin,
s.inventory_value,
@@ -100,11 +107,11 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount,
(s.total_revenue - s.total_cost) / s.inventory_value
ELSE 0
END as gmroi
FROM sales_data s
LEFT JOIN purchase_data p
ON s.pid = p.pid
AND s.year = p.year
AND s.month = p.month
FROM monthly_sales s
LEFT JOIN monthly_stock ms
ON s.pid = ms.pid
AND s.year = ms.year
AND s.month = ms.month
UNION
SELECT
p.pid,
@@ -120,8 +127,8 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount,
0 as profit_margin,
(SELECT cost_price * stock_quantity FROM products WHERE pid = p.pid) as inventory_value,
0 as gmroi
FROM purchase_data p
LEFT JOIN sales_data s
FROM monthly_stock p
LEFT JOIN monthly_sales s
ON p.pid = s.pid
AND p.year = s.year
AND p.month = s.month