test(materials per day): work on getting this running better
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
import { formatISO, parseISO, startOfWeek } from "date-fns";
|
||||
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
|
||||
import { query } from "../../../sqlServer/prodSqlServer.js";
|
||||
import { materialPurchasesPerDay } from "../../../sqlServer/querys/dataMart/materialPerDay.js";
|
||||
|
||||
function toDate(val: any) {
|
||||
if (val instanceof Date) return val;
|
||||
@@ -6,20 +9,52 @@ function toDate(val: any) {
|
||||
return new Date(val);
|
||||
}
|
||||
|
||||
export const materialPurchases = async (data: any) => {
|
||||
export const materialPurchases = async ({
|
||||
startDate,
|
||||
endDate,
|
||||
}: {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
}) => {
|
||||
/** @type {Record<string, Record<string, number>>} */
|
||||
const grouped: any = {};
|
||||
|
||||
for (const r of data) {
|
||||
const { data: p, error } = (await tryCatch(
|
||||
query(
|
||||
materialPurchasesPerDay
|
||||
.replace("[startDate]", startDate)
|
||||
.replace("[endDate]", endDate),
|
||||
"material check",
|
||||
),
|
||||
)) as any;
|
||||
|
||||
if (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Error getting the material data",
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
if (!p.success) {
|
||||
return {
|
||||
success: false,
|
||||
message: p.message,
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
for (const r of p.data) {
|
||||
const pOrder = String(r.purhcaseOrder);
|
||||
const mat = String(r.MaterialHumanReadableId);
|
||||
const d = toDate(r.CalDate);
|
||||
const d = toDate(r.deliveryDate);
|
||||
const week = formatISO(startOfWeek(d, { weekStartsOn: 1 }), {
|
||||
representation: "date",
|
||||
});
|
||||
|
||||
grouped[mat] ??= {};
|
||||
grouped[mat][week] ??= 0;
|
||||
grouped[mat][week] += Number(r.DailyMaterialDemand) || 0;
|
||||
grouped[mat][week] += Number(r.qty) || 0;
|
||||
}
|
||||
|
||||
const result = [];
|
||||
@@ -29,7 +64,7 @@ export const materialPurchases = async (data: any) => {
|
||||
result.push({
|
||||
MaterialHumanReadableId: mat,
|
||||
WeekStart: week,
|
||||
WeeklyDemand: Number(total).toFixed(2),
|
||||
WeeklyPurchase: Number(total).toFixed(2),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user