Compare commits

..

23 Commits

Author SHA1 Message Date
a0330f5635 Merge pull request 'wisdom' (#64) from wisdom into main
Reviewed-on: #64
2026-07-08 07:18:55 +00:00
13ce1705fa fix: reminder route 2026-07-08 12:56:08 +07:00
b4fe71ccc6 fix: body message whatsapp in reminder custom 2026-07-08 11:48:32 +07:00
a52efeceb5 fix: reminder monthly in db device 2026-07-08 11:47:11 +07:00
1c56239fc8 fix: router reminder 2026-07-08 11:37:47 +07:00
1735db35ef Merge pull request 'wisdom' (#63) from wisdom into main
Reviewed-on: #63
2026-06-26 09:51:53 +00:00
84ba679b2e fix: update and create sparepart 2026-06-26 16:38:33 +07:00
e5a77f2f93 fix: validation in sparepart and device 2026-06-26 16:10:54 +07:00
fb880cc3b6 Merge pull request 'wisdom' (#62) from wisdom into main
Reviewed-on: #62
2026-06-25 06:41:42 +00:00
5112090a35 fix: custom reminder 2026-06-24 19:50:50 +07:00
e2dcbe74d3 fix: add cron in reminder monthly 2026-06-24 19:34:31 +07:00
55aa2f05c6 fix: reminder monthly, and cron in reminder reminder monthly 2026-06-24 19:33:23 +07:00
c0874f69df fix(module): add node-cron dependency 2026-06-24 16:16:55 +07:00
8fd317083b add: feature reminder custom device with cron-job 2026-06-23 21:59:02 +07:00
da8cdcb705 fix(reminder_monthly): fix loop blocking issue by scoping validation to device_id 2026-06-11 15:43:13 +07:00
e0b227c9b8 add: validation error in onMonthlySparepartReminder 2026-06-11 13:39:08 +07:00
1de41b8e9b Merge pull request 'fix: change email validate to opsional in contact schema' (#61) from wisdom into main
Reviewed-on: #61
2026-06-08 03:11:41 +00:00
Muhammad Afif
297db50e72 fix: change email validate to opsional in contact schema 2026-06-05 19:46:44 +07:00
07e72fba3d Merge pull request 'wisdom' (#60) from wisdom into main
Reviewed-on: #60
2026-06-05 09:53:13 +00:00
Muhammad Afif
69ba363c14 repair: change email schema optional to required 2026-06-05 14:09:29 +07:00
Muhammad Afif
ab5fe3e9c4 add: columns / field email in contact 2026-06-05 13:42:30 +07:00
Muhammad Afif
40de826da9 add: reminder whatsapp sparepart monthly 2026-06-05 09:17:45 +07:00
Muhammad Afif
3d53bf4702 fix: is_send & is_delivered in onNotificationReminder 2026-06-03 15:08:55 +07:00
13 changed files with 981 additions and 72 deletions

View File

@@ -25,6 +25,7 @@ const getAllContactDb = async (searchParams = {}) => {
{ column: "a.contact_name", param: searchParams.name, type: "string" }, { column: "a.contact_name", param: searchParams.name, type: "string" },
{ column: "a.contact_type", param: searchParams.code, type: "string" }, { column: "a.contact_type", param: searchParams.code, type: "string" },
{ column: "a.is_active", param: searchParams.active, type: "boolean" }, { column: "a.is_active", param: searchParams.active, type: "boolean" },
{ column: "a.email", param: searchParams.email, type: "string" },
], ],
queryParams queryParams
); );

View File

@@ -63,7 +63,6 @@ const getAllDevicesDb = async (searchParams = {}) => {
return { data: result.recordset, total }; return { data: result.recordset, total };
}; };
const getDeviceByIdDb = async (id) => { const getDeviceByIdDb = async (id) => {
const queryText = ` const queryText = `
SELECT SELECT
@@ -116,12 +115,15 @@ const updateDeviceDb = async (id, data) => {
}; };
const deleteDeviceDb = async (id, deletedBy) => { const deleteDeviceDb = async (id, deletedBy) => {
// Jika deletedBy adalah string, konversi ke integer atau gunakan default
const deletedById = typeof deletedBy === 'string' ? parseInt(deletedBy) || 0 : deletedBy || 0;
const queryText = ` const queryText = `
UPDATE m_device UPDATE m_device
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1 SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE device_id = $2 AND deleted_at IS NULL WHERE device_id = $2 AND deleted_at IS NULL
`; `;
await pool.query(queryText, [deletedBy, id]); await pool.query(queryText, [deletedById, id]);
return true; return true;
}; };
@@ -139,11 +141,68 @@ const getDeviceReminderChanelDb = async (id) => {
return result.recordset; return result.recordset;
}; };
const getDeviceReminderMonthlyDb = async (id) => {
const queryText = `
SELECT
a.*,
b.brand_name,
COALESCE(a.device_code, '') + ' - ' + COALESCE(a.device_name, '') AS device_code_name
FROM m_device a
LEFT JOIN m_brands b ON a.brand_id = b.brand_id
WHERE a.device_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
const updateDeviceReminderMonthlyDb = async (deviceId, reminderMonthly) => {
const queryText = `
UPDATE m_device
SET reminder_at_monthly = $1,
updated_at = CURRENT_TIMESTAMP
WHERE device_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [reminderMonthly, deviceId]);
return getDeviceByIdDb(deviceId);
};
const getDeviceReminderCustomDb = async (id) => {
const queryText = `
SELECT
a.*,
b.brand_name,
COALESCE(a.device_code, '') + ' - ' + COALESCE(a.device_name, '') AS device_code_name
FROM m_device a
LEFT JOIN m_brands b ON a.brand_id = b.brand_id
WHERE a.device_id = $1
AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
const updateDeviceReminderCustomDb = async (deviceId, startDate, endDate) => {
const queryText = `
UPDATE m_device
SET start_date = $1,
end_date = $2,
updated_at = CURRENT_TIMESTAMP
WHERE device_id = $3 AND deleted_at IS NULL
`;
await pool.query(queryText, [startDate, endDate, deviceId]);
return getDeviceByIdDb(deviceId);
};
module.exports = { module.exports = {
getAllDevicesDb, getAllDevicesDb,
getDeviceByIdDb, getDeviceByIdDb,
createDeviceDb, createDeviceDb,
updateDeviceDb, updateDeviceDb,
deleteDeviceDb, deleteDeviceDb,
getDeviceReminderChanelDb getDeviceReminderChanelDb,
}; getDeviceReminderMonthlyDb,
getDeviceReminderCustomDb,
updateDeviceReminderCustomDb,
updateDeviceReminderMonthlyDb
};

View File

@@ -255,6 +255,36 @@ const getReminderNotificationErrorByYearlyDb = async (errorCode, chanel, year) =
return result.recordset[0]; return result.recordset[0];
}; };
const getReminderNotificationErrorByMonthlyDb = async (errorCode, monthly, deviceId) => {
const queryText = `
SELECT a.*
FROM notification_error a
WHERE a.error_code_id = $1
AND MONTH(a.created_at) = $2
AND a.message_error_issue LIKE '%device_id: ' + CAST($3 AS VARCHAR) + '%'
AND a.is_active = 1
AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [errorCode, monthly, deviceId]);
return result.recordset[0];
};
const getReminderNotificationErrorByCustomDb = async (errorCode, custom, deviceId) => {
const queryText = `
SELECT a.*
FROM notification_error a
WHERE a.error_code_id = $1
AND a.created_at = $2
AND a.message_error_issue LIKE '%device_id: ' + CAST($3 AS VARCHAR) + '%'
AND a.is_active = 1
AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [errorCode, custom, deviceId]);
return result.recordset[0];
};
module.exports = { module.exports = {
getNotificationByIdDb, getNotificationByIdDb,
getDeviceNotificationByIdDb, getDeviceNotificationByIdDb,
@@ -264,6 +294,8 @@ module.exports = {
getUsersNotificationErrorDb, getUsersNotificationErrorDb,
getDeviceChannelReminder, getDeviceChannelReminder,
getReminderNotificationErrorByYearlyDb, getReminderNotificationErrorByYearlyDb,
getReminderNotificationErrorByMonthlyDb,
getReminderNotificationErrorByCustomDb,
updateNotificationErrorByChanelReminderDb updateNotificationErrorByChanelReminderDb
}; };

View File

@@ -197,6 +197,42 @@ const getSparepartsByYearlyDb = async (yearly) => {
return result.recordset; return result.recordset;
}; };
const getSparepartsByMonthlyDb = async (monthly) => {
const queryText = `
SELECT *
FROM m_sparepart
WHERE deleted_at IS NULL
AND EXISTS (
SELECT 1
FROM OPENJSON(sparepart_monthly)
WHERE value = $1
)
`;
const result = await pool.query(queryText, [monthly]);
return result.recordset;
};
const getSparepartsByCustomDb = async (custom) => {
const queryText = `
SELECT *
FROM m_sparepart
WHERE deleted_at IS NULL
AND EXISTS (
SELECT 1
FROM OPENJSON(sparepart_custom)
WHERE value = $1
)
`;
const result = await pool.query(queryText, [custom]);
return result.recordset;
};
module.exports = { module.exports = {
getAllSparepartDb, getAllSparepartDb,
getSparepartByIdDb, getSparepartByIdDb,
@@ -205,5 +241,7 @@ module.exports = {
createSparepartDb, createSparepartDb,
updateSparepartDb, updateSparepartDb,
deleteSparepartDb, deleteSparepartDb,
getSparepartsByYearlyDb getSparepartsByYearlyDb,
getSparepartsByMonthlyDb,
getSparepartsByCustomDb
}; };

View File

@@ -45,6 +45,7 @@
"mqtt": "^5.14.0", "mqtt": "^5.14.0",
"mssql": "^11.0.1", "mssql": "^11.0.1",
"multer": "^1.4.5-lts.2", "multer": "^1.4.5-lts.2",
"node-cron": "^4.5.0",
"nodemailer": "^6.8.0", "nodemailer": "^6.8.0",
"pg": "^8.8.0", "pg": "^8.8.0",
"pino": "^6.11.3", "pino": "^6.11.3",

View File

@@ -1,5 +1,8 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const verifyToken = require("../middleware/verifyToken");
const verifyAccess = require("../middleware/verifyAccess");
const NotifikasiWaService = require('../services/notifikasi-wa.service'); const NotifikasiWaService = require('../services/notifikasi-wa.service');
router.post('/restart-wa', async (req, res) => { router.post('/restart-wa', async (req, res) => {
@@ -11,4 +14,73 @@ router.post('/restart-wa', async (req, res) => {
} }
}); });
router.post('/reminder-monthly/:id', verifyToken.verifyAccessToken, verifyAccess(), async (req, res) => {
try {
const { id } = req.params;
const { reminder_at_monthly } = req.body;
const result = await NotifikasiWaService.onMonthlyReminder(id, reminder_at_monthly);
return res.status(200).json(result);
} catch (error) {
return res.status(500).json(error);
}
});
router.post('/reminder-custom/:id', verifyToken.verifyAccessToken, verifyAccess(), async (req, res) => {
try {
const { id } = req.params;
const { start_date, end_date } = req.body;
const result = await NotifikasiWaService.onCustomReminder(id, start_date, end_date);
return res.status(200).json(result);
} catch (error) {
return res.status(500).json(error);
}
});
// router.get('/cron/jobs', async (req, res) => {
// try {
// const activeJobs = NotifikasiWaService.getActiveCronJobs();
// return res.status(200).json({
// success: true,
// total: activeJobs.length,
// jobs: activeJobs
// });
// } catch (error) {
// return res.status(500).json({
// success: false,
// message: error.message
// });
// }
// });
// router.delete('/cron/jobs/:deviceId', async (req, res) => {
// try {
// const { deviceId } = req.params;
// NotifikasiWaService.stopCronJob(deviceId);
// return res.status(200).json({
// success: true,
// message: `Cron job untuk device ${deviceId} dihentikan`
// });
// } catch (error) {
// return res.status(500).json({
// success: false,
// message: error.message
// });
// }
// });
// router.delete('/cron/jobs', async (req, res) => {
// try {
// NotifikasiWaService.stopAllCronJobs();
// return res.status(200).json({
// success: true,
// message: 'Semua cron job dihentikan'
// });
// } catch (error) {
// return res.status(500).json({
// success: false,
// message: error.message
// });
// }
// });
module.exports = router; module.exports = router;

View File

@@ -1,19 +0,0 @@
[
{
"notification_log": 851,
"error_code_id": 1,
"error_chanel": 2025,
"start_at": "02:10",
"interval": 1,
"max": 3,
"active": 1,
"count": 0,
"last_run": "2026-05-31T17:41:09.191Z",
"last_run_indo": "01-06-2026 00:41:09",
"next_run": "2026-05-31T18:41:09.191Z",
"next_run_indo": "01-06-2026 01:41:09",
"message": "Reminder untuk PLC Compressor B dengan reminder 1YEAR telah dijalankan pada 01-06-2026 00:41:09, hasil pengiriman: sukses",
"time": "00:41",
"created_at": "2026-05-31T17:41:18.802Z"
}
]

View File

@@ -31,7 +31,7 @@ const {
} = require("../db/notification_wa.db"); } = require("../db/notification_wa.db");
const { ErrorHandler } = require("../helpers/error"); const { ErrorHandler } = require("../helpers/error");
const { getSparepartsByYearlyDb } = require("../db/sparepart.db"); const { getSparepartsByYearlyDb, getSparepartsByMonthlyDb } = require("../db/sparepart.db");
const notifikasiWaService = require("./notifikasi-wa.service"); const notifikasiWaService = require("./notifikasi-wa.service");
@@ -140,11 +140,18 @@ class NotificationService {
notification.is_reminder = false; notification.is_reminder = false;
notification.spareparts_reminder = []; notification.spareparts_reminder = [];
if (notification.message_error_issue) { if (notification.message_error_issue) {
const sparepartsReminder = await getSparepartsByYearlyDb(notification.error_code_id);
notification.spareparts_reminder = sparepartsReminder ?? []; const [sparepartsYearly, sparepartsMonthly] = await Promise.all([
getSparepartsByYearlyDb(notification.error_code_id),
getSparepartsByMonthlyDb(notification.error_code_id)
]);
notification.spareparts_reminder = [
...(sparepartsYearly ?? []),
...(sparepartsMonthly ?? [])
];
notification.is_reminder = true; notification.is_reminder = true;
} }
return notification; return notification;
@@ -172,7 +179,7 @@ class NotificationService {
if (!notification.is_read) { if (!notification.is_read) {
const updateStatus = await updateNotificationErrorDb( const updateStatus = await updateNotificationErrorDb(
notification_error_id, notification_error_id,
{ is_read: true} { is_read: true }
); );
if (!updateStatus) { if (!updateStatus) {

View File

@@ -1,34 +1,53 @@
const { getAllContactDb } = require("../db/contact.db"); const { getAllContactDb } = require("../db/contact.db");
const { const {
InsertNotificationErrorDb, InsertNotificationErrorDb,
updateNotificationErrorDb, updateNotificationErrorDb,
getReminderNotificationErrorByYearlyDb, getReminderNotificationErrorByYearlyDb,
getDeviceNotificationByIdDb,
getReminderNotificationErrorByMonthlyDb,
getReminderNotificationErrorByCustomDb,
updateNotificationErrorByChanelReminderDb, updateNotificationErrorByChanelReminderDb,
} = require("../db/notification_error.db"); } = require("../db/notification_error.db");
const { const {
createNotificationErrorUserDb, createNotificationErrorUserDb,
updateNotificationErrorUserDb, updateNotificationErrorUserDb,
getNotificationErrorByIdDb, getNotificationErrorByIdDb,
} = require("../db/notification_error_user.db"); } = require("../db/notification_error_user.db");
const { const {
generateTokenRedirect, generateTokenRedirect,
shortUrltiny, shortUrltiny,
sendNotifikasi, sendNotifikasi,
} = require("../db/notification_wa.db"); } = require("../db/notification_wa.db");
const { getErrorCodeByBrandAndCodeDb } = require("../db/brand_code.db"); const { getErrorCodeByBrandAndCodeDb } = require("../db/brand_code.db");
const { getDeviceNotificationByIdDb } = require("../db/notification_error.db");
const {
getDeviceReminderChanelDb,
getDeviceReminderMonthlyDb,
getDeviceReminderCustomDb,
updateDeviceReminderCustomDb,
updateDeviceReminderMonthlyDb
} = require("../db/device.db");
const {
getSparepartsByMonthlyDb,
getSparepartsByCustomDb
} = require("../db/sparepart.db");
const { exec } = require("child_process"); const { exec } = require("child_process");
const util = require("util"); const util = require("util");
const execPromise = util.promisify(exec); const execPromise = util.promisify(exec);
const fs = require('fs').promises; const fs = require('fs').promises;
const path = require("path"); const path = require("path");
const { getDeviceReminderChanelDb } = require("../db/device.db");
const baseDir = path.resolve(__dirname, '../scheduler'); const baseDir = path.resolve(__dirname, '../scheduler');
const filePath = path.join(baseDir, 'reminder.json'); const filePath = path.join(baseDir, 'reminder.json');
// const filePathLog = path.join(baseDir, 'log.json'); // const filePathLog = path.join(baseDir, 'log.json');
const cron = require('node-cron');
const dayjs = require('dayjs'); const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc'); const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone'); const timezone = require('dayjs/plugin/timezone');
@@ -38,8 +57,16 @@ const timeZone = 'Asia/Jakarta';
dayjs.extend(utc); dayjs.extend(utc);
dayjs.extend(timezone); dayjs.extend(timezone);
let reminderCronJob = null;
let isCronInitialized = false;
class NotifikasiWaService { class NotifikasiWaService {
constructor() {
this.timeZone = 'Asia/Jakarta';
this.cronJobs = new Map();
}
async saveReminder(data, isReset = false) { async saveReminder(data, isReset = false) {
console.log(`Reminder dibuat`); console.log(`Reminder dibuat`);
@@ -396,7 +423,7 @@ class NotifikasiWaService {
); );
} }
} }
item.last_run = now.toISOString(); // tetap UTC (standar DB) item.last_run = now.toISOString();
item.last_run_indo = now.format('DD-MM-YYYY HH:mm:ss'); // WIB item.last_run_indo = now.format('DD-MM-YYYY HH:mm:ss'); // WIB
item.count += 1; item.count += 1;
} }
@@ -489,9 +516,7 @@ class NotifikasiWaService {
}; };
const resultNotificationError = await InsertNotificationErrorDb(data); const resultNotificationError = await InsertNotificationErrorDb(data);
const results = await getAllContactDb(paramDb); const results = await getAllContactDb(paramDb);
const dataUsers = results.data; const dataUsers = results.data;
let isSendNotification = false; let isSendNotification = false;
@@ -513,8 +538,7 @@ class NotifikasiWaService {
`Hai ${dataUser.contact_name || "-"},\n` + `Hai ${dataUser.contact_name || "-"},\n` +
`Diberitahukan bahwa terdapat sparepart pada device "${deviceName ?? "-"}" ` + `Diberitahukan bahwa terdapat sparepart pada device "${deviceName ?? "-"}" ` +
`yang telah memasuki jadwal perawatan tahunan.\n` + `yang telah memasuki jadwal perawatan tahunan.\n` +
`\nSilakan segera lakukan pengecekan dan perawatan untuk memastikan kinerja tetap optimal.` + `\nSilakan segera lakukan pengecekan dan perawatan untuk memastikan kinerja tetap optimal.`;
`\nDetail sparepart dapat dilihat pada link berikut:\n${shortUrl}`;
const param = { const param = {
idData: resultNotificationError.notification_error_id, idData: resultNotificationError.notification_error_id,
@@ -523,21 +547,31 @@ class NotifikasiWaService {
bodyMessage: bodyMessage, bodyMessage: bodyMessage,
}; };
const resultNotificationErrorUser = const resultNotificationErrorUser = await createNotificationErrorUserDb({
await createNotificationErrorUserDb({ notification_error_id: param.idData,
notification_error_id: param.idData, contact_phone: param.userPhone,
contact_name: param.userName,
contact_phone: param.userPhone, message_error_issue: param.bodyMessage,
contact_name: param.userName, is_send: false,
message_error_issue: param.bodyMessage, });
is_send: false,
});
const resultSend = await sendNotifikasi( const resultSend = await sendNotifikasi(
param.userPhone, param.userPhone,
param.bodyMessage param.bodyMessage
); );
// await this.saveLogReminder({
// message: `Reminder dijalankan`,
// resultSend
// })
await updateNotificationErrorUserDb(
resultNotificationErrorUser[0].notification_error_user_id,
{
is_send: resultSend.success,
}
);
await this.saveReminder({ await this.saveReminder({
notification_log: resultNotificationError.notification_error_id, notification_log: resultNotificationError.notification_error_id,
error_code_id: data['error_code_id'], error_code_id: data['error_code_id'],
@@ -551,21 +585,9 @@ class NotifikasiWaService {
last_run_indo: now.format('DD-MM-YYYY HH:mm:ss'), last_run_indo: now.format('DD-MM-YYYY HH:mm:ss'),
next_run: null, next_run: null,
next_run_indo: null, next_run_indo: null,
message: `Reminder untuk ${deviceName} dengan reminder ${chanel.value} telah dijalankan pada ${now.format('DD-MM-YYYY HH:mm:ss')}, hasil pengiriman: ${resultSend.success ? 'sukses' : 'gagal'}`, message: `Reminder untuk ${deviceName} dengan reminder ${chanel.value} telah dijalankan pada ${now.format('DD-MM-YYYY HH:mm:ss')}}`,
}, false); }, false);
// await this.saveLogReminder({
// message: `Reminder dijalankan`,
// resultSend
// })
await updateNotificationErrorUserDb(
resultNotificationErrorUser[0].notification_error_user_id,
{
is_send: resultSend.success,
}
);
if (resultSend.success) { if (resultSend.success) {
isSendNotification = resultSend.success; isSendNotification = resultSend.success;
} }
@@ -591,6 +613,669 @@ class NotifikasiWaService {
} }
} }
async onMonthlyReminder(deviceId, reminderMonthly) {
try {
const paramDb = {
limit: 100,
page: 1,
criteria: "",
active: true,
};
const devices = await getDeviceReminderMonthlyDb(deviceId);
if (!devices || devices.length === 0) {
return {
success: false,
message: `Device dengan ID ${deviceId} tidak ditemukan di database`
};
}
const device = devices[0];
const deviceName = device.device_name;
const currentDeviceId = device.device_id;
let targetReminderTime = device.reminder_at_monthly;
if (reminderMonthly) {
const isValidDate = dayjs.tz(reminderMonthly, this.timeZone).isValid();
if (!isValidDate) {
return {
success: false,
message: 'Format Reminder Monthly tidak valid. Gunakan format YYYY-MM-DD HH:mm:ss'
};
}
const updatedDevice = await updateDeviceReminderMonthlyDb(deviceId, reminderMonthly);
if (!updatedDevice) {
return {
success: false,
message: 'Gagal mengupdate Reminder Monthly.'
};
}
targetReminderTime = reminderMonthly;
} else if (!targetReminderTime) {
const reminderTime = dayjs().tz(this.timeZone).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
const updatedDevice = await updateDeviceReminderMonthlyDb(deviceId, reminderTime);
if (!updatedDevice) {
return {
success: false,
message: 'Gagal update Reminder Monthly dengan default time.'
};
}
targetReminderTime = reminderTime;
}
const reminderAt = dayjs.tz(targetReminderTime, this.timeZone);
const now = dayjs().tz(this.timeZone);
const isEndDatePassed = now.isAfter(reminderAt) || now.isSame(reminderAt);
if (isEndDatePassed) {
const sendResult = await this.sendMonthlyReminderNow(
currentDeviceId,
deviceName,
reminderAt
);
return sendResult;
}
this.stopCronJob(currentDeviceId);
const scheduleResult = await this.scheduleMonthlyReminderJob(
currentDeviceId,
deviceName,
reminderAt
);
return {
success: true,
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
};
} catch (err) {
console.error('Error on Monthly Reminder:', err);
throw err
}
}
async scheduleMonthlyReminderJob(deviceId, deviceName, reminderAt) {
try {
const now = dayjs().tz(this.timeZone);
const targetTime = reminderAt.clone()
.set('second', 0)
.set('millisecond', 0);
const nextRun = targetTime.format('YYYY-MM-DD HH:mm:ss');
console.log(`Reminder untuk ${deviceName} dijadwalkan pada ${nextRun}`);
console.log(`Reminder At: ${reminderAt.format('YYYY-MM-DD HH:mm:ss')}`);
const timeoutId = setTimeout(async () => {
console.log(`Waktu pengiriman tiba untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
try {
await this.sendMonthlyReminderNow(deviceId, deviceName, reminderAt);
} catch (error) {
console.error(`Gagal mengirim reminder untuk ${deviceName}:`, error);
}
});
this.cronJobs.set(deviceId, {
timeoutId,
nextRun,
reminderAt: reminderAt.format('YYYY-MM-DD HH:mm:ss')
});
const cronExpression = `${reminderAt.minute()} ${reminderAt.hour()} * * *`;
console.log(`Backup cron akan berjalan setiap hari pada ${reminderAt.hour()}:${reminderAt.minute()}`);
const cronTask = cron.schedule(cronExpression, async () => {
console.log(`Backup cron job berjalan untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
try {
const now = dayjs().tz(this.timeZone);
const isEndDatePassed = now.isAfter(reminderAt) || now.isSame(reminderAt);
if (isEndDatePassed) {
const currentMonth = now.month() + 1;
const checkNotifExist = await getReminderNotificationErrorByMonthlyDb(
parseInt(`${currentMonth}`),
currentMonth,
deviceId
);
if (!checkNotifExist) {
await this.sendMonthlyReminderNow(deviceId, deviceName, reminderAt);
} else {
console.log(`Reminder untuk ${deviceName} sudah pernah dikirim`);
}
cronTask.stop();
this.cronJobs.delete(`cron_${deviceId}`);
} else {
console.log(`Menunggu reminder untuk ${deviceName}: ${reminderAt.format('YYYY-MM-DD HH:mm:ss')}`);
}
} catch (error) {
console.error(`Backup cron job gagal untuk ${deviceName}:`, error);
}
}, {
timezone: this.timeZone
});
this.cronJobs.set(`cron_${deviceId}`, {
cronTask,
nextRun,
reminderAt: reminderAt.format('YYYY-MM-DD HH:mm:ss')
});
return {
nextRun,
targetDate: targetTime.format('YYYY-MM-DD HH:mm:ss'),
reminderAt: reminderAt.format('YYYY-MM-DD HH:mm:ss'),
cronExpression: cronExpression,
};
} catch (error) {
console.error('Error scheduling monthly reminder:', error);
throw error;
}
}
async sendMonthlyReminderNow(deviceId, deviceName, reminderAt) {
try {
const paramDb = {
limit: 100,
page: 1,
criteria: "",
active: true,
};
const now = dayjs().tz(this.timeZone);
const currentMonth = now.month() + 1;
const currentYear = now.year();
const monthlyCode = parseInt(`${currentMonth}`);
const checkNotifExist = await getReminderNotificationErrorByMonthlyDb(
monthlyCode,
currentMonth,
deviceId
);
if (checkNotifExist) {
return {
success: false,
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
};
}
const spareparts = await getSparepartsByMonthlyDb(currentMonth);
const sparepartList = spareparts && spareparts.length > 0
? "\n\nDaftar sparepart yang perlu diperiksa:\n" +
spareparts.map((sp, idx) => `${idx + 1}. ${sp.sparepart_name || 'Sparepart'}`).join('\n')
: "";
const data = {
error_code_id: monthlyCode,
error_chanel: 0,
is_send: 0,
is_delivered: 0,
is_read: 0,
is_active: 1,
message_error_issue: `reminder monthly device ${deviceName} in month ${currentMonth}`,
};
const resultNotificationError = await InsertNotificationErrorDb(data);
if (!resultNotificationError) {
return {
success: false,
message: 'Gagal menyimpan notifikasi error'
};
}
const results = await getAllContactDb(paramDb);
const dataUsers = results.data;
let isSendNotification = false;
let successCount = 0;
let failCount = 0;
for (const dataUser of dataUsers) {
if (dataUser.is_active) {
const tokenRedirect = await generateTokenRedirect(
dataUser.contact_phone,
dataUser.contact_name,
resultNotificationError.notification_error_id
);
const encodedToken = encodeURIComponent(tokenRedirect);
const shortUrl = await shortUrltiny(encodedToken);
const bodyMessage =
`Hai ${dataUser.contact_name || "-"},\n\n` +
`Diberitahukan bahwa terdapat sparepart pada device "${deviceName}" ` +
`yang telah memasuki jadwal perawatan bulanan untuk bulan ${currentMonth} pada tahun ${currentYear}.${sparepartList}\n\n` +
`Silakan segera lakukan pengecekan dan perawatan untuk memastikan kinerja tetap optimal.`
const param = {
idData: resultNotificationError.notification_error_id,
userPhone: dataUser.contact_phone,
userName: dataUser.contact_name,
bodyMessage: bodyMessage,
};
const resultNotificationErrorUser = await createNotificationErrorUserDb({
notification_error_id: param.idData,
contact_phone: param.userPhone,
contact_name: param.userName,
message_error_issue: param.bodyMessage,
is_send: false,
});
const resultSend = await sendNotifikasi(
param.userPhone,
param.bodyMessage
);
if (resultNotificationErrorUser && resultNotificationErrorUser.length > 0) {
await updateNotificationErrorUserDb(
resultNotificationErrorUser[0].notification_error_user_id,
{
is_send: resultSend.success,
}
);
}
if (resultSend.success) {
isSendNotification = true;
}
}
}
await updateNotificationErrorDb(
resultNotificationError.notification_error_id,
{
is_send: isSendNotification,
is_delivered: isSendNotification,
}
);
await this.saveReminder({
notification_log: resultNotificationError.notification_error_id,
error_code_id: data['error_code_id'],
error_chanel: data['error_chanel'],
start_at: now.format('HH:mm'),
interval: 1,
max: 3,
active: 1,
count: 0,
last_run: now.toISOString(),
last_run_indo: now.format('DD-MM-YYYY HH:mm:ss'),
next_run: null,
next_run_indo: null,
message: `Reminder monthly untuk ${deviceName} bulan ${currentMonth} telah dijalankan.`,
}, false);
this.stopCronJob(deviceId);
return {
success: true,
message: "Reminder has been sent.",
};
} catch (error) {
throw error;
}
}
async onCustomReminder(deviceId, inputStartDate, inputEndDate) {
try {
const paramDb = {
limit: 100,
page: 1,
criteria: "",
active: true,
};
if (!inputStartDate || !inputEndDate) {
return {
success: false,
message: 'Start Date dan End Date harus diisi. Format: YYYY-MM-DD HH:mm:ss'
};
}
const startDateObj = dayjs.tz(inputStartDate, this.timeZone);
const endDateObj = dayjs.tz(inputEndDate, this.timeZone);
if (!startDateObj.isValid() || !endDateObj.isValid()) {
return {
success: false,
message: 'Format tanggal Start Date dan End Date tidak valid. Gunakan format: YYYY-MM-DD HH:mm:ss'
};
}
if (!endDateObj.isAfter(startDateObj)) {
return {
success: false,
message: 'End Date harus lebih besar dari Start Date'
};
}
const deviceData = await getDeviceReminderCustomDb(deviceId);
if (!deviceData || deviceData.length === 0) {
return { success: false, message: 'Device tidak ditemukan' };
}
const device = deviceData[0];
const deviceName = device.device_name ?? '-';
const currentDeviceId = device.device_id;
const updateResult = await updateDeviceReminderCustomDb(
currentDeviceId,
inputStartDate,
inputEndDate
);
if (!updateResult || updateResult.length === 0) {
return {
success: false,
message: 'Gagal menyimpan start_date dan end_date'
};
}
this.stopCronJob(currentDeviceId);
const scheduleResult = await this.scheduleCustomReminderJob(
currentDeviceId,
deviceName,
startDateObj,
endDateObj
);
const now = dayjs().tz(this.timeZone);
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
if (isEndDatePassed) {
console.log(`⏰ End_date sudah terlewati, mengirim reminder sekarang untuk ${deviceName}`);
const sendResult = await this.sendCustomReminderNow(
currentDeviceId,
deviceName,
startDateObj,
endDateObj
);
return {
success: true,
message: 'Reminder berhasil dijadwalkan dan dikirim sekarang',
};
}
return {
success: true,
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
};
} catch (err) {
console.error('Error on Custom Reminder:', err);
throw err;
}
}
async scheduleCustomReminderJob(deviceId, deviceName, startDateObj, endDateObj) {
try {
const now = dayjs().tz(this.timeZone);
const targetTime = endDateObj.clone()
.set('second', 0)
.set('millisecond', 0);
const nextRun = targetTime.format('YYYY-MM-DD HH:mm:ss');
const timeoutId = setTimeout(async () => {
console.log(`Waktu pengiriman tiba untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
try {
const now = dayjs().tz(this.timeZone);
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
if (isEndDatePassed) {
await this.sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj);
}
} catch (err) {
throw err
}
});
this.cronJobs.set(deviceId, {
timeoutId,
nextRun,
startDate: startDateObj.format('YYYY-MM-DD HH:mm:ss'),
endDate: endDateObj.format('YYYY-MM-DD HH:mm:ss')
});
const endHour = endDateObj.hour();
const endMinute = endDateObj.minute();
const cronExpression = `${endMinute} ${endHour} * * *`;
const cronTask = cron.schedule(cronExpression, async () => {
try {
const now = dayjs().tz(this.timeZone);
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
if (isEndDatePassed) {
const currentMonth = now.month() + 1;
const checkNotifExist = await getReminderNotificationErrorByCustomDb(
parseInt(`${currentMonth}`),
currentMonth,
deviceId
);
if (!checkNotifExist) {
await this.sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj);
} else {
return {
success: false,
message: `Reminder untuk ${deviceName} sudah pernah dikirim`
};
}
cronTask.stop();
this.cronJobs.delete(deviceId);
this.cronJobs.delete(`cron_${deviceId}`);
}
} catch (err) {
throw err
}
}, {
timezone: this.timeZone
});
this.cronJobs.set(`cron_${deviceId}`, {
cronTask,
nextRun,
startDate: startDateObj.format('YYYY-MM-DD HH:mm:ss'),
endDate: endDateObj.format('YYYY-MM-DD HH:mm:ss')
});
return {
nextRun,
targetDate: targetTime.format('YYYY-MM-DD HH:mm:ss'),
endDate: endDateObj.format('YYYY-MM-DD HH:mm:ss'),
cronExpression: cronExpression
};
} catch (error) {
console.error('Error scheduling reminder:', error);
throw error;
}
}
async sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj) {
try {
const paramDb = {
limit: 100,
page: 1,
criteria: "",
active: true,
};
const now = dayjs().tz(this.timeZone);
const currentMonth = now.month() + 1;
const monthlyCode = parseInt(`${currentMonth}`);
const checkNotifExist = await getReminderNotificationErrorByCustomDb(
monthlyCode,
currentMonth,
deviceId
);
if (checkNotifExist) {
return {
success: false,
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
};
}
const data = {
error_code_id: monthlyCode,
error_chanel: 0,
is_send: 0,
is_delivered: 0,
is_read: 0,
is_active: 1,
message_error_issue: `reminder custom device ${deviceName} in month ${currentMonth}`,
};
const resultNotificationError = await InsertNotificationErrorDb(data);
const results = await getAllContactDb(paramDb);
const dataUsers = results.data;
let isSendNotification = false;
for (const dataUser of dataUsers) {
if (dataUser.is_active) {
const tokenRedirect = await generateTokenRedirect(
dataUser.contact_phone,
dataUser.contact_name,
resultNotificationError.notification_error_id
);
const encodedToken = encodeURIComponent(tokenRedirect);
const shortUrl = await shortUrltiny(encodedToken);
const bodyMessage =
`Hai ${dataUser.contact_name || "-"},\n\n` +
`Diberitahukan bahwa terdapat sparepart pada device "${deviceName}" ` +
`yang telah memasuki jadwal perawatan.\n\n` +
`Silakan segera lakukan pengecekan dan perawatan untuk memastikan kinerja tetap optimal.\n\n` +
`Detail Periode Perawatan:\n` +
`Start Date: ${startDateObj.format('DD-MM-YYYY HH:mm')}\n` +
`End Date: ${endDateObj.format('DD-MM-YYYY HH:mm')}\n`
const param = {
idData: resultNotificationError.notification_error_id,
userPhone: dataUser.contact_phone,
userName: dataUser.contact_name,
bodyMessage: bodyMessage,
};
const resultNotificationErrorUser = await createNotificationErrorUserDb({
notification_error_id: param.idData,
contact_phone: param.userPhone,
contact_name: param.userName,
message_error_issue: param.bodyMessage,
is_send: false,
});
const resultSend = await sendNotifikasi(
param.userPhone,
param.bodyMessage
);
if (resultNotificationErrorUser && resultNotificationErrorUser.length > 0) {
await updateNotificationErrorUserDb(
resultNotificationErrorUser[0].notification_error_user_id,
{
is_send: resultSend.success,
}
);
}
if (resultSend.success) {
isSendNotification = true;
}
}
}
await updateNotificationErrorDb(
resultNotificationError.notification_error_id,
{
is_send: isSendNotification,
is_delivered: isSendNotification,
}
);
await this.saveReminder({
notification_log: resultNotificationError.notification_error_id,
error_code_id: data['error_code_id'],
error_chanel: data['error_chanel'],
start_at: now.format('HH:mm'),
interval: 1,
max: 3,
active: 1,
count: 0,
last_run: now.toISOString(),
last_run_indo: now.format('DD-MM-YYYY HH:mm:ss'),
next_run: null,
next_run_indo: null,
message: `Reminder untuk ${deviceName} bulan ${currentMonth} telah dijalankan.`,
}, false);
this.stopCronJob(deviceId);
return { success: true, message: "Reminder has been sent." };
} catch (err) {
console.error('Error sending reminder now:', err);
throw err;
}
}
stopCronJob(deviceId) {
const jobData = this.cronJobs.get(deviceId);
if (jobData && jobData.timeoutId) {
clearTimeout(jobData.timeoutId);
console.log(`Timeout dihentikan untuk device ${deviceId}`);
}
const intervalData = this.cronJobs.get(`interval_${deviceId}`);
if (intervalData && intervalData.intervalId) {
clearInterval(intervalData.intervalId);
console.log(`Interval dihentikan untuk device ${deviceId}`);
}
const cronData = this.cronJobs.get(`cron_${deviceId}`);
if (cronData && cronData.cronTask) {
cronData.cronTask.stop();
console.log(`Cron job dihentikan untuk device ${deviceId}`);
}
this.cronJobs.delete(deviceId);
this.cronJobs.delete(`cron_${deviceId}`);
this.cronJobs.delete(`interval_${deviceId}`);
}
async restartWhatsapp() { async restartWhatsapp() {
try { try {
@@ -602,19 +1287,18 @@ class NotifikasiWaService {
const endJSON = cleanJSON.lastIndexOf(']') + 1; const endJSON = cleanJSON.lastIndexOf(']') + 1;
if (startJSON === -1 || endJSON === 0) { if (startJSON === -1 || endJSON === 0) {
throw new Error(`Terminal tidak mengembalikan JSON yang valid. Output: ${stdout}`); console.error(`Terminal tidak mengembalikan JSON yang valid. Output: ${stdout}`);
} }
const index = cleanJSON.slice(startJSON, endJSON); const index = cleanJSON.slice(startJSON, endJSON);
const processes = JSON.parse(index); const processes = JSON.parse(index);
const waProcess = processes.find((p) => p.name === processName); const waProcess = processes.find((p) => p.name === processName);
if (!waProcess) throw new Error(`PM2 proses dengan nama "${processName}" tidak ditemukan!`); if (!waProcess) console.error(`PM2 proses dengan nama ${processName} tidak ditemukan`);
const waProcessId = waProcess.pm_id; const waProcessId = waProcess.pm_id;
const pathDelete = waProcess.pm2_env.pm_cwd; const pathDelete = waProcess.pm2_env.pm_cwd;
// console.log(`stop proses id: ${waProcessId}`);
await execPromise(`pm2 stop ${waProcessId}`); await execPromise(`pm2 stop ${waProcessId}`);
const pathFolderDelete = [ const pathFolderDelete = [
@@ -622,8 +1306,6 @@ class NotifikasiWaService {
path.join(pathDelete, ".wwebjs_cache"), path.join(pathDelete, ".wwebjs_cache"),
]; ];
// console.log(`path: ${pathDelete}`);
for (const dir of pathFolderDelete) { for (const dir of pathFolderDelete) {
try { try {
await fs.access(dir); await fs.access(dir);
@@ -637,12 +1319,19 @@ class NotifikasiWaService {
} }
} }
// console.log(`start proses id: ${waProcessId}`);
await execPromise(`pm2 start ${waProcessId}`); await execPromise(`pm2 start ${waProcessId}`);
return { success: true, message: "WhatsApp has been restarted." }; return {
success: true,
message: "WhatsApp has been restarted."
};
} catch (err) { } catch (err) {
return { success: false, error: err.message || err }; return {
success: false,
message: `Gagal mengirim Whatsapp`
};
throw err
} }
} }
} }

View File

@@ -28,7 +28,10 @@ class SparepartService {
throw new ErrorHandler(404, "Sparepart not found"); throw new ErrorHandler(404, "Sparepart not found");
} }
sparepart[0].sparepart_yearly = JSON.parse(sparepart[0].sparepart_yearly); if (sparepart[0]) {
if (sparepart[0].sparepart_yearly) sparepart[0].sparepart_yearly = JSON.parse(sparepart[0].sparepart_yearly);
if (sparepart[0].sparepart_monthly) sparepart[0].sparepart_monthly = JSON.parse(sparepart[0].sparepart_monthly);
}
return sparepart[0]; return sparepart[0];
} catch (error) { } catch (error) {
@@ -49,6 +52,10 @@ class SparepartService {
data.sparepart_yearly = JSON.stringify(data.sparepart_yearly); data.sparepart_yearly = JSON.stringify(data.sparepart_yearly);
} }
if (data.sparepart_monthly) {
data.sparepart_monthly = JSON.stringify(data.sparepart_monthly);
}
const created = await createSparepartDb(data); const created = await createSparepartDb(data);
if (!created) throw new ErrorHandler(500, "Failed to create Sparepart"); if (!created) throw new ErrorHandler(500, "Failed to create Sparepart");
return created; return created;
@@ -70,14 +77,17 @@ class SparepartService {
data.sparepart_number, data.sparepart_number,
id id
); );
if (exists)
throw new ErrorHandler(400, "Sparepart name already exists");
} }
if (data.sparepart_yearly) { if (data.sparepart_yearly) {
data.sparepart_yearly = JSON.stringify(data.sparepart_yearly); data.sparepart_yearly = JSON.stringify(data.sparepart_yearly);
} }
if (data.sparepart_monthly) {
data.sparepart_monthly = JSON.stringify(data.sparepart_monthly);
}
const updated = await updateSparepartDb(id, data); const updated = await updateSparepartDb(id, data);
if (!updated) throw new ErrorHandler(500, "Failed to update Sparepart"); if (!updated) throw new ErrorHandler(500, "Failed to update Sparepart");
return await this.getSparepartById(id); return await this.getSparepartById(id);

View File

@@ -13,7 +13,8 @@ const insertContactSchema = Joi.object({
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX", "Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
}), }),
is_active: Joi.boolean().required(), is_active: Joi.boolean().required(),
contact_type: Joi.string().max(255).optional().allow(null) contact_type: Joi.string().max(255).optional().allow(null),
email: Joi.string().email().optional().allow(null)
}); });
const updateContactSchema = Joi.object({ const updateContactSchema = Joi.object({
@@ -26,7 +27,8 @@ const updateContactSchema = Joi.object({
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX", "Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
}), }),
is_active: Joi.boolean().optional(), is_active: Joi.boolean().optional(),
contact_type: Joi.string().max(255).optional().allow(null) contact_type: Joi.string().max(255).optional().allow(null),
email: Joi.string().email().optional().allow(null)
}); });
module.exports = { module.exports = {

View File

@@ -19,6 +19,9 @@ const insertDeviceSchema = Joi.object({
listen_channel: Joi.string().max(100).required(), listen_channel: Joi.string().max(100).required(),
listen_channel_reminder: Joi.string().max(100).allow('', null), listen_channel_reminder: Joi.string().max(100).allow('', null),
reminder_at: Joi.date().iso().allow('', null), reminder_at: Joi.date().iso().allow('', null),
reminder_at_monthly: Joi.date().iso().allow('', null),
start_date: Joi.date().iso().allow('', null),
end_date: Joi.date().iso().allow('', null),
}); });
const updateDeviceSchema = Joi.object({ const updateDeviceSchema = Joi.object({
@@ -35,6 +38,9 @@ const updateDeviceSchema = Joi.object({
listen_channel: Joi.string().max(100), listen_channel: Joi.string().max(100),
listen_channel_reminder: Joi.string().max(100).allow('', null), listen_channel_reminder: Joi.string().max(100).allow('', null),
reminder_at: Joi.date().iso().allow('', null), reminder_at: Joi.date().iso().allow('', null),
reminder_at_monthly: Joi.date().iso().allow('', null),
start_date: Joi.date().iso().allow('', null),
end_date: Joi.date().iso().allow('', null),
}).min(1); }).min(1);

View File

@@ -14,6 +14,11 @@ const insertSparepartSchema = Joi.object({
sparepart_merk: Joi.string().max(255).optional(), sparepart_merk: Joi.string().max(255).optional(),
sparepart_stok: Joi.string().max(255).optional(), sparepart_stok: Joi.string().max(255).optional(),
sparepart_yearly: Joi.array() sparepart_yearly: Joi.array()
.items(Joi.number().integer())
.min(0)
.allow(null)
.optional(),
sparepart_monthly: Joi.array()
.items(Joi.number().integer()) .items(Joi.number().integer())
.min(0) .min(0)
.allow(null) .allow(null)
@@ -33,11 +38,17 @@ const updateSparepartSchema = Joi.object({
sparepart_merk: Joi.string().max(255).optional(), sparepart_merk: Joi.string().max(255).optional(),
sparepart_stok: Joi.string().max(255).optional(), sparepart_stok: Joi.string().max(255).optional(),
sparepart_yearly: Joi.array() sparepart_yearly: Joi.array()
.items(Joi.number().integer())
.min(0)
.allow(null)
.optional(),
sparepart_monthly: Joi.array()
.items(Joi.number().integer()) .items(Joi.number().integer())
.min(0) .min(0)
.allow(null) .allow(null)
.optional() .optional()
}); })
module.exports = { module.exports = {
insertSparepartSchema, insertSparepartSchema,
updateSparepartSchema, updateSparepartSchema,