Fix calculate errors

This commit is contained in:
2025-02-01 23:38:13 -05:00
parent 0a51328da2
commit bd5bcdd548
6 changed files with 92 additions and 92 deletions

View File

@@ -35,6 +35,13 @@ async function calculateProductMetrics(startTime, totalProducts, processedCount
return processedCount;
}
// First ensure all products have a metrics record
await connection.query(`
INSERT IGNORE INTO product_metrics (pid, last_calculated_at)
SELECT pid, NOW()
FROM products
`);
// Calculate base product metrics
if (!SKIP_PRODUCT_BASE_METRICS) {
outputProgress({
@@ -59,6 +66,8 @@ async function calculateProductMetrics(startTime, totalProducts, processedCount
JOIN (
SELECT
p.pid,
p.stock_quantity,
p.cost_price,
p.cost_price * p.stock_quantity as inventory_value,
SUM(o.quantity) as total_quantity,
COUNT(DISTINCT o.order_number) as number_of_orders,
@@ -71,7 +80,7 @@ async function calculateProductMetrics(startTime, totalProducts, processedCount
COUNT(DISTINCT DATE(o.date)) as active_days
FROM products p
LEFT JOIN orders o ON p.pid = o.pid AND o.canceled = false
GROUP BY p.pid
GROUP BY p.pid, p.stock_quantity, p.cost_price
) stats ON pm.pid = stats.pid
SET
pm.inventory_value = COALESCE(stats.inventory_value, 0),
@@ -89,12 +98,12 @@ async function calculateProductMetrics(startTime, totalProducts, processedCount
pm.last_sale_date = stats.last_sale_date,
pm.days_of_inventory = CASE
WHEN COALESCE(stats.total_quantity / NULLIF(stats.active_days, 0), 0) > 0
THEN FLOOR(p.stock_quantity / (stats.total_quantity / stats.active_days))
THEN FLOOR(stats.stock_quantity / (stats.total_quantity / stats.active_days))
ELSE NULL
END,
pm.weeks_of_inventory = CASE
WHEN COALESCE(stats.total_quantity / NULLIF(stats.active_days, 0), 0) > 0
THEN FLOOR(p.stock_quantity / (stats.total_quantity / stats.active_days) / 7)
THEN FLOOR(stats.stock_quantity / (stats.total_quantity / stats.active_days) / 7)
ELSE NULL
END,
pm.gmroi = CASE
@@ -239,8 +248,7 @@ async function calculateProductMetrics(startTime, totalProducts, processedCount
avg_price = VALUES(avg_price),
profit_margin = VALUES(profit_margin),
inventory_value = VALUES(inventory_value),
gmroi = VALUES(gmroi),
last_calculated_at = CURRENT_TIMESTAMP
gmroi = VALUES(gmroi)
`);
processedCount = Math.floor(totalProducts * 0.6);