diff --git a/app.js b/app.js index 29ac577..e69433c 100644 --- a/app.js +++ b/app.js @@ -1,3 +1,5 @@ +//app.js + require("dotenv").config({ path: ".env" }) require("events").EventEmitter.prototype._maxListeners = 30 const morgan = require("morgan") @@ -14,6 +16,7 @@ const LibMail = require("./library/LibMail") const LibHelper = require("./library/LibHelper") const nanoid = require("nanoid").nanoid const LibWinston = require("./library/LibWinston") +const cron = require("node-cron") const express = require("express") // const routes = require("./routes/routes") @@ -288,6 +291,102 @@ async function commitMessage(now, logDevice) { } } +async function checkMaintenanceMileage(vhc) { + try { + if (!vhc || !vhc.id) return false + + const lastHistory = await db.query( + `SELECT odometer FROM t_vehicles_maintenance_history + WHERE vhc_id = ? AND isdeleted = 0 + ORDER BY id DESC LIMIT 1`, + [vhc.id], + ) + + if (!lastHistory?.length) return false + + const lastOdometer = Number(lastHistory[0].odometer || 0) + const currentMileage = Number(vhc.sum_milleage || 0) + const diff = currentMileage - lastOdometer + + const thresholds = [5000, 10000, 150000] + if (!thresholds.includes(diff)) return false + + await db.query( + `INSERT INTO t_vehicles_maintenance_history SET vhc_id = ?, odometer = ?`, + [vhc.id, currentMileage], + ) + + const users = await db.query( + `SELECT phone FROM t_users WHERE status_sms = 1 AND FIND_IN_SET(?, vhc) > 0`, + [vhc.id], + ) + if (!users?.length) return false + + const nopol = (vhc.nopol1 ?? "") + (vhc.nopol2 ?? "") + (vhc.nopol3 ?? "") + + const rawMsg = `${nopol} | MAINTENANCE | ${diff} km sejak maintenance terakhir`.substring(0, 150).trim() + const countryCode = process.env.SMS_COUNTRY_CODE ?? "670" + const smsHost = process.env.SMS_HOST ?? "http://192.168.40.2:8181/submitsm/ka" + + await Promise.allSettled( + users + .filter((u) => u.phone) + .map(async (user) => { + try { + await axios.get(`${smsHost}`, { + params: { to: `${countryCode}${user.phone}`, msg: rawMsg, sender: "Maintenance FROTA" }, + }) + } catch (smsErr) { + console.error("Error sending SMS:", smsErr.response ? JSON.stringify(smsErr.response.data) : smsErr.message) + } + + try { + await db.query(`INSERT INTO sms_notif SET to_no = ?, message = ?`, [user.phone, rawMsg]) + } catch (dbErr) { + console.error("Error logging SMS to DB:", dbErr.message) + } + }), + ) + } catch (e) { + console.error("Error checkMaintenanceMileage:", e) + } +} + +async function checkMaintenanceMileageScheduler() { + console.log("Maintenance mileage check job executed:", moment().format("YYYY-MM-DD HH:mm:ss")) + try { + console.time("Maintenance mileage check") + + // ambil semua vehicle aktif beserta mileage & nopol + // vhc.id di sini didapat dari kolom `id` tabel t_vehicles, BUKAN dari device + const vehicles = await db.query( + `SELECT id, nopol1, nopol2, nopol3, sum_milleage + FROM t_vehicles + WHERE dlt IS NULL`, + [], + ) + + if (!vehicles?.length) { + console.log("No active vehicles found.") + console.timeEnd("Maintenance mileage check") + return + } + + for (const vhc of vehicles) { + try { + await checkMaintenanceMileage(vhc) + } catch (err) { + console.error(`Error checking maintenance for vhc_id ${vhc.id}:`, err.message) + } + } + + console.timeEnd("Maintenance mileage check") + } catch (error) { + console.error("Error in checkMaintenanceMileageScheduler:", error.message) + } + console.log("Maintenance mileage check job completed.") +} + const devices = [] const netConn = require("./config/netConn") /** @@ -519,8 +618,8 @@ net.createServer( commitMessage(now, logDevice) }) - c.on("end", () => {}) - c.on("close", () => {}) + c.on("end", () => { }) + c.on("close", () => { }) c.on("drain", (a) => { console.log("client drain", a) @@ -643,3 +742,4 @@ udp.on("listening", () => { }) udp.bind(process.env.PORT_UDP) +cron.schedule("0 * * * *", () => { checkMaintenanceMileageScheduler() })