feat(notify): material per day for the next 90 days
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
addDays,
|
||||
format,
|
||||
formatISO,
|
||||
isBefore,
|
||||
parseISO,
|
||||
startOfWeek,
|
||||
} from "date-fns";
|
||||
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
|
||||
import { query } from "../../../sqlServer/prodSqlServer.js";
|
||||
import { materialPerDay } from "../../../sqlServer/querys/dataMart/materialPerDay.js";
|
||||
|
||||
function toDate(val: any) {
|
||||
if (val instanceof Date) return val;
|
||||
if (typeof val === "string") return parseISO(val.replace(" ", "T"));
|
||||
return new Date(val);
|
||||
}
|
||||
|
||||
export function sumByMaterialAndWeek(data: any) {
|
||||
/** @type {Record<string, Record<string, number>>} */
|
||||
const grouped: any = {};
|
||||
|
||||
for (const r of data) {
|
||||
const mat = String(r.MaterialHumanReadableId);
|
||||
const d = toDate(r.CalDate);
|
||||
const week = formatISO(startOfWeek(d, { weekStartsOn: 1 }), {
|
||||
representation: "date",
|
||||
});
|
||||
|
||||
grouped[mat] ??= {};
|
||||
grouped[mat][week] ??= 0;
|
||||
grouped[mat][week] += Number(r.DailyMaterialDemand) || 0;
|
||||
}
|
||||
|
||||
const result = [];
|
||||
for (const [mat, weeks] of Object.entries(grouped)) {
|
||||
// @ts-ignore
|
||||
for (const [week, total] of Object.entries(weeks)) {
|
||||
result.push({
|
||||
MaterialHumanReadableId: mat,
|
||||
WeekStart: week,
|
||||
WeeklyDemand: Number(total).toFixed(2),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export default async function materialPerDayCheck() {
|
||||
/**
|
||||
* getting the shipped pallets
|
||||
*/
|
||||
|
||||
const startDate = format(new Date(Date.now()), "yyyy-MM-dd");
|
||||
const endDate = format(addDays(new Date(Date.now()), 90), "yyyy-MM-dd");
|
||||
|
||||
const { data, error } = (await tryCatch(
|
||||
query(
|
||||
materialPerDay
|
||||
.replace("[startDate]", startDate)
|
||||
.replace("[endDate]", endDate),
|
||||
"material check",
|
||||
),
|
||||
)) as any;
|
||||
|
||||
if (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Error getting the material data",
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
if (!data.success) {
|
||||
return {
|
||||
success: false,
|
||||
message: data.message,
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "material data",
|
||||
data: sumByMaterialAndWeek(data.data),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user