feat(notify): shortage bookings based on time and article type

This commit is contained in:
2025-06-20 11:18:37 -05:00
parent 095d724e65
commit c5bd5a7c0a
5 changed files with 268 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { notifications } from "../../../../../database/schema/notifications.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { sendEmail } from "../sendMail.js";
import { format } from "date-fns-tz";
import { shortageBookings } from "../../../sqlServer/querys/notifications/shortageBookings.js";
export interface Labels {
IdEtikettenHistorie?: number;
}
const notification = async (notifyData: any) => {
/**
* Pass the entire notification over
*/
createLog(
"info",
"wastebooking",
"notify",
`monitoring ${notifyData.name}`
);
// validate if there are any emails.
if (notifyData.emails === "") {
createLog(
"error",
"reprinting",
"notify",
`There are no emails set for ${notifyData.name}`
);
return;
}
//console.log(notifyData);
// update the settings so we have everything we need
let updatedQuery = shortageBookings
.replace("[time]", notifyData?.notifiySettings.time)
.replace("[type]", notifyData?.notifiySettings.type)
.replace("[avType]", notifyData?.notifiySettings.avType);
const { data: l, error: shortageError } = await tryCatch(
query(updatedQuery, "Removed as waste check")
);
const pallets: any = l?.data as any;
//console.log(updatedQuery);
//console.log(pallets);
if (shortageError) {
createLog(
"error",
"reprinting",
"notify",
`Failed to get the labels: ${shortageError}`
);
return;
}
if (pallets.length > 0) {
//send the email :D
const emailSetup = {
email: notifyData.emails,
subject: `Alert! New shortage booking as been completed in the last ${notifyData?.notifiySettings.time} min`,
template: "shortageBookings",
context: {
items: pallets.map((i: any) => {
return {
...i,
bookingDate: format(i.bookingDate, "M/d/yyyy"),
};
}),
},
};
const sentEmail = await sendEmail(emailSetup);
if (!sentEmail.success) {
createLog(
"error",
"reprinting",
"notify",
"Failed to send email, will try again on next interval"
);
return;
}
// // update the last time we ran and the prod id
// const notifUpdate = {
// prodID: labels[0].IdEtikettenHistorie,
// lastRan: nowDate(),
// };
// update the last time ran
const { data, error } = await tryCatch(
db
.update(notifications)
.set({
lastRan: sql`NOW()`,
})
.where(eq(notifications.name, notifyData.name))
);
} else {
return;
}
};
export default notification;