Update calculate script to account for import changes

This commit is contained in:
2025-01-27 10:41:18 -05:00
parent 44d9ae2aad
commit 5781b45f37
10 changed files with 508 additions and 297 deletions

View File

@@ -6,7 +6,7 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount)
// Initial insert of time-based aggregates
await connection.query(`
INSERT INTO product_time_aggregates (
product_id,
pid,
year,
month,
total_quantity_sold,
@@ -20,7 +20,7 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount)
)
WITH sales_data AS (
SELECT
o.product_id,
o.pid,
YEAR(o.date) as year,
MONTH(o.date) as month,
SUM(o.quantity) as total_quantity_sold,
@@ -35,23 +35,23 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount)
SUM((o.price - COALESCE(o.discount, 0)) * o.quantity)) * 100
END as profit_margin
FROM orders o
JOIN products p ON o.product_id = p.product_id
JOIN products p ON o.pid = p.pid
WHERE o.canceled = 0
GROUP BY o.product_id, YEAR(o.date), MONTH(o.date)
GROUP BY o.pid, YEAR(o.date), MONTH(o.date)
),
purchase_data AS (
SELECT
product_id,
pid,
YEAR(date) as year,
MONTH(date) as month,
SUM(received) as stock_received,
SUM(ordered) as stock_ordered
FROM purchase_orders
WHERE status = 'closed'
GROUP BY product_id, YEAR(date), MONTH(date)
WHERE receiving_status >= 30 -- Partial or fully received
GROUP BY pid, YEAR(date), MONTH(date)
)
SELECT
s.product_id,
s.pid,
s.year,
s.month,
s.total_quantity_sold,
@@ -64,12 +64,12 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount)
s.profit_margin
FROM sales_data s
LEFT JOIN purchase_data p
ON s.product_id = p.product_id
ON s.pid = p.pid
AND s.year = p.year
AND s.month = p.month
UNION
SELECT
p.product_id,
p.pid,
p.year,
p.month,
0 as total_quantity_sold,
@@ -82,10 +82,10 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount)
0 as profit_margin
FROM purchase_data p
LEFT JOIN sales_data s
ON p.product_id = s.product_id
ON p.pid = s.pid
AND p.year = s.year
AND p.month = s.month
WHERE s.product_id IS NULL
WHERE s.pid IS NULL
ON DUPLICATE KEY UPDATE
total_quantity_sold = VALUES(total_quantity_sold),
total_revenue = VALUES(total_revenue),
@@ -102,17 +102,17 @@ async function calculateTimeAggregates(startTime, totalProducts, processedCount)
UPDATE product_time_aggregates pta
JOIN (
SELECT
p.product_id,
p.pid,
YEAR(o.date) as year,
MONTH(o.date) as month,
p.cost_price * p.stock_quantity as inventory_value,
SUM(o.quantity * (o.price - p.cost_price)) as gross_profit,
COUNT(DISTINCT DATE(o.date)) as days_in_period
FROM products p
LEFT JOIN orders o ON p.product_id = o.product_id
LEFT JOIN orders o ON p.pid = o.pid
WHERE o.canceled = false
GROUP BY p.product_id, YEAR(o.date), MONTH(o.date)
) fin ON pta.product_id = fin.product_id
GROUP BY p.pid, YEAR(o.date), MONTH(o.date)
) fin ON pta.pid = fin.pid
AND pta.year = fin.year
AND pta.month = fin.month
SET