import { MissionLog, prisma } from "@repo/db"; import cron from "node-cron"; const removeClosedMissions = async () => { const oldMissions = await prisma.mission.findMany({ where: { state: "running", }, }); oldMissions.forEach(async (mission) => { const lastAlert = (mission.missionLog as unknown as MissionLog[]).find((l) => { return l.type === "alert-log"; }); const lastAlertTime = lastAlert ? new Date(lastAlert.timeStamp) : null; const aircraftsInMission = await prisma.connectedAircraft.findMany({ where: { stationId: { in: mission.missionStationIds, }, }, }); if ( aircraftsInMission.length > 0 && // Check if any aircraft is still active !aircraftsInMission.some((a) => ["1", "2", "6"].includes(a.fmsStatus)) // Check if any aircraft is in a status that indicates it's not inactive ) return; const now = new Date(); if (!lastAlertTime) return; // change State to closed if last alert was more than 180 minutes ago if (now.getTime() - lastAlertTime.getTime() < 30 * 60 * 1000) return; const log: MissionLog = { type: "completed-log", auto: true, timeStamp: new Date().toISOString(), data: {}, }; await prisma.mission.update({ where: { id: mission.id, }, data: { state: "finished", missionLog: { push: log as any, }, }, }); console.log(`Mission ${mission.id} closed due to inactivity.`); }); }; const removeConnectedAircrafts = async () => { const connectedAircrafts = await prisma.connectedAircraft.findMany({ where: { logoutTime: null, }, }); connectedAircrafts.forEach(async (aircraft) => { const lastUpdate = new Date(aircraft.lastHeartbeat); const now = new Date(); if (now.getTime() - lastUpdate.getTime() > 12 * 60 * 60 * 1000) { await prisma.connectedAircraft.update({ where: { id: aircraft.id }, data: { logoutTime: now }, }); console.log(`Aircraft ${aircraft.id} disconnected due to inactivity.`); } }); }; cron.schedule("*/5 * * * *", async () => { try { await removeClosedMissions(); await removeConnectedAircrafts(); } catch (error) { console.error("Error removing closed missions:", error); } });