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 { palletsRemovedAswaste } from "../../../sqlServer/querys/notifications/palletsRemovedAsWaste.js"; import { format } from "date-fns-tz"; 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; } const { data: l, error: palletError } = await tryCatch( query(palletsRemovedAswaste, "Removed as waste check") ); const pallets: any = l?.data as any; if (palletError) { createLog( "error", "reprinting", "notify", `Failed to get the labels: ${palletError}` ); return; } console.log(pallets); if (pallets.length > 0) { //send the email :D const emailSetup = { email: notifyData.emails, subject: `Alert! ${ pallets.length > 1 ? "Some pallets were" : "A pallet was " } brought back in`, template: "palletBookedAsWaste", context: { items: pallets.map((i: any) => { return { ...i, lastMovingDate: format(i.lastMovingDate, "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()`, notifiySettings: { ...notifyData.notifiySettings, prodID: pallets[0].runningnumber, }, }) .where(eq(notifications.name, notifyData.name)) ); } else { return; } }; export default notification;