Compare commits

..

153 Commits

Author SHA1 Message Date
c09d51591d Merge pull request 'connect mqtt ws colo' (#38) from wisdom into main
Reviewed-on: #38
2026-01-08 08:10:02 +00:00
b680a249d5 connect mqtt ws colo 2026-01-08 15:07:47 +07:00
2a2df58b7d Merge pull request 'wisdom' (#37) from wisdom into main
Reviewed-on: #37
2026-01-08 07:43:58 +00:00
b1cf4ff624 optional solution error code 2026-01-08 14:32:43 +07:00
747a96ac30 fixing verify token redirect 2026-01-08 14:17:11 +07:00
026a88a9a9 remove validation at least 1 solution 2026-01-08 13:16:13 +07:00
ef491995f9 Merge pull request 'fixing verify access' (#36) from wisdom into main
Reviewed-on: #36
2026-01-08 05:38:22 +00:00
4d2c18edfb fixing verify access 2026-01-08 12:16:16 +07:00
d9975b832b Merge pull request 'add log in resend notif wa' (#35) from wisdom into main
Reviewed-on: #35
2026-01-08 04:51:46 +00:00
a4d8d55dbf add log in resend notif wa 2026-01-08 11:30:41 +07:00
205cb9d7cc Merge pull request 'Test push' (#34) from wisdom into main
Reviewed-on: #34
2026-01-08 03:48:11 +00:00
a6075174f5 Test push 2026-01-08 10:47:39 +07:00
41f5cc9011 Merge branch 'wisdom'
# Conflicts:
#	services/notification_error.service.js
2026-01-08 10:45:02 +07:00
3d163f4507 repair resend notif wa 2026-01-08 09:35:52 +07:00
bc265ccc33 repair resend notif wa 2026-01-08 09:35:18 +07:00
6885443bc2 repair resend notif wa 2026-01-08 09:32:20 +07:00
cecdc09719 fixing notification 2026-01-07 16:09:53 +07:00
f5494fb4a1 Merge pull request 'repair: resend wa' (#29) from wisdom into main
Reviewed-on: #29
2026-01-07 05:18:12 +00:00
2a25339478 repair: resend wa 2026-01-07 12:16:53 +07:00
ed77576958 Merge pull request 'repair: resend notif wa' (#28) from wisdom into main
Reviewed-on: #28
2026-01-07 05:01:44 +00:00
3faa3656c1 repair: resend notif wa 2026-01-07 11:59:27 +07:00
9e862d1a48 Merge pull request 'repair: service & controller notif and notif user' (#27) from wisdom into main
Reviewed-on: #27
2026-01-07 03:10:33 +00:00
aa7cd2fbaa repair: service & controller notif and notif user 2026-01-07 09:34:59 +07:00
9913724d08 Merge pull request 'wisdom' (#26) from wisdom into main
Reviewed-on: #26
2026-01-06 11:41:36 +00:00
f3abaeac39 repair: change error update is_read true to success 2026-01-06 16:28:37 +07:00
b025c5ea82 repair: body message wa in notif 2026-01-06 14:37:52 +07:00
63a646fce3 Merge pull request 'add: self-signed certificate' (#25) from wisdom into main
Reviewed-on: #25
2026-01-06 05:38:46 +00:00
6f4d171537 add: self-signed certificate 2026-01-06 11:39:33 +07:00
8d947a818b Merge pull request 'repair: change message wa notification' (#24) from wisdom into main
Reviewed-on: #24
2026-01-06 03:05:33 +00:00
71c5e94f42 repair: change message wa notification 2026-01-05 16:10:29 +07:00
81e07ed927 Merge pull request 'wisdom' (#23) from wisdom into main
Reviewed-on: #23
2026-01-05 07:06:16 +00:00
0c16b2a3fd add: is_send & updated_at in notif error user at notif error 2026-01-05 11:31:43 +07:00
402c1c0705 add: is_read & updated_at in notif error user at notif error 2026-01-05 11:25:25 +07:00
019c79d5bc Merge pull request 'wisdom' (#22) from wisdom into main
Reviewed-on: #22
2026-01-05 04:25:09 +00:00
adaa9fda9a repair: update is read in notification error 2026-01-05 10:08:53 +07:00
3eb403c557 repair: resend chat all user & by user 2026-01-04 19:20:43 +07:00
bedc948a74 add: params contact_phone and validation resend chat wa in notif error user 2026-01-01 18:31:09 +07:00
889aa04808 update is_read in notification error 2025-12-31 15:38:47 +07:00
25ba80ab7e add: resend chat wa notif error user 2025-12-31 15:11:34 +07:00
fae6bb7a43 Merge pull request 'repair: notification error log created_by' (#21) from wisdom into main
Reviewed-on: #21
2025-12-31 03:20:14 +00:00
a704eb3235 repair: notification error log created_by 2025-12-23 17:54:14 +07:00
8ecb00a4d3 Merge pull request 'wisdom' (#20) from wisdom into main
Reviewed-on: #20
2025-12-23 05:19:45 +00:00
10b7ac5e68 add: list user berdasarkan notifcation_error_id 2025-12-23 11:53:12 +07:00
37185a9fbc fixing redirect token wa 2025-12-22 17:23:22 +07:00
b62ca35185 Merge pull request 'wisdom' (#19) from wisdom into main
Reviewed-on: #19
2025-12-22 09:18:17 +00:00
c9dba276bb repair: notification_log 2025-12-18 17:32:21 +07:00
706fd401f4 rapair: info device notification error 2025-12-18 16:36:48 +07:00
518d6ff427 repair: detail notif get with error_channel 2025-12-18 16:19:46 +07:00
9f7a73e149 add: plant sub section name, device, brand name in detail notification 2025-12-18 15:18:20 +07:00
bba50177e9 repair: change readers to users 2025-12-18 14:38:58 +07:00
85750b397b repair: change readers to users in detail notification 2025-12-18 14:37:47 +07:00
Athif
1496b80fdf Update Value Report. 2025-12-18 13:37:47 +07:00
Albani Rajata Malik
c112ff165a update value report 2025-12-18 13:26:48 +07:00
5e7de6d144 delete: api is ready & not read 2025-12-18 13:04:57 +07:00
dd5e1cc713 add: api is read & not read in notification 2025-12-18 12:43:44 +07:00
1aa7b1bc08 add: reader in notification detail & update notification 2025-12-18 11:39:24 +07:00
f2c8c3818d repair: ErrorCode brand-device 2025-12-18 10:51:19 +07:00
907f5767c1 notification wa by mqtt broker 2025-12-18 10:05:50 +07:00
2b93baa648 add: crud notif error user 2025-12-09 16:30:19 +07:00
fb3061e0d1 add: add notification 2025-12-09 16:04:32 +07:00
d063478fc2 add: path icon & error code color in all notif error 2025-12-08 11:29:16 +07:00
555a68e90c repair: brand + errorcode 2025-12-05 18:18:50 +07:00
dc7712a79f add: sparepart in detail notification error 2025-12-05 09:21:04 +07:00
20d035a1ca add: sparepart in detail notification error 2025-12-05 09:13:41 +07:00
1d3de9ae41 repair: notification error sparepart 2025-12-04 16:07:04 +07:00
198346ff0b repair: device_description not required 2025-12-04 15:44:27 +07:00
a8eb785a5b repair get error code by brandId 2025-12-04 15:38:19 +07:00
096fe9461d add: field listen_channel m_device 2025-12-04 15:37:48 +07:00
31daa470b7 repair: notification error sparepart 2025-12-04 14:34:32 +07:00
be80206056 repair: notification error sparepart 2025-12-04 14:31:41 +07:00
73b4abfd68 repair: notification error sparepart 2025-12-04 14:30:57 +07:00
8b4cc89be5 repair: change mandatory to opsional 2025-12-04 09:28:39 +07:00
6fc21160f5 repair: get errorcodeby brand id 2025-12-04 00:51:41 +07:00
c8b2387e4f izin ubah be dikit 2025-12-03 16:45:24 +07:00
cecb88b838 update: delete path sollution 2025-12-03 16:15:18 +07:00
1ec69b388d repair: update sparepart_qty validation to allow zero 2025-12-03 13:27:18 +07:00
867976030a repair: get error code 2025-12-02 15:58:06 +07:00
790b949302 repair: error code detail 2025-12-02 15:29:43 +07:00
f797685a4f add: error_code api 2025-12-02 15:22:20 +07:00
feff905d8f repair: sparepart per error code 2025-12-02 14:45:29 +07:00
097030029f env imagekit 2025-12-02 10:45:40 +07:00
28e99c2a0d add: import , repair: change save local storage to imagekit 2025-12-02 10:44:07 +07:00
920b24bfd2 repair: brand device connect to sparepart 2025-12-01 10:35:25 +07:00
5e74122b9e Merge pull request 'wisdom' (#18) from wisdom into main
Reviewed-on: #18
2025-11-28 05:09:58 +00:00
462cf6e94b add: relation m_brand & m_sparepart 2025-11-28 00:32:17 +07:00
9926e2b181 repair: sparepart to brand device 2025-11-28 00:31:36 +07:00
fdb560985c repair: change mandatory to opsional 2025-11-27 13:51:51 +07:00
c9713910b3 repair: delete double api export 2025-11-26 09:10:03 +07:00
380864b1ab Merge branch 'wisdom' of https://gitea.idetama.id/yogiedigital/cod-api into wisdom 2025-11-25 14:58:44 +07:00
5a9ef3356d add: install package exceljs 2025-11-25 14:58:38 +07:00
662cf6f5f3 repair: notification error log 2025-11-25 14:56:49 +07:00
78a813e9ec add: notif error log 2025-11-25 11:59:44 +07:00
44107c9753 add: export excell sparepart 2025-11-25 11:58:57 +07:00
ca973d931f add: export excell sparepart 2025-11-25 11:52:51 +07:00
778d6f98e8 repair: get notif error byid 2025-11-25 11:49:53 +07:00
050543dbbf Merge pull request 'wisdom' (#17) from wisdom into main
Reviewed-on: #17
2025-11-25 03:50:08 +00:00
9dc165e15d repair: sparepart controller & service 2025-11-25 10:17:56 +07:00
70817df361 repair: sparepart service and controller 2025-11-25 10:16:05 +07:00
6de0d5d149 repair: notification error 2025-11-25 10:10:29 +07:00
fd07481fb0 repair: replace path_foto to sparepart_foto 2025-11-25 09:21:35 +07:00
8dcdddb42f repair: get detail sparepart 2025-11-24 16:59:16 +07:00
833b1bee82 crud: sparepart 2025-11-24 16:53:10 +07:00
8bab066dd0 crud: sparepart 2025-11-24 16:44:34 +07:00
4253e29889 repair: reset brand device without sparepart 2025-11-24 14:56:33 +07:00
e1b397e1d3 Merge pull request 'add brand id' (#16) from wisdom into main
Reviewed-on: #16
2025-11-20 03:42:49 +00:00
98a1b15669 add brand id 2025-11-19 15:53:10 +07:00
34db6b8d89 Merge pull request 'wisdom' (#15) from wisdom into main
Reviewed-on: #15
2025-11-19 01:04:37 +00:00
5e4a992834 repair: crud notification error sparepart 2025-11-18 13:50:23 +07:00
46c69aafa0 repair get notification error detail 2025-11-18 13:35:58 +07:00
919824bb41 crud: notification error sparepart 2025-11-18 13:13:55 +07:00
de5051bfaf fix: brand device service 2025-11-18 10:06:21 +07:00
5d1b6daef6 Merge pull request 'repair brand device: add brand sparepart in 2 step' (#14) from wisdom into main
Reviewed-on: #14
2025-11-18 00:25:14 +00:00
8176eb2bdd repair brand device: add brand sparepart in 2 step 2025-11-17 16:01:29 +07:00
30431be379 Merge pull request 'wisdom' (#13) from wisdom into main
Reviewed-on: #13
2025-11-17 08:27:07 +00:00
ff4176f8f9 repair: get all notification 2025-11-17 11:14:36 +07:00
ac68a380dd repair: message_error_issue 2025-11-14 18:32:24 +07:00
b8dd4a61f8 repair: get all notification 2025-11-14 08:53:58 +07:00
c8149c2359 crud: brand sparepart 2025-11-13 14:08:27 +07:00
342c06e49c crud: notification 2025-11-13 11:29:35 +07:00
d2d6ce2ab1 add: crud contact 2025-11-12 14:22:08 +07:00
361f750330 Update ecosystem.config.js 2025-11-04 06:14:58 +00:00
31f50d05ab Update .gitignore 2025-11-04 06:12:17 +00:00
961f0d6314 Update ecosystem.config.js 2025-11-04 05:50:27 +00:00
d87fc07a8e Update ecosystem.config.js 2025-11-04 05:46:55 +00:00
95e0c90a16 Merge pull request 'wisdom' (#11) from wisdom into main
Reviewed-on: #11
2025-10-28 09:46:55 +00:00
93b6b1b15e update, column error code color & path icon 2025-10-28 13:20:26 +07:00
d96cbd5e19 fixing api history event alarm 2025-10-28 12:24:52 +07:00
aa8aad94cf format number value history 2025-10-28 12:12:05 +07:00
55e8a6d9ca Merge pull request 'repair: params user_schedule' (#10) from wisdom into main
Reviewed-on: #10
2025-10-28 04:48:25 +00:00
a37906470b repair: params user_schedule 2025-10-27 13:27:08 +07:00
253d83357f Merge pull request 'add: tag_description in tags schema' (#9) from wisdom into main
Reviewed-on: #9
2025-10-27 04:07:05 +00:00
85fca5613e add: tag_description in tags schema 2025-10-27 11:04:11 +07:00
88a0404af0 Merge pull request 'wisdom' (#8) from wisdom into main
Reviewed-on: #8
2025-10-27 03:48:36 +00:00
85ee767451 api history report 2025-10-27 10:29:16 +07:00
afebb64e47 dummy pdf 2025-10-26 18:27:06 +07:00
cd77fda212 fix: file uploads api 2025-10-26 18:26:58 +07:00
a3b7f79546 update verify token 2025-10-26 18:26:38 +07:00
409e2d3750 fix: brand api 2025-10-26 18:26:22 +07:00
2fa263e9e4 api history list alarm 2025-10-25 23:50:49 +07:00
02a2561274 repair: json all user_schedule 2025-10-25 21:31:36 +07:00
d11207aedb Merge pull request 'wisdom' (#7) from wisdom into main
Reviewed-on: #7
2025-10-25 09:19:08 +00:00
3633590a8f fixing validate unit and tag 2025-10-25 15:35:15 +07:00
Muhammad Afif
3b9f3474a6 repair json body user_schedule and validasi user_id tidak boleh sama di satu shift_id 2025-10-24 16:21:20 +07:00
26f7420688 fix: plant sub section validate 2025-10-24 12:46:34 +07:00
d7044521bd Merge pull request 'wisdom' (#6) from wisdom into main
Reviewed-on: #6
2025-10-24 05:42:48 +00:00
ea2905d558 add: brand validate 2025-10-24 11:09:50 +07:00
893f177abd add: crud brand 2025-10-24 11:09:30 +07:00
3a95cdf315 add: uploads api 2025-10-24 10:54:26 +07:00
e2a008c2e1 Merge pull request 'wisdom' (#5) from wisdom into main
Reviewed-on: #5
2025-10-24 03:35:12 +00:00
6d575f649a Merge pull request 'wisdom' (#4) from wisdom into main
Reviewed-on: #4
2025-10-23 04:51:40 +00:00
e8fd307a05 Merge pull request 'wisdom' (#3) from wisdom into main
Reviewed-on: #3
2025-10-22 05:27:56 +00:00
00239db472 Merge pull request 'wisdom' (#2) from wisdom into main
Reviewed-on: #2
2025-10-20 03:26:32 +00:00
251f7148b6 Merge pull request 'wisdom' (#1) from wisdom into main
Reviewed-on: #1
2025-09-17 08:40:15 +00:00
78 changed files with 5700 additions and 127 deletions

View File

@@ -23,6 +23,11 @@ SECRET=secret
# JWT refresh secret
REFRESH_SECRET=refreshsecret
# IMAGEKIT
IMAGEKIT_URL_ENDPOINT=https://ik.imagekit.io/j0hxk7x3p
IMAGEKIT_PUBLIC_KEY=public_iMPQFBnXmdQy73TTB9w4SMQO4Jk=
IMAGEKIT_PRIVATE_KEY=private_vhO/jXHnEoaVYptOHIuZDPMbxIA=
# mail server settings
# SMTP_FROM=youremail
# SMTP_USER=youremail

3
.gitignore vendored
View File

@@ -3,4 +3,5 @@ node_modules
.vscode
request.http
*.rest
package-lock.json
package-lock.json
*.log

9
app.js
View File

@@ -8,7 +8,8 @@ const helmet = require("helmet");
const compression = require("compression");
const unknownEndpoint = require("./middleware/unKnownEndpoint");
const { handleError } = require("./helpers/error");
const { checkConnection } = require("./config");
const { checkConnection, mqttClient } = require("./config");
const { onNotification } = require("./services/notifikasi-wa.service");
const app = express();
@@ -47,4 +48,10 @@ app.get("/check-db", async (req, res) => {
app.use(unknownEndpoint);
app.use(handleError);
// Saat pesan diterima
mqttClient.on('message', (topic, message) => {
console.log(`Received message on topic "${topic}":`, message.toString());
onNotification(topic, message);
});
module.exports = app;

View File

@@ -1,8 +1,11 @@
require("dotenv").config();
const { default: mqtt } = require("mqtt");
const sql = require("mssql");
const isProduction = process.env.NODE_ENV === "production";
const endPointWhatsapp = process.env.ENDPOINT_WHATSAPP;
// Config SQL Server
const config = {
user: process.env.SQL_USERNAME,
@@ -101,7 +104,7 @@ function buildFilterQuery(filterQuery = [], fixedParams = []) {
queryParams.push(from);
queryParams.push(to);
whereConditions.push(
`${f.column} BETWEEN $${queryParams.length - 1} AND $${queryParams.length}`
`CAST(${f.column} AS DATE) BETWEEN $${queryParams.length - 1} AND $${queryParams.length}`
);
}
}
@@ -184,7 +187,6 @@ function buildDateFilter(column, type, dateValue, fixedParams = []) {
return { whereDateCondition: whereCondition, whereDateParams: queryParams };
}
/**
* Build dynamic UPDATE
*/
@@ -285,6 +287,34 @@ async function generateKode(prefix, tableName, columnName) {
return prefix + String(nextNumber).padStart(3, "0");
}
// Koneksi ke broker MQTT
const mqttOptions = {
clientId: 'express_mqtt_client_' + Math.random().toString(16).substr(2, 8),
clean: true,
connectTimeout: 4000,
username: 'morekmorekmorek', // jika ada
password: 'morek888', // jika ada
};
const mqttUrl = 'ws://117.102.231.130:7001'; // Ganti dengan broker kamu
const topic = process.env.TOPIC_COD ?? 'morek';
const mqttClient = mqtt.connect(mqttUrl, mqttOptions);
// Saat terkoneksi
mqttClient.on('connect', () => {
console.log('MQTT connected');
// Subscribe ke topik tertentu
mqttClient.subscribe(topic, (err) => {
if (!err) {
console.log(`Subscribed to topic "${topic}"`);
} else {
console.error('Subscribe error:', err);
}
});
});
module.exports = {
checkConnection,
query,
@@ -294,4 +324,6 @@ module.exports = {
buildDynamicInsert,
buildDynamicUpdate,
generateKode,
endPointWhatsapp,
mqttClient
};

View File

@@ -2,6 +2,9 @@ const AuthService = require('../services/auth.service');
const { setResponse, checkValidate } = require('../helpers/utils');
const { registerSchema, loginSchema } = require('../validate/auth.schema');
const { createCaptcha } = require('../utils/captcha');
const JWTService = require('../utils/jwt');
const CryptoJS = require('crypto-js');
class AuthController {
// Register
@@ -94,6 +97,42 @@ class AuthController {
const response = await setResponse({ svg, text }, 'Captcha generated');
res.status(response.statusCode).json(response);
}
static async verifyTokenRedirect(req, res) {
const { tokenRedirect } = req.body;
const bytes = CryptoJS.AES.decrypt(tokenRedirect, process.env.VITE_KEY_SESSION);
const decrypted = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
const userPhone = decrypted?.user_phone
const userName = decrypted?.user_name
const idData = decrypted?.id
const payload = {
user_id: userPhone,
user_fullname: userName,
};
const tokens = JWTService.generateTokenPair(payload);
// Simpan refresh token di cookie
res.cookie('refreshToken', tokens.refreshToken, {
httpOnly: true,
secure: false,
sameSite: 'lax',
maxAge: 7 * 24 * 60 * 60 * 1000
});
const response = await setResponse(
{
accessToken: tokens.accessToken,
idData
},
'Verify successful'
);
res.status(response.statusCode).json(response);
}
}
module.exports = AuthController;

View File

@@ -0,0 +1,77 @@
const BrandService = require('../services/brand.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const {
insertBrandSchema,
updateBrandSchema,
} = require('../validate/brand.schema');
class BrandController {
// Get all brands
static async getAll(req, res) {
const queryParams = req.query;
const results = await BrandService.getAllBrands(queryParams);
const response = await setResponsePaging(queryParams, results, 'Brand found');
res.status(response.statusCode).json(response);
}
// Get brand by ID
static async getById(req, res) {
const { id } = req.params;
const results = await BrandService.getBrandById(id);
// console.log('Brand response structure:', JSON.stringify(results, null, 2));
const response = await setResponse(results, 'Brand found');
res.status(response.statusCode).json(response);
}
// Create brand
static async create(req, res) {
const { error, value } = await checkValidate(insertBrandSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
value.created_by = req.user?.user_id || null;
const results = await BrandService.createBrand(value);
const response = await setResponse(results, 'Brand created successfully');
return res.status(response.statusCode).json(response);
}
// Update brand
static async update(req, res) {
const { id } = req.params;
const { error, value } = await checkValidate(updateBrandSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
value.updated_by = req.user?.user_id || null;
const results = await BrandService.updateBrand(id, value);
const response = await setResponse(results, 'Brand updated successfully');
res.status(response.statusCode).json(response);
}
// Soft delete brand by ID
static async delete(req, res) {
const { id } = req.params;
const results = await BrandService.deleteBrand(id, req.user.user_id);
const response = await setResponse(results, 'Brand deleted successfully');
res.status(response.statusCode).json(response);
}
}
module.exports = BrandController;

View File

@@ -0,0 +1,71 @@
const ContactService = require('../services/contact.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertContactSchema, updateContactSchema } = require('../validate/contact.schema');
class ContactController {
// Get all contact
static async getAll(req, res) {
const queryParams = req.query;
const results = await ContactService.getAllContact(queryParams);
const response = await setResponsePaging(queryParams, results, 'Contact found')
res.status(response.statusCode).json(response);
}
// Get contact by ID
static async getById(req, res) {
const { id } = req.params;
const results = await ContactService.getContactById(id);
const response = await setResponse(results, 'Contact found')
res.status(response.statusCode).json(response);
}
// Create contact
static async create(req, res) {
const { error, value } = await checkValidate(insertContactSchema, req)
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
value.userId = req.user.user_id
const results = await ContactService.createContact(value);
const response = await setResponse(results, 'Contact created successfully')
return res.status(response.statusCode).json(response);
}
// Update contact
static async update(req, res) {
const { id } = req.params;
const { error, value } = checkValidate(updateContactSchema, req)
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
value.userId = req.user.user_id
const results = await ContactService.updateContact(id, value);
const response = await setResponse(results, 'Contact updated successfully')
res.status(response.statusCode).json(response);
}
// Soft delete contact
static async delete(req, res) {
const { id } = req.params;
const results = await ContactService.deleteContact(id, req.user.user_id);
const response = await setResponse(results, 'Contact deleted successfully')
res.status(response.statusCode).json(response);
}
}
module.exports = ContactController;

View File

@@ -0,0 +1,74 @@
const ErrorCodeService = require('../services/error_code.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const {
insertErrorCodeSchema,
updateErrorCodeSchema,
} = require('../validate/error_code.schema');
class ErrorCodeController {
static async getByBrandId(req, res) {
const { brandId } = req.params;
const queryParams = req.query;
const results = await ErrorCodeService.getErrorCodesByBrandId(brandId, queryParams);
const response = await setResponsePaging(queryParams, results, 'Error codes found');
res.status(response.statusCode).json(response);
}
// Get error code by ID
static async getById(req, res) {
const { id } = req.params;
const result = await ErrorCodeService.getErrorCodeById(id);
const response = setResponse(result, 'Error code found');
res.status(response.statusCode).json(response);
}
// Create error code with solutions and spareparts
static async create(req, res) {
const { error, value } = await checkValidate(insertErrorCodeSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
const { brandId } = req.params;
value.created_by = req.user?.user_id || null;
const result = await ErrorCodeService.createErrorCodeWithFullData(brandId, value);
const response = setResponse(result, 'Error code created successfully');
res.status(response.statusCode).json(response);
}
// Update error code with solutions and spareparts
static async update(req, res) {
const { error, value } = await checkValidate(updateErrorCodeSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
const { brandId, errorCodeId } = req.params;
value.updated_by = req.user?.user_id || null;
const result = await ErrorCodeService.updateErrorCodeWithFullData(brandId, errorCodeId, value);
const response = setResponse(result, 'Error code updated successfully');
res.status(response.statusCode).json(response);
}
// Soft delete error code
static async delete(req, res) {
const { brandId, errorCodeId } = req.params;
const deletedBy = req.user?.user_id || null;
const result = await ErrorCodeService.deleteErrorCode(brandId, errorCodeId, deletedBy);
const response = setResponse(result, 'Error code deleted successfully');
res.status(response.statusCode).json(response);
}
}
module.exports = ErrorCodeController;

View File

@@ -0,0 +1,117 @@
const path = require("path");
const fs = require("fs");
const { setResponse } = require("../helpers/utils");
const {
createFileUploadDb,
deleteFileUploadByPathDb,
} = require("../db/file_uploads.db");
const uploadFile = async (req, res) => {
try {
if (!req.file) {
const response = await setResponse([], "Tidak ada file yang diunggah", 400);
return res.status(400).json(response);
}
const file = req.file;
const ext = path.extname(file.originalname).toLowerCase();
const typeDoc = ext === ".pdf" ? "PDF" : "IMAGE";
const folder = typeDoc === "PDF" ? "pdf" : "images";
const pathDocument = `${folder}/${file.filename}`;
const fileData = {
file_upload_name: file.originalname,
path_document: pathDocument,
type_document: typeDoc,
createdBy: req.user?.user_id || null,
};
await createFileUploadDb(fileData);
const response = await setResponse(
{
file_upload_name: file.originalname,
path_document: pathDocument
},
"File berhasil diunggah"
);
res.status(200).json(response);
} catch (error) {
const response = await setResponse([], error.message, 500);
res.status(500).json(response);
}
};
const getFileByPath = async (req, res) => {
try {
const { folder, filename } = req.params;
// Decode filename from URL encoding
const decodedFilename = decodeURIComponent(filename);
const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);
console.log('getFileByPath Debug:', {
folder,
originalFilename: filename,
decodedFilename,
filePath
});
if (!fs.existsSync(filePath)) {
console.log('File not found at path:', filePath);
// try {
// const folderPath = path.join(__dirname, "../uploads", folder);
// const availableFiles = fs.readdirSync(folderPath);
// console.log('Available files in', folderPath, ':', availableFiles);
// } catch (listError) {
// console.log('Could not list files in folder:', listError.message);
// }
const response = await setResponse([], "File tidak ditemukan", 404);
return res.status(404).json(response);
}
res.sendFile(filePath);
} catch (error) {
console.error('getFileByPath Error:', error);
const response = await setResponse([], error.message, 500);
res.status(500).json(response);
}
};
const deleteFileByPath = async (req, res) => {
try {
const { folder, filename } = req.params;
// Decode filename from URL encoding
const decodedFilename = decodeURIComponent(filename);
const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);
if (!fs.existsSync(filePath)) {
const response = await setResponse([], "File tidak ditemukan", 404);
return res.status(404).json(response);
}
// Delete physical file
fs.unlinkSync(filePath);
const pathDocument = `${folder}/${decodedFilename}`;
const deletedBy = req.user?.user_id || null;
await deleteFileUploadByPathDb(pathDocument, deletedBy);
const response = await setResponse([], "File berhasil dihapus");
res.status(200).json(response);
} catch (error) {
const response = await setResponse([], error.message, 500);
res.status(500).json(response);
}
};
module.exports = {
uploadFile,
getFileByPath,
deleteFileByPath,
};

View File

@@ -0,0 +1,105 @@
const HistoryValue = require('../services/history_value.service');
const { setResponsePaging } = require('../helpers/utils');
class HistoryValueController {
static async getAllHistoryAlarm(req, res) {
try {
const queryParams = req.query;
const results = await HistoryValue.getAllHistoryAlarm(queryParams);
const response = await setResponsePaging(queryParams, results, 'Data found');
res.status(response.statusCode).json(response);
} catch (error) {
const statusCode = error.statusCode || 500;
res.status(statusCode).json({
success: false,
statusCode,
message: error.message || 'Internal server error'
});
}
}
static async getAllHistoryEvent(req, res) {
try {
const queryParams = req.query;
const results = await HistoryValue.getAllHistoryEvent(queryParams);
const response = await setResponsePaging(queryParams, results, 'Data found');
res.status(response.statusCode).json(response);
} catch (error) {
const statusCode = error.statusCode || 500;
res.status(statusCode).json({
success: false,
statusCode,
message: error.message || 'Internal server error'
});
}
}
static async getHistoryValueReport(req, res) {
try {
const queryParams = req.query;
const results = await HistoryValue.getHistoryValueReport(queryParams);
const response = await setResponsePaging(queryParams, results, 'Data found');
res.status(response.statusCode).json(response);
} catch (error) {
const statusCode = error.statusCode || 500;
res.status(statusCode).json({
success: false,
statusCode,
message: error.message || 'Internal server error'
});
}
}
static async getHistoryValueReportPivot(req, res) {
try {
const queryParams = req.query;
const results = await HistoryValue.getHistoryValueReportPivot(queryParams);
const response = await setResponsePaging(queryParams, results, 'Data found');
if (results.column) {
response.columns = results.column;
}
res.status(response.statusCode).json(response);
} catch (error) {
const statusCode = error.statusCode || 500;
res.status(statusCode).json({
success: false,
statusCode,
message: error.message || 'Internal server error'
});
}
}
static async getHistoryValueTrendingPivot(req, res) {
try {
const queryParams = req.query;
const results = await HistoryValue.getHistoryValueTrendingPivot(queryParams);
const response = await setResponsePaging(queryParams, results, 'Data found');
if (results.column) {
response.columns = results.column;
}
res.status(response.statusCode).json(response);
} catch (error) {
const statusCode = error.statusCode || 500;
res.status(statusCode).json({
success: false,
statusCode,
message: error.message || 'Internal server error'
});
}
}
}
module.exports = HistoryValueController;

View File

@@ -0,0 +1,88 @@
const NotificationErrorService = require("../services/notification_error.service");
const {
setResponse,
setResponsePaging,
checkValidate,
} = require("../helpers/utils");
const {
insertNotificationSchema,
updateNotificationSchema,
} = require("../validate/notification.schema");
class NotificationErrorController {
static async getAll(req, res) {
const queryParams = req.query;
const results = await NotificationErrorService.getAllNotification(
queryParams
);
const response = await setResponsePaging(
queryParams,
results,
"Notification found"
);
res.status(response.statusCode).json(response);
}
static async getById(req, res) {
const { id } = req.params;
const results = await NotificationErrorService.getNotificationById(id);
const response = await setResponse(
results,
"Notification retrieved successfully"
);
return res.status(response.statusCode).json(response);
}
static async create(req, res) {
const { error, value } = await checkValidate(insertNotificationSchema, req);
if (error) {
return res.status(400).json(setResponse(error, "Validation failed", 400));
}
value.userId = req.user.user_id;
const results = await NotificationErrorService.createNotificationError(
value
);
const response = await setResponse(
results,
"Notification created successfully"
);
return res.status(response.statusCode).json(response);
}
static async update(req, res) {
const { id } = req.params;
const userId = req.user.user_id;
const results = await NotificationErrorService.updateNotificationError(
id,
userId
);
const response = await setResponse(
results,
"Notification Error updated successfully"
);
res.status(response.statusCode).json(response);
}
static async resend(req, res) {
const { id } = req.params;
const results = await NotificationErrorService.resendNotification(id);
const response = await setResponse(
results,
"Notification Error resend successfully"
);
res.status(response.statusCode).json(response);
}
}
module.exports = NotificationErrorController;

View File

@@ -0,0 +1,69 @@
const NotificationErrorLogService = require('../services/notification_error_log.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertNotificationErrorLogSchema } = require('../validate/notification_error_log.schema');
class NotificationErrorLogController {
// Get all notification error logs
static async getAll(req, res) {
try {
const results = await NotificationErrorLogService.getAllNotificationErrorLog();
const response = await setResponse(results, 'Notification Error Logs found')
res.status(response.statusCode).json(response);
} catch (error) {
const response = await setResponse(error, error.message, error.statusCode || 500);
res.status(response.statusCode).json(response);
}
}
// Get notification error log by ID
static async getById(req, res) {
try {
const { id } = req.params;
const results = await NotificationErrorLogService.getNotificationErrorLogById(id);
const response = await setResponse(results, 'Notification Error Log found')
res.status(response.statusCode).json(response);
} catch (error) {
const response = await setResponse(error, error.message, error.statusCode || 500);
res.status(response.statusCode).json(response);
}
}
// Get notification error logs by notification_error_id
static async getByNotificationErrorId(req, res) {
try {
const { id } = req.params;
const results = await NotificationErrorLogService.getNotificationErrorLogByNotificationErrorId(id);
const response = await setResponse(results, 'Notification Error Logs found')
res.status(response.statusCode).json(response);
} catch (error) {
const response = await setResponse(error, error.message, error.statusCode || 500);
res.status(response.statusCode).json(response);
}
}
// Create notification error log
static async create(req, res) {
try {
const { error, value } = await checkValidate(insertNotificationErrorLogSchema, req)
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
const results = await NotificationErrorLogService.createNotificationErrorLog(value, req.user.user_id);
const response = await setResponse(results, 'Notification Error Log created successfully')
return res.status(response.statusCode).json(response);
} catch (error) {
const response = await setResponse(error, error.message, error.statusCode || 500);
return res.status(response.statusCode).json(response);
}
}
}
module.exports = NotificationErrorLogController;

View File

@@ -0,0 +1,62 @@
const NotificationErrorSparepart = require('../services/notification_error_sparepart.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { updateNotificationErrorSparepartSchema, insertNotificationErrorSparepartSchema } = require('../validate/notification_error_sparepart.schema');
class NotificationErrorSparepartController {
static async getAll(req, res) {
const { contact_id } = req.body;
const queryParams = req.query;
const results = await NotificationErrorSparepart.getAll(queryParams, contact_id);
const response = await setResponsePaging(queryParams, results, 'Notification Error Sparepart found');
res.status(response.statusCode).json(response);
}
static async getById(req, res) {
const { id } = req.params;
const results = await NotificationErrorSparepart.getById(id);
const response = await setResponse(results, 'Notification Error Sparepart found');
res.status(response.statusCode).json(response);
}
static async create(req, res) {
const { error, value } = await checkValidate(insertNotificationErrorSparepartSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
const results = await NotificationErrorSparepart.create(value);
const response = await setResponse(results, 'Notification Error Sparepart created successfully');
res.status(response.statusCode).json(response);
}
static async update(req, res) {
const { id } = req.params;
const { error, value } = await checkValidate(updateNotificationErrorSparepartSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
const results = await NotificationErrorSparepart.update(id, value);
const response = await setResponse(results, 'Notification Error Sparepart updated successfully');
res.status(response.statusCode).json(response);
}
static async delete(req, res) {
const { id } = req.params;
const { contact_id } = req.body;
const results = await NotificationErrorSparepart.delete(id, contact_id);
const response = await setResponse(results, 'Notification Error Sparepart deleted successfully');
res.status(response.statusCode).json(response);
}
}
module.exports = NotificationErrorSparepartController;

View File

@@ -0,0 +1,123 @@
const NotificationErrorUserService = require("../services/notification_error_user.service");
const {
setResponse,
setResponsePaging,
checkValidate,
} = require("../helpers/utils");
const {
insertNotificationErrorUserSchema,
updateNotificationErrorUserSchema,
} = require("../validate/notification_error_user.schema");
class NotificationErrorUserController {
// Get all NotificationErrorUser
static async getAll(req, res) {
const queryParams = req.query;
const results =
await NotificationErrorUserService.getAllNotificationErrorUser(
queryParams
);
const response = await setResponsePaging(
queryParams,
results,
"Notification Error User found"
);
res.status(response.statusCode).json(response);
}
// Get NotificationErrorUser by ID
static async getById(req, res) {
const { id } = req.params;
const results =
await NotificationErrorUserService.getNotificationErrorUserById(id);
const response = await setResponse(
results,
"Notification Error User found"
);
res.status(response.statusCode).json(response);
}
// Create NotificationErrorUser
static async create(req, res) {
const { error, value } = await checkValidate(
insertNotificationErrorUserSchema,
req
);
if (error) {
return res.status(400).json(setResponse(error, "Validation failed", 400));
}
value.userId = req.user.user_id;
const results =
await NotificationErrorUserService.createNotificationErrorUser(value);
const response = await setResponse(
results,
"Notification Error User created successfully"
);
return res.status(response.statusCode).json(response);
}
// Update NotificationErrorUser
static async update(req, res) {
const { id } = req.params;
const { error, value } = checkValidate(
updateNotificationErrorUserSchema,
req
);
if (error) {
return res.status(400).json(setResponse(error, "Validation failed", 400));
}
value.userId = req.user.user_id;
const results =
await NotificationErrorUserService.updateNotificationErrorUser(id, value);
const response = await setResponse(
results,
"Notification Error User updated successfully"
);
res.status(response.statusCode).json(response);
}
// Soft delete Notification Error User
static async delete(req, res) {
const { id } = req.params;
const results =
await NotificationErrorUserService.deleteNotificationErrorUser(
id,
req.user.user_id
);
const response = await setResponse(
results,
"Notification Error User deleted successfully"
);
res.status(response.statusCode).json(response);
}
static async resendByUser(req, res) {
const { id, contact_phone } = req.params;
const results = await NotificationErrorUserService.resendNotificationByUser(
id,
contact_phone
);
const response = await setResponse(
results,
"Notification Error By User resend successfully"
);
res.status(response.statusCode).json(response);
}
}
module.exports = NotificationErrorUserController;

View File

@@ -1,6 +1,6 @@
const SubSectionService = require('../services/plant_sub_section.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertSubSectionSchema, updateSubSectionSchema } = require('../validate/sub_section.schema');
const { insertSubSectionSchema, updateSubSectionSchema } = require('../validate/plant_sub_section.schema');
class SubSectionController {
// Get all sub sections

View File

@@ -0,0 +1,327 @@
const ExcelJS = require("exceljs");
const path = require("path");
const ImageKit = require("imagekit");
const imagekit = new ImageKit({
publicKey: process.env.IMAGEKIT_PUBLIC_KEY,
privateKey: process.env.IMAGEKIT_PRIVATE_KEY,
urlEndpoint: process.env.IMAGEKIT_URL_ENDPOINT,
});
const SparepartService = require("../services/sparepart.service");
const {
setResponse,
setResponsePaging,
checkValidate,
} = require("../helpers/utils");
const {
insertSparepartSchema,
updateSparepartSchema,
} = require("../validate/sparepart.schema");
class SparepartController {
static async getAll(req, res) {
const queryParams = req.query;
const results = await SparepartService.getAllSparepart(queryParams);
const response = await setResponsePaging(
queryParams,
results,
"Sparepart found"
);
res.status(response.statusCode).json(response);
}
static async getById(req, res) {
const { id } = req.params;
const results = await SparepartService.getSparepartById(id);
const response = await setResponse(results, "Sparepart found");
res.status(response.statusCode).json(response);
}
static async create(req, res) {
const { error, value } = await checkValidate(insertSparepartSchema, req);
if (error) {
return res.status(400).json(setResponse(error, "Validation failed", 400));
}
try {
if (req.file) {
const upload = await imagekit.upload({
file: req.file.buffer,
fileName: req.file.originalname,
folder: "/sparepart",
});
value.sparepart_foto = upload.url;
}
value.userId = req.user.user_id;
const results = await SparepartService.createSparepart(value);
return res
.status(201)
.json(setResponse(results, "Sparepart created successfully"));
} catch (err) {
return res
.status(err.statusCode || 500)
.json(setResponse([], err.message, err.statusCode || 500));
}
}
static async update(req, res) {
const { id } = req.params;
const { error, value } = await checkValidate(updateSparepartSchema, req);
if (error) {
return res.status(400).json(setResponse(error, "Validation failed", 400));
}
try {
if (req.file) {
const upload = await imagekit.upload({
file: req.file.buffer,
fileName: req.file.originalname,
folder: "/sparepart",
});
value.sparepart_foto = upload.url;
}
value.userId = req.user.user_id;
const results = await SparepartService.updateSparepart(id, value);
return res
.status(200)
.json(setResponse(results, "Sparepart updated successfully"));
} catch (err) {
return res
.status(err.statusCode || 500)
.json(setResponse([], err.message, err.statusCode || 500));
}
}
static async exportExcel(req, res) {
try {
const queryParams = req.query || {};
queryParams.limit = null;
const results = await SparepartService.getAllSparepart(queryParams);
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet("Sparepart Data");
worksheet.columns = [
{ header: "Name Sparepart", key: "sparepart_name", width: 30 },
{ header: "Code Sparepart", key: "sparepart_code", width: 20 },
{ header: "QTY Sparepart", key: "sparepart_qty", width: 15 },
{ header: "Merk", key: "sparepart_merk", width: 20 },
{ header: "Model", key: "sparepart_model", width: 20 },
{ header: "Unit", key: "sparepart_unit", width: 10 },
{ header: "Stock", key: "sparepart_stok", width: 10 },
{ header: "Foto", key: "sparepart_foto", width: 25 },
{ header: "Item Type", key: "sparepart_item_type", width: 25 },
{ header: "Dibuat Pada", key: "created_at", width: 20 },
];
worksheet.addRows(
results.data.map((item) => ({
...item,
sparepart_foto: "",
}))
);
for (let i = 0; i < results.data.length; i++) {
const item = results.data[i];
const rowNumber = i + 2;
if (!item.sparepart_foto) continue;
let imageUrl = item.sparepart_foto;
if (!imageUrl.startsWith("https")) continue;
let ext = path.extname(imageUrl).toLowerCase().replace(".", "");
if (!ext) ext = "jpg";
const supported = ["jpg", "jpeg", "png"];
if (!supported.includes(ext)) {
ext = "png";
}
let buffer;
try {
const resp = await fetch(imageUrl);
buffer = Buffer.from(await resp.arrayBuffer());
} catch (e) {
continue;
}
const imageId = workbook.addImage({
buffer,
extension: ext === "jpg" ? "jpeg" : ext,
});
worksheet.addImage(imageId, {
tl: { col: 7, row: rowNumber - 1 },
ext: { width: 80, height: 80 },
});
worksheet.getRow(rowNumber).height = 70;
}
worksheet.getRow(1).eachCell((cell) => {
cell.font = { bold: true };
cell.alignment = { horizontal: "center" };
});
const buffer = await workbook.xlsx.writeBuffer();
res.setHeader(
"Content-Type",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
res.setHeader(
"Content-Disposition",
"attachment; filename=sparepart_data.xlsx"
);
return res.send(buffer);
} catch (error) {
return res.status(500).json({ message: error.message });
}
}
static async importExcel(req, res) {
try {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load(req.file.buffer);
const worksheet = workbook.getWorksheet(1);
const images = worksheet.getImages();
const imageMap = {};
images.forEach((imgObj) => {
const imageId = imgObj.imageId;
const range = imgObj.range;
const row = range.tl.nativeRow + 1;
const image = workbook.getImage(imageId);
imageMap[row] = image;
});
const spareparts = [];
worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
if (rowNumber === 1) return;
const [
sparepart_name,
sparepart_code,
sparepart_description,
sparepart_qty_excel,
sparepart_merk,
sparepart_model,
sparepart_unit,
sparepart_stok_excel,
sparepart_foto_excel,
sparepart_item_type,
] = row.values.slice(1);
if (!sparepart_name) return;
if (!sparepart_code) {
return;
}
spareparts.push({
sparepart_name: sparepart_name || "",
sparepart_code: sparepart_code || "",
sparepart_description: sparepart_description || "",
sparepart_qty: Number(sparepart_qty_excel) || 0,
sparepart_merk: sparepart_merk || "",
sparepart_model: sparepart_model || "",
sparepart_unit: sparepart_unit || "",
sparepart_stok: sparepart_stok_excel || "",
sparepart_foto: sparepart_foto_excel || "",
sparepart_item_type: sparepart_item_type || "",
rowNumber,
});
});
if (spareparts.length === 0) {
return res
.status(400)
.json(setResponse([], "Tidak ada data valid untuk diimport", 400));
}
const results = [];
for (const data of spareparts) {
let uploadedUrl = "";
try {
const image = imageMap[data.rowNumber];
if (image) {
const fileName = `sparepart_${Date.now()}_${
data.sparepart_code
}.jpg`;
const uploadResult = await imagekit.upload({
file: image.buffer,
fileName: fileName,
folder: "/sparepart",
});
uploadedUrl = uploadResult.url;
}
} catch (err) {
err;
}
data.sparepart_foto = uploadedUrl || "";
const { rowNumber, ...dbData } = data;
const created = await SparepartService.createSparepart(dbData);
if (created && created[0]) {
results.push({
sparepart_id: created[0].sparepart_id,
sparepart_name: created[0].sparepart_name,
sparepart_code: created[0].sparepart_code,
sparepart_description: created[0].sparepart_description,
sparepart_qty: created[0].sparepart_qty,
sparepart_merk: created[0].sparepart_merk,
sparepart_model: created[0].sparepart_model,
sparepart_unit: created[0].sparepart_unit,
sparepart_stok: created[0].sparepart_stok,
sparepart_foto: created[0].sparepart_foto,
sparepart_item_type: created[0].sparepart_item_type,
});
}
}
return res.json(
setResponse(results, `${results.length} Sparepart berhasil diimport`)
);
} catch (error) {
return res.status(500).json({ message: error.message });
}
}
static async delete(req, res) {
const { id } = req.params;
const results = await SparepartService.deleteSparepart(
id,
req.user.user_id
);
const response = await setResponse(
results,
"Sparepart deleted successfully"
);
res.status(response.statusCode).json(response);
}
}
module.exports = SparepartController;

View File

@@ -4,23 +4,28 @@ const pool = require("../config");
const getAllBrandsDb = async (searchParams = {}) => {
let queryParams = [];
// Pagination
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
// Search
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["b.brand_name"],
["a.brand_name", "a.brand_type", "a.brand_manufacture", "a.brand_model", "a.brand_code"],
searchParams.criteria,
queryParams
);
queryParams = whereParamOr ? whereParamOr : queryParams;
// Filter
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "b.brand_name", param: searchParams.name, type: "string" },
{ column: "b.created_by", param: searchParams.created_by, type: "number" },
{ column: "a.brand_type", param: searchParams.type, type: "string" },
{ column: "a.brand_manufacture", param: searchParams.manufacture, type: "string" },
{ column: "a.brand_model", param: searchParams.model, type: "string" },
{ column: "a.is_active", param: searchParams.status, type: "string" },
],
queryParams
);
@@ -28,49 +33,57 @@ const getAllBrandsDb = async (searchParams = {}) => {
queryParams = whereParamAnd ? whereParamAnd : queryParams;
const queryText = `
SELECT COUNT(*) OVER() AS total_data, b.*
FROM m_brands b
WHERE b.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? whereOrConditions : ""}
ORDER BY b.brand_id ASC
SELECT
COUNT(*) OVER() AS total_data,
a.*
FROM m_brands a
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
${whereOrConditions ? whereOrConditions : ''}
ORDER BY a.brand_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
const total =
result?.recordset.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
// Get brand by ID
const getBrandByIdDb = async (id) => {
// Get brand by name (path-based)
const getBrandByNameDb = async (brandName) => {
const queryText = `
SELECT b.*
FROM m_brands b
WHERE b.brand_id = $1 AND b.deleted_at IS NULL
SELECT
a.*
FROM m_brands a
WHERE a.brand_name = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
const result = await pool.query(queryText, [brandName]);
return result.recordset[0];
};
// Get brand by name
const getBrandByNameDb = async (name) => {
// Get brand by ID (for internal use)
const getBrandByIdDb = async (id) => {
const queryText = `
SELECT b.*
FROM m_brands b
WHERE b.brand_name = $1 AND b.deleted_at IS NULL
SELECT
a.*
FROM m_brands a
WHERE a.brand_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [name]);
const result = await pool.query(queryText, [id]);
return result.recordset[0];
};
// Create brand
const createBrandDb = async (data) => {
const newCode = await pool.generateKode("BRD", "m_brands", "brand_code");
const store = {
...data,
created_at: new Date(),
brand_code: newCode,
};
const { query: queryText, values } = pool.buildDynamicInsert("m_brands", store);
@@ -79,23 +92,17 @@ const createBrandDb = async (data) => {
return insertedId ? await getBrandByIdDb(insertedId) : null;
};
// Update brand
const updateBrandDb = async (id, data) => {
const store = {
...data,
updated_at: new Date(),
};
const whereData = {
brand_id: id,
};
// Update brand by name
const updateBrandDb = async (brandName, data) => {
const store = { ...data };
const whereData = { brand_name: brandName };
const { query: queryText, values } = pool.buildDynamicUpdate("m_brands", store, whereData);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getBrandByIdDb(id);
return getBrandByNameDb(brandName);
};
// Soft delete brand
// Soft delete brand
const deleteBrandDb = async (id, deletedBy) => {
const queryText = `
UPDATE m_brands
@@ -106,11 +113,31 @@ const deleteBrandDb = async (id, deletedBy) => {
return true;
};
// Check if brand name exists (for validation)
const checkBrandNameExistsDb = async (brandName, excludeId = null) => {
let queryText = `
SELECT brand_id
FROM m_brands
WHERE brand_name = $1 AND deleted_at IS NULL
`;
let values = [brandName];
if (excludeId) {
queryText += ` AND brand_id != $2`;
values.push(excludeId);
}
const result = await pool.query(queryText, values);
return result.recordset.length > 0;
};
module.exports = {
getAllBrandsDb,
getBrandByIdDb,
getBrandByNameDb,
getBrandByIdDb,
createBrandDb,
updateBrandDb,
deleteBrandDb,
};
checkBrandNameExistsDb,
};

174
db/brand_code.db.js Normal file
View File

@@ -0,0 +1,174 @@
const pool = require("../config");
// Get error codes by brand ID
const getErrorCodesByBrandIdDb = async (brandId, searchParams = {}) => {
let queryParams = [brandId];
// Pagination
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [brandId, Number(searchParams.limit ?? 10), page];
}
// Search across multiple columns
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["a.error_code", "a.error_code_name", "a.error_code_description"],
searchParams.criteria,
queryParams
);
queryParams = whereParamOr ? whereParamOr : queryParams;
// Filter conditions
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.is_active", param: searchParams.status, type: "string" },
],
queryParams
);
queryParams = whereParamAnd ? whereParamAnd : queryParams;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*
FROM brand_code a
WHERE a.brand_id = $1 AND a.deleted_at IS NULL
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
${whereOrConditions ? whereOrConditions : ''}
ORDER BY a.error_code_id DESC
${searchParams.limit ? `OFFSET $3 * $2 ROWS FETCH NEXT $2 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
// Return paginated format if limit is provided
if (searchParams.limit) {
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
return { data: result.recordset, total };
}
// Return simple array for backward compatibility
return result.recordset;
};
const createErrorCodeDb = async (brandId, data) => {
const store = {
brand_id: brandId,
error_code: data.error_code,
error_code_name: data.error_code_name,
error_code_description: data.error_code_description,
error_code_color: data.error_code_color,
path_icon: data.path_icon,
is_active: data.is_active,
created_by: data.created_by
};
const { query: queryText, values } = pool.buildDynamicInsert("brand_code", store);
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId;
};
const updateErrorCodeDb = async (brandId, errorCode, data) => {
const store = { ...data };
const whereData = {
brand_id: brandId,
error_code: errorCode
};
const { query: queryText, values } = pool.buildDynamicUpdate("brand_code", store, whereData);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return true;
};
const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => {
const queryText = `
UPDATE brand_code
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE brand_id = $2 AND error_code = $3 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, brandId, errorCode]);
return true;
};
const getErrorCodeByIdDb = async (error_code_id) => {
const queryText = `
SELECT
a.*
FROM brand_code a
WHERE a.error_code_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [error_code_id]);
return result.recordset[0];
};
const getErrorCodeByBrandAndCodeDb = async (brandId, errorCode) => {
const queryText = `
SELECT
a.*
FROM brand_code a
WHERE a.brand_id = $1 AND a.error_code = $2 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [brandId, errorCode]);
return result.recordset[0];
};
// Get all error codes with pagination and search
const getAllErrorCodesDb = async (searchParams = {}) => {
let queryParams = [];
// Pagination
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
// Search across multiple columns
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["a.error_code", "a.error_code_name", "a.error_code_description"],
searchParams.criteria,
queryParams
);
queryParams = whereParamOr ? whereParamOr : queryParams;
// Filter conditions
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.is_active", param: searchParams.status, type: "string" },
{ column: "a.brand_id", param: searchParams.brand_id, type: "number" },
],
queryParams
);
queryParams = whereParamAnd ? whereParamAnd : queryParams;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*
FROM brand_code a
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
${whereOrConditions ? whereOrConditions : ''}
ORDER BY a.error_code_id DESC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
return { data: result.recordset, total };
};
module.exports = {
getErrorCodesByBrandIdDb,
getErrorCodeByIdDb,
getErrorCodeByBrandAndCodeDb,
createErrorCodeDb,
updateErrorCodeDb,
deleteErrorCodeDb,
getAllErrorCodesDb,
};

View File

@@ -0,0 +1,60 @@
const pool = require("../config");
// Get solutions by error code ID
const getSolutionsByErrorCodeIdDb = async (errorCodeId) => {
const queryText = `
SELECT
a.*
FROM brand_code_solution a
WHERE a.error_code_id = $1 AND a.deleted_at IS NULL
ORDER BY a.brand_code_solution_id
`;
const result = await pool.query(queryText, [errorCodeId]);
return result.recordset;
};
// Create solution for error code
const createSolutionDb = async (errorCodeId, data) => {
const store = {
error_code_id: errorCodeId,
solution_name: data.solution_name,
type_solution: data.type_solution,
text_solution: data.text_solution,
path_solution: data.path_solution,
is_active: data.is_active,
created_by: data.created_by
};
const { query: queryText, values } = pool.buildDynamicInsert("brand_code_solution", store);
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId;
};
// Update solution
const updateSolutionDb = async (solutionId, data) => {
const store = { ...data };
const whereData = { brand_code_solution_id: solutionId };
const { query: queryText, values } = pool.buildDynamicUpdate("brand_code_solution", store, whereData);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return true;
};
// Soft delete solution
const deleteSolutionDb = async (solutionId, deletedBy) => {
const queryText = `
UPDATE brand_code_solution
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE brand_code_solution_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, solutionId]);
return true;
};
module.exports = {
getSolutionsByErrorCodeIdDb,
createSolutionDb,
updateSolutionDb,
deleteSolutionDb,
};

187
db/brand_sparepart.db.js Normal file
View File

@@ -0,0 +1,187 @@
const pool = require("../config");
// Get spareparts by error_code_id
const getSparepartsByErrorCodeIdDb = async (errorCodeId) => {
const queryText = `
SELECT
s.sparepart_id,
s.sparepart_name,
s.sparepart_code,
s.sparepart_description,
s.sparepart_model,
s.sparepart_foto,
s.sparepart_item_type,
s.sparepart_qty,
s.sparepart_unit,
s.sparepart_merk,
s.sparepart_stok,
bs.created_at,
bs.created_by
FROM brand_sparepart bs
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
WHERE bs.error_code_id = $1
AND s.deleted_at IS NULL
ORDER BY s.sparepart_name
`;
const result = await pool.query(queryText, [errorCodeId]);
return result.recordset;
};
// Get error codes by sparepart_id
const getErrorCodesBySparepartIdDb = async (sparepartId) => {
const queryText = `
SELECT
ec.error_code_id,
ec.error_code,
ec.error_code_name,
ec.error_code_description,
ec.error_code_color,
ec.path_icon,
ec.is_active,
ec.created_at,
ec.updated_at
FROM brand_sparepart bs
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
WHERE bs.sparepart_id = $1
AND ec.deleted_at IS NULL
ORDER BY ec.error_code
`;
const result = await pool.query(queryText, [sparepartId]);
return result.recordset;
};
// Insert error_code-spareparts relationship
const insertErrorCodeSparepartDb = async (errorCodeId, sparepartId, createdBy) => {
const queryText = `
INSERT INTO brand_sparepart (error_code_id, sparepart_id, created_by, created_at)
VALUES ($1, $2, $3, CURRENT_TIMESTAMP)
`;
const result = await pool.query(queryText, [errorCodeId, sparepartId, createdBy]);
return result.recordset;
};
// Insert multiple error_code-spareparts relationships
const insertMultipleErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, createdBy) => {
if (!sparepartIds || sparepartIds.length === 0) return [];
const values = sparepartIds.map((_, index) => `($1, $${index + 2}, $${sparepartIds.length + 2}, CURRENT_TIMESTAMP)`).join(', ');
const queryText = `
INSERT INTO brand_sparepart (error_code_id, sparepart_id, created_by, created_at)
VALUES ${values}
`;
const params = [errorCodeId, ...sparepartIds, createdBy];
const result = await pool.query(queryText, params);
return result.recordset;
};
// Delete specific error_code-sparepart relationship
const deleteErrorCodeSparepartDb = async (errorCodeId, sparepartId) => {
const queryText = `
DELETE FROM brand_sparepart
WHERE error_code_id = $1 AND sparepart_id = $2
`;
const result = await pool.query(queryText, [errorCodeId, sparepartId]);
return result.rowsAffected > 0;
};
// Delete all spareparts for an error_code
const deleteAllErrorCodeSparepartsDb = async (errorCodeId) => {
const queryText = `
DELETE FROM brand_sparepart
WHERE error_code_id = $1
`;
const result = await pool.query(queryText, [errorCodeId]);
return result.rowsAffected > 0;
};
// Update error_code-spareparts (replace all)
const updateErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, updatedBy) => {
// Delete existing relationships
await deleteAllErrorCodeSparepartsDb(errorCodeId);
// Insert new relationships
if (sparepartIds && sparepartIds.length > 0) {
return await insertMultipleErrorCodeSparepartsDb(errorCodeId, sparepartIds, updatedBy);
}
return true;
};
const checkErrorCodeSparepartExistsDb = async (errorCodeId, sparepartId) => {
const queryText = `
SELECT 1
FROM brand_spareparts
WHERE error_code_id = $1 AND sparepart_id = $2
`;
const result = await pool.query(queryText, [errorCodeId, sparepartId]);
return result.recordset.length > 0;
};
const getSparepartsByBrandIdDb = async (brandId) => {
const queryText = `
SELECT DISTINCT
s.sparepart_id,
s.sparepart_name,
s.sparepart_code,
s.sparepart_description,
s.sparepart_model,
s.sparepart_foto,
s.sparepart_item_type,
s.sparepart_qty,
s.sparepart_unit,
s.sparepart_merk,
s.sparepart_stok,
s.created_at,
s.updated_at
FROM brand_sparepart bs
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
WHERE ec.brand_id = $1
AND s.deleted_at IS NULL
AND ec.deleted_at IS NULL
ORDER BY s.sparepart_name
`;
const result = await pool.query(queryText, [brandId]);
return result.recordset;
};
// Get brands by sparepart_id (now using error_code_id mapping)
const getBrandsBySparepartIdDb = async (sparepartId) => {
const queryText = `
SELECT DISTINCT
b.brand_id,
b.brand_name,
b.brand_type,
b.brand_manufacture,
b.brand_model,
b.brand_code,
b.is_active,
b.created_at,
b.updated_at
FROM brand_sparepart bs
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
JOIN m_brands b ON ec.brand_id = b.brand_id
WHERE bs.sparepart_id = $1
AND s.deleted_at IS NULL
AND ec.deleted_at IS NULL
AND b.deleted_at IS NULL
ORDER BY b.brand_name
`;
const result = await pool.query(queryText, [sparepartId]);
return result.recordset;
};
// Deprecated functions removed - table structure changed to use error_code_id instead of brand_id
module.exports = {
// New functions using error_code_id
getSparepartsByErrorCodeIdDb,
getErrorCodesBySparepartIdDb,
insertErrorCodeSparepartDb,
insertMultipleErrorCodeSparepartsDb,
deleteErrorCodeSparepartDb,
deleteAllErrorCodeSparepartsDb,
updateErrorCodeSparepartsDb,
checkErrorCodeSparepartExistsDb,
};

106
db/contact.db.js Normal file
View File

@@ -0,0 +1,106 @@
const pool = require("../config");
// Get all Contact
const getAllContactDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
[
"a.contact_name",
"a.contact_type",
],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.contact_name", param: searchParams.name, type: "string" },
{ column: "a.contact_type", param: searchParams.code, type: "string" },
{ column: "a.is_active", param: searchParams.active, type: "boolean" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*
FROM contact a
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.contact_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const getContactByIdDb = async (id) => {
const queryText = `
SELECT
a.*
FROM contact a
WHERE a.contact_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
const createContactDb = async (store) => {
const { query: queryText, values } = pool.buildDynamicInsert("contact", store);
const result = await pool.query(queryText, values);
const insertedId = result.recordset?.[0]?.inserted_id;
return insertedId ? await getContactByIdDb(insertedId) : null;
};
const updateContactDb = async (id, data) => {
const store = { ...data };
const whereData = { contact_id: id };
const { query: queryText, values } = pool.buildDynamicUpdate(
"contact",
store,
whereData
);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getContactByIdDb(id);
};
// Soft delete tag
const deleteContactDb = async (id, deletedBy) => {
const queryText = `
UPDATE contact
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE contact_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllContactDb,
getContactByIdDb,
createContactDb,
updateContactDb,
deleteContactDb,
};

92
db/file_uploads.db.js Normal file
View File

@@ -0,0 +1,92 @@
const pool = require("../config");
// Get file upload by path
const getFileUploadByPathDb = async (path) => {
const queryText = `
SELECT
file_upload_id,
file_upload_name,
type_document,
path_document,
created_by,
updated_by,
deleted_by,
created_at,
updated_at,
deleted_at
FROM file_upload
WHERE path_document = $1 AND deleted_at IS NULL
`;
const result = await pool.query(queryText, [path]);
return result.recordset[0];
};
// Create file upload
const createFileUploadDb = async (data) => {
const store = {
file_upload_name: data.file_upload_name,
};
// Add path_document if exists
if (data.path_document) {
store.path_document = data.path_document;
}
// Add type_document if exists
if (data.type_document) {
store.type_document = data.type_document;
}
if (data.createdBy) {
store.created_by = data.createdBy;
}
console.log('Data to insert:', store);
const queryText = `
INSERT INTO file_upload (file_upload_name, path_document, type_document, created_by, created_at, updated_at)
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
SELECT SCOPE_IDENTITY() as inserted_id;
`;
const values = [
store.file_upload_name,
store.path_document,
store.type_document,
store.created_by || null
];
// console.log('Manual Query:', queryText);
// console.log('Manual Values:', values);
const result = await pool.query(queryText, values);
return result.recordset[0];
};
// Soft delete file upload by path
const deleteFileUploadByPathDb = async (path, deletedBy = null) => {
const store = {
deleted_at: new Date(),
};
if (deletedBy) {
store.deleted_by = deletedBy;
}
const whereData = {
path_document: path,
};
const { query: queryText, values } = pool.buildDynamicUpdate(
"file_upload",
store,
whereData
);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return true;
};
module.exports = {
getFileUploadByPathDb,
createFileUploadDb,
deleteFileUploadByPathDb,
};

568
db/history_value.db.js Normal file
View File

@@ -0,0 +1,568 @@
const { columns } = require("mssql");
const pool = require("../config");
const getHistoryAlarmDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
[
"b.tag_name",
"a.tagnum"
],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "b.tag_name", param: searchParams.name, type: "string" },
{ column: "b.tag_number", param: searchParams.name, type: "number" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*,
b.tag_name,
b.tag_number,
b.lim_low_crash,
b.lim_low,
b.lim_high,
b.lim_high_crash,
c.status_color
FROM alarm_history a
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
LEFT JOIN m_status c ON a.status = c.status_number AND c.deleted_at IS NULL
WHERE a.datetime IS NOT NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.datetime DESC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const getHistoryEventDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
[
"b.tag_name",
"a.tagnum"
],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "b.tag_name", param: searchParams.name, type: "string" },
{ column: "b.tag_number", param: searchParams.name, type: "number" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*,
c.status_color
FROM event_alarm a
LEFT JOIN m_status c ON a.status = c.status_number AND c.deleted_at IS NULL
WHERE a.datetime IS NOT NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.datetime DESC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const checkTableNamedDb = async (tableName) => {
try {
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
throw new Error('Invalid table name format');
}
const queryText = `
SELECT TABLE_NAME, TABLE_SCHEMA, TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = $1
`;
const result = await pool.query(queryText, [tableName]);
return result.recordset;
} catch (error) {
console.error('Error in checkTableNamedDb:', error);
throw error;
}
};
const getHistoryValueReportDb = async (tableName, searchParams = {}) => {
try {
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
throw new Error('Invalid table name format');
}
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["b.tag_name", "CAST(a.tagnum AS VARCHAR)"],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "b.tag_name", param: searchParams.name, type: "string" },
{ column: "b.tag_number", param: searchParams.name, type: "number" },
{ column: "a.datetime", param: [searchParams.from, searchParams.to], type: "between" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*,
b.tag_name,
b.tag_number,
b.lim_low_crash,
b.lim_low,
b.lim_high,
b.lim_high_crash,
c.status_color
FROM ${tableName} a
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
LEFT JOIN m_status c ON a.status = c.status_number AND c.deleted_at IS NULL
WHERE a.datetime IS NOT NULL AND b.is_report = 1
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.datetime DESC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total = result.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
} catch (error) {
console.error('Error in getHistoryValueReportDb:', error);
throw error;
}
};
const getHistoryValueReportPivotDb = async (tableName, searchParams = {}) => {
try {
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
throw new Error('Invalid table name format');
}
let from = searchParams.from || '';
let to = searchParams.to || '';
const interval = Math.max(1, Math.min(1440, Number(searchParams.interval ?? 10)));
if (from.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(from)) {
from += ' 00:00:00';
}
if (to.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(to)) {
to += ' 23:59:59';
}
console.log('Table:', tableName);
console.log('From:', from, '| To:', to, '| Interval:', interval);
console.log('Filters:', searchParams);
const dateRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
if (!dateRegex.test(from) || !dateRegex.test(to)) {
throw new Error('Invalid date format. Expected: YYYY-MM-DD or YYYY-MM-DD HH:MM:SS');
}
const fromDate = new Date(from);
const toDate = new Date(to);
const daysDiff = (toDate - fromDate) / (1000 * 60 * 60 * 24);
if (daysDiff > 365) {
throw new Error('Date range cannot exceed 1 year');
}
if (daysDiff < 0) {
throw new Error('From date must be before to date');
}
let tagQueryParams = [];
let tagWhereConditions = [];
if (searchParams.plant_sub_section_id) {
tagWhereConditions.push(`plant_sub_section_id = $${tagQueryParams.length + 1}`);
tagQueryParams.push(searchParams.plant_sub_section_id);
}
if (searchParams.plant_section_id) {
tagWhereConditions.push(`plant_section_id = $${tagQueryParams.length + 1}`);
tagQueryParams.push(searchParams.plant_section_id);
}
if (searchParams.name) {
const nameFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
tagWhereConditions.push(nameFilter);
tagQueryParams.push(`%${searchParams.name}%`, `%${searchParams.name}%`);
}
if (searchParams.criteria) {
const criteriaFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
tagWhereConditions.push(criteriaFilter);
tagQueryParams.push(`%${searchParams.criteria}%`, `%${searchParams.criteria}%`);
}
const tagWhereClause = tagWhereConditions.length > 0
? ` AND ${tagWhereConditions.join(" AND ")}`
: '';
const tagsQuery = `
SELECT tag_name, tag_number
FROM m_tags
WHERE is_report = 1 AND deleted_at IS NULL
${tagWhereClause}
ORDER BY tag_name
`;
console.log('Tags Query:', tagsQuery);
console.log('Tags Query Params:', tagQueryParams);
const tagsResult = await pool.query(tagsQuery, tagQueryParams);
console.log('Tags found:', tagsResult.recordset.length);
if (tagsResult.recordset.length === 0) {
return { data: [], column: '' };
}
const tagNames = tagsResult.recordset.map(r => `[${r.tag_name}]`).join(', ');
const tagNamesColumn = tagsResult.recordset.map(r => r.tag_name).join(', ');
const tagNumbers = tagsResult.recordset.map(r => r.tag_number);
console.log('Filtered tag numbers:', tagNumbers);
console.log('Filtered tag names:', tagNamesColumn);
const tagNumbersFilter = tagNumbers.length > 0
? ` AND a.tagnum IN (${tagNumbers.join(',')})`
: '';
const queryText = `
DECLARE
@fromParam DATETIME = $1,
@toParam DATETIME = $2,
@intervalParam INT = $3;
SELECT TOP 10
'DEBUG_AVERAGING' as info,
b.tag_name,
DATEADD(MINUTE,
(DATEDIFF(MINUTE, @fromParam, CAST(a.datetime AS DATETIME)) / @intervalParam) * @intervalParam,
@fromParam
) AS waktu_group,
COUNT(*) as data_points,
AVG(CAST(a.val AS FLOAT)) as avg_val,
MIN(CAST(a.val AS FLOAT)) as min_val,
MAX(CAST(a.val AS FLOAT)) as max_val
FROM ${tableName} a
INNER JOIN m_tags b ON a.tagnum = b.tag_number
AND b.deleted_at IS NULL
AND b.is_report = 1
WHERE CAST(a.datetime AS DATETIME) BETWEEN @fromParam AND @toParam
AND a.val IS NOT NULL
${tagNumbersFilter}
GROUP BY
b.tag_name,
DATEADD(MINUTE,
(DATEDIFF(MINUTE, @fromParam, CAST(a.datetime AS DATETIME)) / @intervalParam) * @intervalParam,
@fromParam
)
ORDER BY b.tag_name, waktu_group;
;WITH TimeSeries AS (
SELECT @fromParam AS waktu
UNION ALL
SELECT DATEADD(MINUTE, @intervalParam, waktu)
FROM TimeSeries
WHERE DATEADD(MINUTE, @intervalParam, waktu) <= @toParam
),
CleanData AS (
SELECT
CAST(a.datetime AS DATETIME) as datetime_clean,
a.tagnum,
CAST(a.val AS FLOAT) as val,
b.tag_name
FROM ${tableName} a
INNER JOIN m_tags b ON a.tagnum = b.tag_number
AND b.deleted_at IS NULL
AND b.is_report = 1
WHERE ISDATE(a.datetime) = 1
AND a.val IS NOT NULL
AND CAST(a.datetime AS DATETIME) BETWEEN @fromParam AND @toParam
${tagNumbersFilter}
),
Averaged AS (
SELECT
DATEADD(MINUTE,
(DATEDIFF(MINUTE, @fromParam, datetime_clean) / @intervalParam) * @intervalParam,
@fromParam
) AS waktu_group,
tag_name,
AVG(val) AS avg_val
FROM CleanData
GROUP BY
DATEADD(MINUTE,
(DATEDIFF(MINUTE, @fromParam, datetime_clean) / @intervalParam) * @intervalParam,
@fromParam
),
tag_name
),
Pivoted AS (
SELECT
waktu_group,
${tagNames}
FROM Averaged
PIVOT (
MAX(avg_val)
FOR tag_name IN (${tagNames})
) AS p
)
SELECT
CONVERT(VARCHAR(19), ts.waktu, 120) AS waktu,
${tagNames}
FROM TimeSeries ts
LEFT JOIN Pivoted p ON ts.waktu = p.waktu_group
ORDER BY ts.waktu
OPTION (MAXRECURSION 0);
`;
const result = await pool.query(queryText, [from, to, interval]);
if (result.recordsets && result.recordsets.length >= 2) {
console.log('Sample averaging data:');
result.recordsets[0].slice(0, 10).forEach(row => {
console.log(`${row.tag_name} @ ${row.waktu_group}: avg=${row.avg_val}, min=${row.min_val}, max=${row.max_val}, points=${row.data_points}`);
});
console.log('\nPivot result sample:');
if (result.recordsets[1] && result.recordsets[1].length > 0) {
result.recordsets[1].slice(0, 5).forEach(row => {
console.log(JSON.stringify(row, null, 2));
});
}
}
const rows = result.recordsets?.[1] || result.recordset;
if (!rows || rows.length === 0) {
console.log('No pivot data');
return { data: [], column: tagNamesColumn };
}
const timeKey = 'waktu';
const tagList = Object.keys(rows[0]).filter(k => k !== timeKey);
const nivoData = tagList.map(tag => ({
id: tag,
data: rows.map(row => ({
x: row[timeKey],
y: row[tag] !== null && row[tag] !== undefined ? Number(row[tag]) : null
}))
}));
nivoData.forEach(series => {
const nonNull = series.data.filter(d => d.y !== null && d.y !== 0);
const sampleVals = nonNull.slice(0, 3).map(d => d.y);
console.log(`${series.id}: ${nonNull.length} non-zero values, sample: [${sampleVals.join(', ')}]`);
});
return { data: nivoData, column: tagNamesColumn };
} catch (error) {
console.error('Error in getHistoryValueReportPivotDb:', error);
throw error;
}
};
const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
let from = searchParams.from;
let to = searchParams.to;
// pastikan interval berupa number dan ada nilai default
const interval = Number(searchParams.interval) > 0 ? Number(searchParams.interval) : 10;
// --- Normalisasi tanggal (kalau cuma tanggal tanpa jam)
if (from.length === 10) from += ' 00:00:00';
if (to.length === 10) to += ' 23:59:59';
let tagQueryParams = [];
let tagWhereConditions = [];
if (searchParams.plant_sub_section_id) {
tagWhereConditions.push(`plant_sub_section_id = $${tagQueryParams.length + 1}`);
tagQueryParams.push(searchParams.plant_sub_section_id);
}
if (searchParams.plant_section_id) {
tagWhereConditions.push(`plant_section_id = $${tagQueryParams.length + 1}`);
tagQueryParams.push(searchParams.plant_section_id);
}
if (searchParams.name) {
const nameFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
tagWhereConditions.push(nameFilter);
tagQueryParams.push(`%${searchParams.name}%`, `%${searchParams.name}%`);
}
if (searchParams.criteria) {
const criteriaFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
tagWhereConditions.push(criteriaFilter);
tagQueryParams.push(`%${searchParams.criteria}%`, `%${searchParams.criteria}%`);
}
const tagWhereClause = tagWhereConditions.length > 0
? ` AND ${tagWhereConditions.join(" AND ")}`
: '';
const tagsQuery = `
SELECT tag_name, tag_number
FROM m_tags
WHERE is_report = 1 AND deleted_at IS NULL
${tagWhereClause}
ORDER BY tag_name
`;
const tags = await pool.query(tagsQuery, tagQueryParams);
if (tags.recordset.length === 0) {
return { data: [] };
}
const tagNames = tags.recordset.map(r => `[${r.tag_name}]`).join(', ');
const tagNumbers = tags.recordset.map(r => r.tag_number);
const tagNumbersFilter = tagNumbers.length > 0
? ` AND a.tagnum IN (${tagNumbers.join(',')})`
: '';
const queryText = `
DECLARE
@fromParam DATETIME = '${from}',
@toParam DATETIME = '${to}',
@intervalParam INT = ${interval};
;WITH TimeSeries AS (
SELECT @fromParam AS waktu
UNION ALL
SELECT DATEADD(MINUTE, @intervalParam, waktu)
FROM TimeSeries
WHERE DATEADD(MINUTE, @intervalParam, waktu) <= @toParam
),
Averaged AS (
SELECT
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, CAST(a.datetime AS DATETIME)) / @intervalParam * @intervalParam, 0) AS waktu_group,
b.tag_name,
ROUND(AVG(a.val), 4) AS avg_val
FROM ${tableName} a
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
WHERE a.datetime BETWEEN @fromParam AND @toParam
${tagNumbersFilter}
GROUP BY
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, CAST(a.datetime AS DATETIME)) / @intervalParam * @intervalParam, 0),
b.tag_name
),
Pivoted AS (
SELECT
waktu_group,
${tagNames}
FROM Averaged
PIVOT (
MAX(avg_val)
FOR tag_name IN (${tagNames})
) AS p
)
SELECT
CONVERT(VARCHAR(16), ts.waktu, 120) AS waktu,
${tagNames}
FROM TimeSeries ts
LEFT JOIN Pivoted p ON ts.waktu = p.waktu_group
ORDER BY ts.waktu
OPTION (MAXRECURSION 0);
`;
const result = await pool.query(queryText);
const rows = result.recordset;
if (!rows || rows.length === 0) return { data: [] };
// --- Bentuk data untuk Nivo Chart
const timeKey = 'waktu';
const tagList = Object.keys(rows[0]).filter(k => k !== timeKey);
const nivoData = tagList.map(tag => ({
id: tag,
data: rows.map(row => ({
x: row[timeKey],
y: row[tag] !== null ? Number(row[tag]) : null
}))
}));
return { data: nivoData };
};
module.exports = {
getHistoryAlarmDb,
getHistoryEventDb,
checkTableNamedDb,
getHistoryValueReportDb,
getHistoryValueReportPivotDb,
getHistoryValueTrendingPivotDb
};

210
db/notification_error.db.js Normal file
View File

@@ -0,0 +1,210 @@
const pool = require("../config");
const InsertNotificationErrorDb = async (store) => {
const { query: queryText, values } = pool.buildDynamicInsert(
"notification_error",
store
);
const result = await pool.query(queryText, values);
const insertedId = result.recordset?.[0]?.inserted_id;
return insertedId ? await getNotificationByIdDb(insertedId) : null;
};
const getNotificationByIdDb = async (id) => {
const queryText = `
SELECT
a.*,
b.plant_sub_section_id,
c.plant_sub_section_name,
d.device_code,
d.device_name,
d.device_location,
d.listen_channel,
e.brand_name
FROM notification_error a
LEFT JOIN m_tags b
ON a.error_chanel = b.tag_number
LEFT JOIN m_plant_sub_section c
ON b.plant_sub_section_id = c.plant_sub_section_id
LEFT JOIN m_device d
ON a.error_chanel = d.listen_channel AND d.deleted_at IS NULL
LEFT JOIN m_brands e
ON d.brand_id = e.brand_id AND d.deleted_at IS NULL
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset[0];
};
const getDeviceNotificationByIdDb = async (chanel_id) => {
const queryText = `
SELECT
device_code,
device_name,
device_location,
listen_channel
FROM m_device
WHERE listen_channel = $1
AND deleted_at IS NULL
`;
const result = await pool.query(queryText, [chanel_id]);
return result.recordset[0];
};
const getAllNotificationDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
[
"a.message_error_issue",
"a.is_send",
"a.is_delivered",
"a.is_read",
"a.is_active",
"b.error_code",
"b.error_code_name",
],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.message_error_issue", param: searchParams.message_error_issue, type: "string" },
{ column: "a.is_send", param: searchParams.is_send, type: "number" },
{ column: "a.is_delivered", param: searchParams.is_delivered, type: "number" },
{ column: "a.is_read", param: searchParams.is_read, type: "number" },
{ column: "a.is_active", param: searchParams.is_active, type: "number" },
{ column: "b.error_code", param: searchParams.error_code, type: "string" },
{ column: "b.error_code_name", param: searchParams.error_code_name, type: "string" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.notification_error_id,
a.error_code_id,
a.message_error_issue,
a.is_send,
a.is_delivered,
a.is_read,
a.is_active,
b.error_code,
b.error_code_name,
b.error_code_color,
b.path_icon,
b.created_at,
c.solution_name,
c.type_solution,
c.path_solution,
d.device_code,
d.device_name,
d.device_location,
d.listen_channel,
e.brand_name,
COALESCE(d.device_name, '') + ' - ' + COALESCE(b.error_code_name, '') AS device_name_error
FROM notification_error a
LEFT JOIN brand_code b
ON a.error_code_id = b.error_code_id AND b.deleted_at IS NULL
LEFT JOIN brand_code_solution c
ON b.error_code_id = c.error_code_id AND c.deleted_at IS NULL
LEFT JOIN m_device d
ON a.error_chanel = d.listen_channel AND d.deleted_at IS NULL
LEFT JOIN m_brands e
ON d.brand_id = e.brand_id AND d.deleted_at IS NULL
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.notification_error_id DESC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const updateNotificationErrorDb = async (id, data) => {
const store = { ...data };
const whereData = { notification_error_id: id };
const { query: queryText, values } = pool.buildDynamicUpdate(
"notification_error",
store,
whereData
);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getNotificationByIdDb(id);
};
const getUsersNotificationErrorDb = async (id) => {
const queryText = `
SELECT
b.notification_error_id,
a.notification_error_user_id,
a.contact_phone,
a.contact_name,
a.is_send,
a.updated_at,
c.is_active
FROM notification_error_user a
LEFT JOIN notification_error b ON a.notification_error_id = b.notification_error_id
LEFT JOIN contact c ON a.contact_phone = c.contact_phone
WHERE a.notification_error_id = $1
AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
module.exports = {
getNotificationByIdDb,
getDeviceNotificationByIdDb,
getAllNotificationDb,
InsertNotificationErrorDb,
updateNotificationErrorDb,
getUsersNotificationErrorDb
};

View File

@@ -0,0 +1,94 @@
const pool = require("../config");
const getAllNotificationErrorLogDb = async () => {
const queryText = `
SELECT
a.*,
b.contact_name,
b.contact_type
FROM notification_error_log a
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
WHERE a.deleted_at IS NULL
ORDER BY a.notification_error_log_id DESC
`;
const result = await pool.query(queryText);
return result.recordset;
};
const getNotificationErrorLogByIdDb = async (id) => {
const queryText = `
SELECT
a.*,
b.contact_name,
b.contact_type
FROM notification_error_log a
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
WHERE a.notification_error_log_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset[0];
};
const getNotificationErrorLogByNotificationErrorIdDb = async (notificationErrorId) => {
const queryText = `
SELECT
a.notification_error_log_description,
a.created_at,
b.contact_type,
c.user_fullname as created_by_name,
case when a.created_by is not null then c.user_fullname else b.contact_name end as contact_name,
case when a.created_by is not null then c.user_phone else a.contact_phone end as contact_phone
FROM notification_error_log a
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
LEFT JOIN m_users c ON a.created_by = c.user_id
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
ORDER BY a.created_at DESC
`;
const result = await pool.query(queryText, [notificationErrorId]);
return result.recordset;
};
const createNotificationErrorLogDb = async (store) => {
const queryText = `
INSERT INTO notification_error_log (
notification_error_id,
contact_phone,
notification_error_log_description,
created_by,
updated_by,
created_at,
updated_at
)
VALUES ($1, $2, $3, $4, $4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
SELECT SCOPE_IDENTITY() as inserted_id;
`;
const values = [
store.notification_error_id,
store.contact_phone,
store.notification_error_log_description,
store.created_by
];
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId ? await getNotificationErrorLogByIdDb(insertedId) : null;
};
const deleteNotificationErrorLogDb = async (id, deletedBy) => {
const queryText = `
UPDATE notification_error_log
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE notification_error_log_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllNotificationErrorLogDb,
getNotificationErrorLogByIdDb,
getNotificationErrorLogByNotificationErrorIdDb,
createNotificationErrorLogDb,
deleteNotificationErrorLogDb,
};

View File

@@ -0,0 +1,176 @@
const pool = require("../config");
const insertNotificationErrorSparepartDb = async () => {
const insertQuery = `
INSERT INTO notification_error_sparepart (
notification_error_id,
brand_sparepart_id
)
SELECT
ne.notification_error_id,
bs.brand_sparepart_id
FROM notification_error ne
INNER JOIN brand_sparepart bs
ON ne.error_code_id = bs.error_code_id
LEFT JOIN notification_error_sparepart nes
ON nes.notification_error_id = ne.notification_error_id
AND nes.brand_sparepart_id = bs.brand_sparepart_id
AND nes.deleted_at IS NULL
WHERE ne.deleted_at IS NULL
AND nes.notification_error_sparepart_id IS NULL;
`;
await pool.query(insertQuery);
};
const getAllNotificationErrorSparepartDb = async (searchParams = {}) => {
await insertNotificationErrorSparepartDb();
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
[
"a.brand_sparepart_id",
"a.device_id",
"a.sparepart_id",
"b.sparepart_name",
"d.device_name",
],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.brand_sparepart_id", param: searchParams.name, type: "int" },
{ column: "a.device_id", param: searchParams.code, type: "int" },
{ column: "a.unit", param: searchParams.unit, type: "string" },
{ column: "b.sparepart_name", param: searchParams.device, type: "string" },
{ column: "d.device_name", param: searchParams.device, type: "string" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*,
b.sparepart_name,
b.sparepart_foto,
b.sparepart_stok,
b.sparepart_qty,
b.sparepart_description,
b.sparepart_model,
b.sparepart_merk,
b.sparepart_unit,
b.sparepart_item_type,
d.device_name
FROM notification_error_sparepart a
LEFT JOIN brand_sparepart c ON a.brand_sparepart_id = c.brand_sparepart_id
LEFT JOIN m_sparepart b ON c.sparepart_id = b.sparepart_id
LEFT JOIN m_device d on c.device_id = d.device_id
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.notification_error_sparepart_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const getNotificationErrorSparepartByIdDb = async (id) => {
const queryText = `
SELECT
a.*,
b.sparepart_name,
b.sparepart_foto,
b.sparepart_stok,
b.sparepart_qty,
b.sparepart_description,
b.sparepart_model,
b.sparepart_merk,
b.sparepart_unit,
b.sparepart_item_type,
d.device_name
FROM notification_error_sparepart a
LEFT JOIN brand_sparepart c ON a.brand_sparepart_id = c.brand_sparepart_id
LEFT JOIN m_sparepart b ON c.sparepart_id = b.sparepart_id
LEFT JOIN m_device d on c.device_id = d.device_id
WHERE a.notification_error_sparepart_id = $1
AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset?.[0] || null;
};
const createNotificationErrorSparepartDb = async (store) => {
const { query: queryText, values } = pool.buildDynamicInsert("notification_error_sparepart", store);
const result = await pool.query(queryText, values);
const insertedId = result.recordset?.[0]?.inserted_id;
return insertedId ? await getNotificationErrorSparepartByIdDb(insertedId) : null;
};
const updateNotificationErrorSparepartDb = async (id, data) => {
const store = { ...data };
const whereData = { notification_error_sparepart_id: id };
const { query: queryText, values } = pool.buildDynamicUpdate(
"notification_error_sparepart",
store,
whereData
);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getNotificationErrorSparepartByIdDb(id);
};
// Soft delete tag
const deleteNotificationErrorSparepartDb = async (id, deletedBy) => {
const queryText = `
UPDATE notification_error_sparepart
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE notification_error_sparepart_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllNotificationErrorSparepartDb,
getNotificationErrorSparepartByIdDb,
createNotificationErrorSparepartDb,
updateNotificationErrorSparepartDb,
deleteNotificationErrorSparepartDb,
};

View File

@@ -0,0 +1,147 @@
const pool = require("../config");
// Get all Notification
const getAllNotificationErrorUserDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["a.notification_error_id", "a.contact_id"],
searchParams.criteria,
queryParams
);
if (whereParamOr) queryParams = whereParamOr;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{
column: "a.notification_error_id",
param: searchParams.name,
type: "int",
},
{ column: "a.contact_id", param: searchParams.code, type: "int" },
],
queryParams
);
if (whereParamAnd) queryParams = whereParamAnd;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*
FROM notification_error_user a
WHERE a.deleted_at IS NULL
${
whereConditions.length > 0
? ` AND ${whereConditions.join(" AND ")}`
: ""
}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.notification_error_user_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const getNotificationErrorUserByIdDb = async (id) => {
const queryText = `
SELECT
a.*,
b. is_active as contact_is_active,
d.error_code,
d.error_code_name,
e.device_name
FROM notification_error_user a
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
LEFT JOIN notification_error c ON a.notification_error_id = c.notification_error_id
LEFT JOIN brand_code d ON d.error_code_id = c.error_code_id
LEFT JOIN m_device e ON c.error_chanel = e.listen_channel
WHERE a.notification_error_user_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
const getNotificationErrorByIdDb = async (notification_error_id) => {
const queryText = `
SELECT
a.*,
b.is_active as contact_is_active,
c.is_read
FROM notification_error_user a
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
LEFT JOIN notification_error c ON a.notification_error_id = c.notification_error_id
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [notification_error_id]);
return result.recordset;
};
const createNotificationErrorUserDb = async (store) => {
const { query: queryText, values } = pool.buildDynamicInsert(
"notification_error_user",
store
);
const result = await pool.query(queryText, values);
const insertedId = result.recordset?.[0]?.inserted_id;
return insertedId ? await getNotificationErrorUserByIdDb(insertedId) : null;
};
const updateNotificationErrorUserDb = async (id, data) => {
const store = { ...data };
const whereData = { notification_error_user_id: id };
const { query: queryText, values } = pool.buildDynamicUpdate(
"notification_error_user",
store,
whereData
);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getNotificationErrorUserByIdDb(id);
};
// Soft delete tag
const deleteNotificationErrorUserDb = async (id, deletedBy) => {
const queryText = `
UPDATE notification_error_user
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE notification_error_user_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllNotificationErrorUserDb,
getNotificationErrorUserByIdDb,
getNotificationErrorByIdDb,
createNotificationErrorUserDb,
updateNotificationErrorUserDb,
deleteNotificationErrorUserDb,
};

62
db/notification_wa.db.js Normal file
View File

@@ -0,0 +1,62 @@
// db/notification_wa.db.js
const { default: axios } = require('axios');
const CryptoJS = require('crypto-js');
const https = require('https');
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
const generateTokenRedirect = async (userPhone, userName, id) => {
const plain = {
user_phone: userPhone,
user_name: userName,
id
}
const tokenCrypt = CryptoJS.AES.encrypt(JSON.stringify(plain), process.env.VITE_KEY_SESSION).toString();
return tokenCrypt
}
const shortUrltiny = async (encodedToken) => {
const url = `${process.env.ENDPOINT_FE}/redirect?token=${encodedToken}`
const encodedUrl = encodeURIComponent(url); // ⬅️ Encode dulu!
const response = await axios.get(`https://tinyurl.com/api-create.php?url=${encodedUrl}`,{httpsAgent}) ;
let shortUrl = response.data;
if (!shortUrl.startsWith('http')) {
shortUrl = 'https://' + shortUrl;
}
return shortUrl
}
const sendNotifikasi = async (phone, message) => {
const payload = {
phone: phone,
message: message
};
// console.log('payload', payload);
const endPointWhatsapp = process.env.ENDPOINT_WHATSAPP;
try {
const response = await axios.post(endPointWhatsapp, payload,{httpsAgent} );
// console.log(response.data);
return response?.data
} catch (error) {
// console.error(error.response?.data || error.message);
return error.response?.data || error.message
}
};
module.exports = {
generateTokenRedirect,
shortUrltiny,
sendNotifikasi,
};

187
db/sparepart.db.js Normal file
View File

@@ -0,0 +1,187 @@
const pool = require("../config");
// Get all devices
const getAllSparepartDb = async (searchParams = {}) => {
let queryParams = [];
// Pagination
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
// Search
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
[
"a.sparepart_name",
"a.sparepart_code",
"a.sparepart_model",
"a.updated_at",
],
searchParams.criteria,
queryParams
);
queryParams = whereParamOr ? whereParamOr : queryParams;
// Filter
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.sparepart_name", param: searchParams.code, type: "string" },
{
column: "a.sparepart_code",
param: searchParams.location,
type: "string",
},
{
column: "b.sparepart_model",
param: searchParams.brand,
type: "string",
},
{ column: "a.updated_at", param: searchParams.status, type: "string" },
],
queryParams
);
queryParams = whereParamAnd ? whereParamAnd : queryParams;
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*,
COALESCE(a.sparepart_code, '') + ' - ' + COALESCE(a.sparepart_name, '') AS sparepart_code_name
FROM m_sparepart a
WHERE a.deleted_at IS NULL
${
whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""
}
${whereOrConditions ? whereOrConditions : ""}
ORDER BY a.sparepart_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
return { data: result.recordset, total };
};
const getSparepartByIdDb = async (id) => {
const queryText = `
SELECT
a.*,
COALESCE(a.sparepart_code, '') + ' - ' + COALESCE(a.sparepart_name, '') AS sparepart_code_name
FROM m_sparepart a
WHERE a.sparepart_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
const checkSparepartNameExistsDb = async (sparePartName, excludeId = null) => {
let queryText = `
SELECT sparepart_id
FROM m_sparepart
WHERE sparepart_name = $1 AND deleted_at IS NULL
`;
let values = [sparePartName];
if (excludeId) {
queryText += ` AND sparepart_id != $2`;
values.push(excludeId);
}
const result = await pool.query(queryText, values);
return result.recordset.length > 0;
};
const createSparepartDb = async (data) => {
const newCode = await pool.generateKode(
"SPAREPART",
"m_sparepart",
"sparepart_code"
);
const store = {
...data,
sparepart_code: newCode,
};
const { query: queryText, values } = pool.buildDynamicInsert(
"m_sparepart",
store
);
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId ? await getSparepartByIdDb(insertedId) : null;
};
const updateSparepartDb = async (id, data) => {
const store = {
...data,
};
// Kondisi WHERE
const whereData = {
sparepart_id: id,
};
const { query: queryText, values } = pool.buildDynamicUpdate(
"m_sparepart",
store,
whereData
);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getSparepartByIdDb(id);
};
const deleteSparepartDb = async (id, deletedBy) => {
const queryText = `
UPDATE m_sparepart
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE sparepart_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
// Get multiple spareparts by IDs
const getSparepartsByIdsDb = async (sparepartIds) => {
if (!sparepartIds || sparepartIds.length === 0) return [];
const placeholders = sparepartIds.map((_, index) => `$${index + 1}`).join(', ');
const queryText = `
SELECT
sparepart_id,
sparepart_name,
sparepart_code,
sparepart_description,
sparepart_model,
sparepart_foto,
sparepart_item_type,
sparepart_qty,
sparepart_unit,
sparepart_merk,
sparepart_stok,
created_at,
updated_at
FROM m_sparepart
WHERE sparepart_id IN (${placeholders})
AND deleted_at IS NULL
`;
const result = await pool.query(queryText, sparepartIds);
return result.recordset;
};
module.exports = {
getAllSparepartDb,
getSparepartByIdDb,
getSparepartsByIdsDb,
checkSparepartNameExistsDb,
createSparepartDb,
updateSparepartDb,
deleteSparepartDb,
};

View File

@@ -10,7 +10,7 @@ const getAllUserScheduleDb = async (searchParams = {}) => {
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["a.user_id", "a.user_schedule_id", "a.schedule_id", "a.user_schedule_id"],
["a.user_id", "a.user_schedule_id", "a.schedule_id", "a.user_schedule_id", "a.shift_id"],
searchParams.criteria,
queryParams
);
@@ -19,9 +19,13 @@ const getAllUserScheduleDb = async (searchParams = {}) => {
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.user_id", param: searchParams.user_id, type: "int" },
{ column: "a.user_schedule_id", param: searchParams.user_schedule_id, type: "int" },
{
column: "a.user_schedule_id",
param: searchParams.user_schedule_id,
type: "int",
},
{ column: "a.schedule_id", param: searchParams.schedule_id, type: "int" },
{ column: "a.user_schedule_id", param: searchParams.user_schedule_id, type: "int" },
{ column: "a.shift_id", param: searchParams.shift_id, type: "int" },
],
queryParams
);
@@ -29,31 +33,75 @@ const getAllUserScheduleDb = async (searchParams = {}) => {
const queryText = `
SELECT
COUNT(*) OVER() AS total_data,
a.*,
b.schedule_date,
COUNT(*) OVER() AS total_data,
a.*,
c.shift_name,
c.start_time,
c.end_time,
d.user_fullname
d.user_fullname,
d.user_name,
d.user_phone
FROM user_schedule a
LEFT JOIN schedule b ON a.schedule_id = b.schedule_id
LEFT JOIN m_shift c ON a.shift_id = c.shift_id
LEFT JOIN m_users d ON a.user_id = d.user_id
LEFT JOIN m_users d ON a.user_id = d.user_id
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${
whereConditions.length > 0
? ` AND ${whereConditions.join(" AND ")}`
: ""
}
${whereOrConditions ? ` ${whereOrConditions}` : ""}
ORDER BY a.user_schedule_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
ORDER BY c.shift_id ASC
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
`;
const result = await pool.query(queryText, queryParams);
const total =
result?.recordset?.length > 0
? parseInt(result.recordset[0].total_data, 10)
: 0;
const records = result.recordset || [];
return { data: result.recordset, total };
const total = records.length > 0 ? parseInt(records[0].total_data, 10) : 0;
const groupedShift = {};
records.forEach((row) => {
if (!groupedShift[row.shift_id]) {
groupedShift[row.shift_id] = {
shift: {
shift_id: row.shift_id,
shift_name: row.shift_name,
start_time: row.start_time,
end_time: row.end_time,
users: [],
},
};
}
groupedShift[row.shift_id].shift.users.push({
user_schedule_id: row.user_schedule_id,
user_id: row.user_id,
user_fullname: row.user_fullname,
user_name: row.user_name,
user_phone: row.user_phone,
});
});
const data = Object.values(groupedShift);
return { data, total };
};
const getUserScheduleById = async (userId, shiftId) => {
const queryText = `
SELECT
a.user_schedule_id,
a.user_id,
a.shift_id
FROM user_schedule a
WHERE a.user_id = $1
AND a.shift_id = $2
AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [userId, shiftId]);
return result.recordset || [];
};
const getUserScheduleByIdDb = async (id) => {
@@ -64,7 +112,9 @@ const getUserScheduleByIdDb = async (id) => {
c.shift_name,
c.start_time,
c.end_time,
d.user_fullname
d.user_fullname,
d.user_name,
d.user_phone
FROM user_schedule a
LEFT JOIN schedule b ON a.schedule_id = b.schedule_id
LEFT JOIN m_shift c ON a.shift_id = c.shift_id
@@ -76,7 +126,10 @@ const getUserScheduleByIdDb = async (id) => {
};
const insertUserScheduleDb = async (store) => {
const { query: queryText, values } = pool.buildDynamicInsert("user_schedule", store);
const { query: queryText, values } = pool.buildDynamicInsert(
"user_schedule",
store
);
const result = await pool.query(queryText, values);
const insertedId = result.recordset?.[0]?.inserted_id;
@@ -113,4 +166,5 @@ module.exports = {
insertUserScheduleDb,
updateUserScheduleDb,
deleteUserScheduleDb,
getUserScheduleById,
};

View File

@@ -1,7 +1,7 @@
module.exports = {
apps: [
{
name: "bengkel-api",
name: "cod-api",
script: "./index.js", // Path to your entry file
env: {
NODE_ENV: "development",
@@ -9,6 +9,14 @@ module.exports = {
env_production: {
NODE_ENV: "production",
},
// Logging configuration
// error_file: "C:\IDETAMA\pm2-log\cod-api\cod-api-error.log",
// out_file: "C:\IDETAMA\pm2-log\cod-api\cod-api-out.log",
// log_file: "C:\IDETAMA\pm2-log\cod-api\cod-api-combined.log", // optional combined file
error_file: "cod-api-error.log",
out_file: "cod-api-out.log",
log_file: "cod-api-combined.log", // optional combined file
time: true, // adds timestamps to logs
},
],
};

8
middleware/imagekit.js Normal file
View File

@@ -0,0 +1,8 @@
const Imagekit = require("imagekit");
const { IMAGEKIT_URL_ENDPOINT, IMAGEKIT_PUBLIC_KEY, IMAGEKIT_PRIVATE_KEY } = process.env;
module.exports = new Imagekit({
publicKey: IMAGEKIT_PUBLIC_KEY,
privateKey: IMAGEKIT_PRIVATE_KEY,
urlEndpoint: IMAGEKIT_URL_ENDPOINT,
});

5
middleware/upload.js Normal file
View File

@@ -0,0 +1,5 @@
const multer = require("multer");
const storage = multer.memoryStorage();
module.exports = multer({ storage });

69
middleware/uploads.js Normal file
View File

@@ -0,0 +1,69 @@
const multer = require("multer");
const path = require("path");
const { randomUUID } = require("crypto");
const fs = require("fs");
// Fungsi untuk tentuin folder berdasarkan file type
function getFolderByType(mimetype) {
if (mimetype === "application/pdf") {
return "pdf";
} else if (mimetype.startsWith("image/")) {
return "images";
}
return "file";
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const folderName = getFolderByType(file.mimetype);
const folderPath = path.join(__dirname, "../uploads", folderName);
fs.mkdirSync(folderPath, { recursive: true });
cb(null, folderPath);
},
filename: (req, file, cb) => {
const ext = path.extname(file.originalname);
const timestamp = Date.now();
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
const formattedDate = `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;
// Prefix berdasarkan tipe file
const prefix = file.mimetype === "application/pdf" ? "pdf" : "img";
const uniqueId = randomUUID().slice(0, 8);
cb(null, `${prefix}-${uniqueId}-${formattedDate}${ext}`);
},
});
const upload = multer({
storage,
fileFilter: (req, file, cb) => {
const allowedTypes = /jpeg|jpg|png|pdf/;
const allowedMimeTypes = /image\/(jpeg|jpg|png)|application\/pdf/;
const extname = allowedTypes.test(
path.extname(file.originalname).toLowerCase()
);
const mimetype = allowedMimeTypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb(new Error("File type not allowed. Only PDF and Images (JPEG, JPG, PNG) are accepted."));
}
},
limits: {
fileSize: 10 * 1024 * 1024, // 10MB max file size
},
});
module.exports = upload;

View File

@@ -1,6 +1,10 @@
const { ErrorHandler } = require("../helpers/error");
const { getUserByIdDb } = require("../db/user.db");
function isPhoneNumberID(phone) {
return /^(?:\+62|62|0)8[1-9][0-9]{6,10}$/.test(phone);
}
const verifyAccess = (minLevel = 1, allowUnapprovedReadOnly = false) => {
return async (req, res, next) => {
try {
@@ -11,21 +15,31 @@ const verifyAccess = (minLevel = 1, allowUnapprovedReadOnly = false) => {
// Super Admin bypass semua
if (user.is_sa) return next();
const fullUser = await getUserByIdDb(user.user_id);
if (!fullUser) throw new ErrorHandler(403, "Forbidden: User not found");
if (!fullUser.is_approve) {
if (req.method !== "GET") {
throw new ErrorHandler(403, "Account not approved — read-only access");
if (!isPhoneNumberID(user.user_id) && user.user_id) {
const fullUser = await getUserByIdDb(user.user_id);
if (!fullUser) throw new ErrorHandler(403, "Forbidden: User not found");
if (!fullUser.is_approve) {
if (req.method !== "GET") {
throw new ErrorHandler(403, "Account not approved — read-only access");
}
if (allowUnapprovedReadOnly) return next();
throw new ErrorHandler(403, "Account not approved");
}
if (allowUnapprovedReadOnly) return next();
if (!fullUser.role_level || fullUser.role_level < minLevel) {
throw new ErrorHandler(403, "Forbidden: Insufficient role level");
}
} else {
if (req.method !== 'GET' && req.baseUrl !== '/api/notification-log') {
if (req.baseUrl !== '/api/notification') {
throw new ErrorHandler(403, "Forbidden: Insufficient Access");
}
}
throw new ErrorHandler(403, "Account not approved");
}
if (!fullUser.role_level || fullUser.role_level < minLevel) {
throw new ErrorHandler(403, "Forbidden: Insufficient role level");
}
next();

View File

@@ -19,10 +19,15 @@ function verifyAccessToken(req, res, next) {
if (!token) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer')) {
throw new ErrorHandler(401, 'Access Token is required');
if (authHeader && authHeader.startsWith('Bearer')) {
token = authHeader.split(' ')[1];
} else {
token = req.query.token;
}
token = authHeader.split(' ')[1];
}
if (!token) {
throw new ErrorHandler(401, 'Access Token is required');
}
const decoded = JWTService.verifyToken(token);

View File

@@ -30,11 +30,13 @@
"crypto": "^1.0.1",
"crypto-js": "^4.2.0",
"dotenv": "^8.2.0",
"exceljs": "^4.4.0",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"google-auth-library": "^8.7.0",
"googleapis": "^112.0.0",
"helmet": "^4.4.1",
"imagekit": "^6.0.0",
"joi": "^17.13.3",
"jsonwebtoken": "^8.5.1",
"moment": "^2.29.4",

View File

@@ -7,5 +7,6 @@ router.post('/login', AuthController.login);
router.post('/register', AuthController.register);
router.get('/generate-captcha', AuthController.generateCaptcha);
router.post('/refresh-token', AuthController.refreshToken);
router.post('/verify-redirect', AuthController.verifyTokenRedirect);
module.exports = router;

17
routes/brand.route.js Normal file
View File

@@ -0,0 +1,17 @@
const express = require('express');
const BrandController = require('../controllers/brand.controller');
const verifyToken = require('../middleware/verifyToken');
const verifyAccess = require('../middleware/verifyAccess');
const router = express.Router();
router.route('/')
.get(verifyToken.verifyAccessToken, BrandController.getAll)
.post(verifyToken.verifyAccessToken, verifyAccess(), BrandController.create);
router.route('/:id')
.get(verifyToken.verifyAccessToken, BrandController.getById)
.put(verifyToken.verifyAccessToken, verifyAccess(), BrandController.update)
.delete(verifyToken.verifyAccessToken, verifyAccess(), BrandController.delete);
module.exports = router;

17
routes/contact.route.js Normal file
View File

@@ -0,0 +1,17 @@
const express = require('express');
const ContactController = require('../controllers/contact.controller');
const verifyToken = require("../middleware/verifyToken")
const verifyAccess = require("../middleware/verifyAccess")
const router = express.Router();
router.route("/")
.get(verifyToken.verifyAccessToken, ContactController.getAll)
.post(verifyToken.verifyAccessToken, verifyAccess(), ContactController.create);
router.route("/:id")
.get(verifyToken.verifyAccessToken, ContactController.getById)
.put(verifyToken.verifyAccessToken, verifyAccess(), ContactController.update)
.delete(verifyToken.verifyAccessToken, verifyAccess(), ContactController.delete);
module.exports = router;

View File

@@ -0,0 +1,19 @@
const express = require('express');
const ErrorCodeController = require('../controllers/error_code.controller');
const verifyToken = require('../middleware/verifyToken');
const verifyAccess = require('../middleware/verifyAccess');
const router = express.Router();
router.route('/brand/:brandId')
.get(verifyToken.verifyAccessToken, ErrorCodeController.getByBrandId)
.post(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.create);
router.route('/brand/:brandId/:errorCodeId')
.put(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.update)
.delete(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.delete);
router.route('/:id')
.get(verifyToken.verifyAccessToken, ErrorCodeController.getById);
module.exports = router;

View File

@@ -0,0 +1,17 @@
const router = require("express").Router();
const upload = require("../middleware/uploads");
const verifyToken = require("../middleware/verifyToken");
const verifyAccess = require("../middleware/verifyAccess");
const {
uploadFile,
getFileByPath,
deleteFileByPath,
} = require("../controllers/file_uploads.controller");
router.post("/", verifyToken.verifyAccessToken, verifyAccess(), upload.single("file"), uploadFile);
router.route("/:folder/:filename")
.get(verifyToken.verifyAccessToken, getFileByPath)
.delete(verifyToken.verifyAccessToken, verifyAccess(), deleteFileByPath);
module.exports = router;

View File

@@ -0,0 +1,19 @@
const express = require('express');
const HistoryValueController = require('../controllers/history_value.controller');
const verifyToken = require('../middleware/verifyToken');
const verifyAccess = require('../middleware/verifyAccess');
const router = express.Router();
router.route('/alarm')
.get(verifyToken.verifyAccessToken, HistoryValueController.getAllHistoryAlarm)
router.route('/event')
.get(verifyToken.verifyAccessToken, HistoryValueController.getAllHistoryEvent)
router.route('/value-report')
.get(verifyToken.verifyAccessToken, HistoryValueController.getHistoryValueReport)
router.route('/value-report-pivot')
.get(verifyToken.verifyAccessToken, HistoryValueController.getHistoryValueReportPivot)
router.route('/value-trending')
.get(verifyToken.verifyAccessToken, HistoryValueController.getHistoryValueTrendingPivot)
module.exports = router;

View File

@@ -4,24 +4,43 @@ const users = require("./users.route");
const device = require('./device.route');
const roles = require('./roles.route');
const tags = require("./tags.route");
const brand = require("./brand.route");
const subSection = require("./plant_sub_section.route");
const fileUploads = require("./file_uploads.route");
const shift = require("./shift.route");
const schedule = require("./schedule.route");
const status = require("./status.route");
const unit = require("./unit.route")
const UserSchedule = require("./user_schedule.route")
const historyValue = require("./history_value.route")
const contact = require("./contact.route")
const notificationError = require("./notification_error.route")
const notificationErrorSparepart = require("./notification_error_sparepart.route")
const sparepart = require("./sparepart.route")
const notificationErrorLog = require("./notification_error_log.route")
const notificationErrorUser = require("./notification_error_user.route")
const errorCode = require("./error_code.route")
router.use("/auth", auth);
router.use("/user", users);
router.use("/device", device);
router.use("/roles", roles);
router.use("/tags", tags);
router.use("/brand", brand);
router.use("/plant-sub-section", subSection);
router.use("/file-uploads", fileUploads);
router.use("/shift", shift);
router.use("/schedule", schedule);
router.use("/status", status);
router.use("/unit", unit);
router.use("/user-schedule", UserSchedule)
router.use("/history", historyValue)
router.use("/contact", contact)
router.use("/notification", notificationError)
router.use("/notification-sparepart", notificationErrorSparepart)
router.use("/sparepart", sparepart)
router.use("/notification-log", notificationErrorLog)
router.use("/notification-user", notificationErrorUser)
router.use("/error-code", errorCode)
module.exports = router;

View File

@@ -0,0 +1,40 @@
const express = require("express");
const NotificationErrorController = require("../controllers/notification_error.controller");
const verifyToken = require("../middleware/verifyToken");
const verifyAccess = require("../middleware/verifyAccess");
const router = express.Router();
router
.route("/")
.get(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorController.getAll
);
router
.route("/")
.post(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorController.create
);
router
.route("/:id")
.get(verifyToken.verifyAccessToken, NotificationErrorController.getById)
.put(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorController.update
);
router.post(
"/resend/:id",
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorController.resend
);
module.exports = router;

View File

@@ -0,0 +1,21 @@
const express = require('express');
const NotificationErrorLogController = require('../controllers/notification_error_log.controller');
const verifyToken = require("../middleware/verifyToken")
const verifyAccess = require("../middleware/verifyAccess")
const router = express.Router();
router.route("/")
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getAll)
.post(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorLogController.create);
router.route("/:id")
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getById);
router.route("/notification_error/:id")
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getByNotificationErrorId);
module.exports = router;

View File

@@ -0,0 +1,23 @@
const express = require('express');
const NotificationErrorSparepartController = require('../controllers/notification_error_sparepart.controller');
const verifyToken = require('../middleware/verifyToken');
const verifyAccess = require('../middleware/verifyAccess');
const router = express.Router();
// ===========================
// Notification Erro rSparepart Routes
// ===========================
router
.route('/')
.get(verifyToken.verifyAccessToken, NotificationErrorSparepartController.getAll)
.post(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorSparepartController.create);
router
.route('/:id')
.get(verifyToken.verifyAccessToken, NotificationErrorSparepartController.getById)
.put(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorSparepartController.update)
.delete(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorSparepartController.delete);
module.exports = router;

View File

@@ -0,0 +1,38 @@
const express = require("express");
const NotificationErrorUserController = require("../controllers/notification_error_user.controller");
const verifyToken = require("../middleware/verifyToken");
const verifyAccess = require("../middleware/verifyAccess");
const router = express.Router();
router
.route("/")
.get(verifyToken.verifyAccessToken, NotificationErrorUserController.getAll)
.post(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorUserController.create
);
router
.route("/:id")
.get(verifyToken.verifyAccessToken, NotificationErrorUserController.getById)
.put(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorUserController.update
)
.delete(
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorUserController.delete
);
router.post(
"/resend/:id/:contact_phone",
verifyToken.verifyAccessToken,
verifyAccess(),
NotificationErrorUserController.resendByUser
);
module.exports = router;

48
routes/sparepart.route.js Normal file
View File

@@ -0,0 +1,48 @@
const express = require("express");
const SparepartController = require("../controllers/sparepart.controller");
const verifyToken = require("../middleware/verifyToken");
const verifyAccess = require("../middleware/verifyAccess");
const upload = require("../middleware/upload");
const router = express.Router();
router.get(
"/export",
verifyToken.verifyAccessToken,
SparepartController.exportExcel
);
router.post(
"/import",
verifyToken.verifyAccessToken,
verifyAccess(),
upload.single("file"),
SparepartController.importExcel
);
router
.route("/")
.get(verifyToken.verifyAccessToken, SparepartController.getAll)
.post(
verifyToken.verifyAccessToken,
verifyAccess(),
upload.single("sparepart_foto"),
SparepartController.create
);
router
.route("/:id")
.get(verifyToken.verifyAccessToken, SparepartController.getById)
.put(
verifyToken.verifyAccessToken,
verifyAccess(),
upload.single("sparepart_foto"),
SparepartController.update
)
.delete(
verifyToken.verifyAccessToken,
verifyAccess(),
SparepartController.delete
);
module.exports = router;

122
services/brand.service.js Normal file
View File

@@ -0,0 +1,122 @@
// Brand operations
const {
getAllBrandsDb,
getBrandByIdDb,
createBrandDb,
updateBrandDb,
deleteBrandDb,
checkBrandNameExistsDb,
} = require("../db/brand.db");
const { ErrorHandler } = require("../helpers/error");
class BrandService {
// Get all brands
static async getAllBrands(param) {
try {
const results = await getAllBrandsDb(param);
return {
...results,
data: results.data
};
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get brand by ID (without error codes)
static async getBrandById(id) {
try {
const brand = await getBrandByIdDb(id);
if (!brand) throw new ErrorHandler(404, "Brand not found");
return brand;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Create brand
static async createBrand(data) {
try {
if (data.brand_name) {
const brandExists = await checkBrandNameExistsDb(data.brand_name);
if (brandExists) {
throw new ErrorHandler(400, "Brand name already exists");
}
}
const brandData = {
brand_name: data.brand_name,
brand_type: data.brand_type,
brand_manufacture: data.brand_manufacture,
brand_model: data.brand_model,
is_active: data.is_active !== undefined ? data.is_active : true,
created_by: data.created_by,
};
const createdBrand = await createBrandDb(brandData);
if (!createdBrand) {
throw new ErrorHandler(500, "Failed to create brand");
}
return createdBrand;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
// Soft delete brand by ID
static async deleteBrand(id, userId) {
try {
const brandExist = await getBrandByIdDb(id);
if (!brandExist) {
throw new ErrorHandler(404, "Brand not found");
}
const result = await deleteBrandDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Update brand
static async updateBrand(id, data) {
try {
const existingBrand = await getBrandByIdDb(id);
if (!existingBrand) throw new ErrorHandler(404, "Brand not found");
if (data.brand_name && data.brand_name !== existingBrand.brand_name) {
const brandExists = await checkBrandNameExistsDb(data.brand_name, id);
if (brandExists) {
throw new ErrorHandler(400, "Brand name already exists");
}
}
const brandData = {
brand_name: data.brand_name || existingBrand.brand_name,
brand_type: data.brand_type !== undefined ? data.brand_type : existingBrand.brand_type,
brand_manufacture: data.brand_manufacture !== undefined ? data.brand_manufacture : existingBrand.brand_manufacture,
brand_model: data.brand_model !== undefined ? data.brand_model : existingBrand.brand_model,
is_active: data.is_active !== undefined ? data.is_active : existingBrand.is_active,
updated_by: data.updated_by,
};
const updatedBrand = await updateBrandDb(existingBrand.brand_name, brandData);
if (!updatedBrand) {
throw new ErrorHandler(500, "Failed to update brand");
}
return updatedBrand;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
}
module.exports = BrandService;

View File

@@ -0,0 +1,88 @@
const {
getAllContactDb,
getContactByIdDb,
createContactDb,
updateContactDb,
deleteContactDb
} = require('../db/contact.db');
const { ErrorHandler } = require('../helpers/error');
class ContactService {
// Get all Contact
static async getAllContact(param) {
try {
const results = await getAllContactDb(param);
results.data.map(element => {
});
return results
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get Contact by ID
static async getContactById(id) {
try {
const result = await getContactByIdDb(id);
if (result.length < 1) throw new ErrorHandler(404, 'Contact not found');
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Create Contact
static async createContact(data) {
try {
if (!data || typeof data !== 'object') data = {};
const result = await createContactDb(data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Update Contact
static async updateContact(id, data) {
try {
if (!data || typeof data !== 'object') data = {};
const dataExist = await getContactByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, 'Contact not found');
}
const result = await updateContactDb(id, data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Soft delete Contact
static async deleteContact(id, userId) {
try {
const dataExist = await getContactByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, 'Contact not found');
}
const result = await deleteContactDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
}
module.exports = ContactService;

View File

@@ -0,0 +1,265 @@
const { ErrorHandler } = require("../helpers/error");
const {
getErrorCodesByBrandIdDb,
getErrorCodeByIdDb,
getErrorCodeByBrandAndCodeDb,
createErrorCodeDb,
updateErrorCodeDb,
deleteErrorCodeDb,
getAllErrorCodesDb,
} = require("../db/brand_code.db");
const {
getSolutionsByErrorCodeIdDb,
createSolutionDb,
updateSolutionDb,
deleteSolutionDb,
} = require("../db/brand_code_solution.db");
const {
getSparepartsByErrorCodeIdDb,
insertMultipleErrorCodeSparepartsDb,
updateErrorCodeSparepartsDb,
} = require("../db/brand_sparepart.db");
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
class ErrorCodeService {
static async getAllErrorCodes(param) {
try {
const results = await getAllErrorCodesDb(param);
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get error code by ID with complete data
static async getErrorCodeById(id) {
try {
const errorCode = await getErrorCodeByIdDb(id);
if (!errorCode) throw new ErrorHandler(404, "Error code not found");
const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);
const spareparts = await getSparepartsByErrorCodeIdDb(errorCode.error_code_id);
const solutionsWithFiles = await Promise.all(
solutions.map(async (solution) => {
let fileData = null;
if (solution.path_solution && solution.type_solution !== "text") {
fileData = await getFileUploadByPathDb(solution.path_solution);
}
return {
...solution,
file_upload_name: fileData?.file_upload_name || null,
path_document: fileData?.path_document || null,
};
})
);
return {
...errorCode,
solution: solutionsWithFiles,
spareparts: spareparts,
};
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get error codes by brand ID
static async getErrorCodesByBrandId(brandId, queryParams = {}) {
try {
const results = await getErrorCodesByBrandIdDb(brandId, queryParams);
if (results.data && results.total !== undefined) {
return results;
}
const errorCodesWithDetails = await Promise.all(
results.map(async (errorCode) => {
const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);
const spareparts = await getSparepartsByErrorCodeIdDb(errorCode.error_code_id);
const solutionsWithFiles = await Promise.all(
solutions.map(async (solution) => {
let fileData = null;
if (solution.path_solution && solution.type_solution !== "text") {
fileData = await getFileUploadByPathDb(solution.path_solution);
}
return {
...solution,
file_upload_name: fileData?.file_upload_name || null,
path_document: fileData?.path_document || null,
};
})
);
return {
...errorCode,
solution: solutionsWithFiles,
spareparts: spareparts,
};
})
);
return errorCodesWithDetails;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Create error code with solutions and spareparts
static async createErrorCodeWithFullData(brandId, data) {
try {
if (!data || typeof data !== "object") data = {};
const errorId = await createErrorCodeDb(brandId, {
error_code: data.error_code,
error_code_name: data.error_code_name,
error_code_description: data.error_code_description,
error_code_color: data.error_code_color,
path_icon: data.path_icon,
is_active: data.is_active,
created_by: data.created_by,
});
if (!errorId) {
throw new Error("Failed to create error code");
}
if (data.spareparts && Array.isArray(data.spareparts)) {
await insertMultipleErrorCodeSparepartsDb(errorId, data.spareparts, data.created_by);
}
if (data.solution && Array.isArray(data.solution)) {
for (const solutionData of data.solution) {
await createSolutionDb(errorId, {
solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution,
text_solution: solutionData.text_solution || null,
path_solution: solutionData.path_solution || null,
is_active: solutionData.is_active,
created_by: data.created_by,
});
}
}
const createdErrorCode = await this.getErrorCodeById(errorId);
return createdErrorCode;
} catch (error) {
throw new ErrorHandler(500, `Create error code failed: ${error.message}`);
}
}
// Update error code with solutions and spareparts
static async updateErrorCodeWithFullData(brandId, errorCodeId, data) {
try {
const existingErrorCode = await getErrorCodeByIdDb(errorCodeId);
if (!existingErrorCode) throw new ErrorHandler(404, "Error code not found");
// Verify the error code belongs to the specified brand
if (existingErrorCode.brand_id !== parseInt(brandId)) {
throw new ErrorHandler(403, "Error code does not belong to specified brand");
}
// Check if there are any error code fields to update
const hasMainFieldUpdate =
data.error_code !== undefined ||
data.error_code_name !== undefined ||
data.error_code_description !== undefined ||
data.error_code_color !== undefined ||
data.path_icon !== undefined ||
data.is_active !== undefined;
if (hasMainFieldUpdate) {
await updateErrorCodeDb(brandId, existingErrorCode.error_code, {
error_code: data.error_code,
error_code_name: data.error_code_name,
error_code_description: data.error_code_description,
error_code_color: data.error_code_color,
path_icon: data.path_icon,
is_active: data.is_active,
updated_by: data.updated_by,
});
}
if (data.spareparts && Array.isArray(data.spareparts)) {
await updateErrorCodeSparepartsDb(existingErrorCode.error_code_id, data.spareparts, data.updated_by);
}
if (data.solution && Array.isArray(data.solution)) {
const existingSolutions = await getSolutionsByErrorCodeIdDb(existingErrorCode.error_code_id);
const incomingSolutionNames = data.solution.map((s) => s.solution_name);
for (const solutionData of data.solution) {
const existingSolution = existingSolutions.find(
(s) => s.solution_name === solutionData.solution_name
);
if (existingSolution) {
await updateSolutionDb(
existingSolution.brand_code_solution_id,
{
solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution,
text_solution: solutionData.text_solution || null,
path_solution: solutionData.path_solution || null,
is_active: solutionData.is_active,
updated_by: data.updated_by,
}
);
} else {
await createSolutionDb(existingErrorCode.error_code_id, {
solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution,
text_solution: solutionData.text_solution || null,
path_solution: solutionData.path_solution || null,
is_active: solutionData.is_active,
created_by: data.updated_by,
});
}
}
for (const existingSolution of existingSolutions) {
if (!incomingSolutionNames.includes(existingSolution.solution_name)) {
await deleteSolutionDb(existingSolution.brand_code_solution_id, data.updated_by);
}
}
}
const updatedErrorCode = await this.getErrorCodeById(existingErrorCode.error_code_id);
return updatedErrorCode;
} catch (error) {
throw new ErrorHandler(500, `Update error code failed: ${error.message}`);
}
}
// Soft delete error code
static async deleteErrorCode(brandId, errorCodeId, deletedBy) {
try {
const errorCodeExist = await getErrorCodeByIdDb(errorCodeId);
if (!errorCodeExist) {
throw new ErrorHandler(404, "Error code not found");
}
// Verify the error code belongs to the specified brand
if (errorCodeExist.brand_id !== parseInt(brandId)) {
throw new ErrorHandler(403, "Error code does not belong to specified brand");
}
const result = await deleteErrorCodeDb(brandId, errorCodeExist.error_code, deletedBy);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
}
module.exports = ErrorCodeService;

View File

@@ -0,0 +1,141 @@
const {
getHistoryAlarmDb,
getHistoryEventDb,
checkTableNamedDb,
getHistoryValueReportDb,
getHistoryValueReportPivotDb,
getHistoryValueTrendingPivotDb
} = require('../db/history_value.db');
const { getSubSectionByIdDb } = require('../db/plant_sub_section.db');
const { ErrorHandler } = require('../helpers/error');
class HistoryValue {
static async getAllHistoryAlarm(param) {
try {
const results = await getHistoryAlarmDb(param);
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message || 'Error fetching alarm history');
}
}
static async getAllHistoryEvent(param) {
try {
const results = await getHistoryEventDb(param);
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message || 'Error fetching event history');
}
}
static async getHistoryValueReport(param) {
try {
if (!param.plant_sub_section_id) {
throw new ErrorHandler(400, 'plant_sub_section_id is required');
}
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
if (!plantSubSection || plantSubSection.length < 1) {
throw new ErrorHandler(404, 'Plant sub section not found');
}
const tableNameValue = plantSubSection[0]?.table_name_value;
if (!tableNameValue) {
throw new ErrorHandler(404, 'Table name not configured for this sub section');
}
const tableExist = await checkTableNamedDb(tableNameValue);
if (!tableExist || tableExist.length < 1) {
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
}
const results = await getHistoryValueReportDb(tableExist[0].TABLE_NAME, param);
return results;
} catch (error) {
throw new ErrorHandler(
error.statusCode || 500,
error.message || 'Error fetching history value report'
);
}
}
static async getHistoryValueReportPivot(param) {
try {
if (!param.plant_sub_section_id) {
throw new ErrorHandler(400, 'plant_sub_section_id is required');
}
if (!param.from || !param.to) {
throw new ErrorHandler(400, 'from and to date parameters are required');
}
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
if (!plantSubSection || plantSubSection.length < 1) {
throw new ErrorHandler(404, 'Plant sub section not found');
}
const tableNameValue = plantSubSection[0]?.table_name_value;
if (!tableNameValue) {
throw new ErrorHandler(404, 'Table name not configured for this sub section');
}
const tableExist = await checkTableNamedDb(tableNameValue);
if (!tableExist || tableExist.length < 1) {
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
}
const results = await getHistoryValueReportPivotDb(tableExist[0].TABLE_NAME, param);
return results;
} catch (error) {
throw new ErrorHandler(
error.statusCode || 500,
error.message || 'Error fetching history value report pivot'
);
}
}
static async getHistoryValueTrendingPivot(param) {
try {
if (!param.plant_sub_section_id) {
throw new ErrorHandler(400, 'plant_sub_section_id is required');
}
if (!param.from || !param.to) {
throw new ErrorHandler(400, 'from and to date parameters are required');
}
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
if (!plantSubSection || plantSubSection.length < 1) {
throw new ErrorHandler(404, 'Plant sub section not found');
}
const tableNameValue = plantSubSection[0]?.table_name_value;
if (!tableNameValue) {
throw new ErrorHandler(404, 'Table name not configured for this sub section');
}
const tableExist = await checkTableNamedDb(tableNameValue);
if (!tableExist || tableExist.length < 1) {
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
}
const results = await getHistoryValueTrendingPivotDb(tableExist[0].TABLE_NAME, param);
return results;
} catch (error) {
throw new ErrorHandler(
error.statusCode || 500,
error.message || 'Error fetching history value trending pivot'
);
}
}
}
module.exports = HistoryValue;

View File

@@ -0,0 +1,267 @@
// services/notification_error.service.js
const {
getAllNotificationDb,
getNotificationByIdDb,
InsertNotificationErrorDb,
getUsersNotificationErrorDb,
updateNotificationErrorDb,
} = require("../db/notification_error.db");
const { getErrorCodeByIdDb } = require("../db/brand_code.db");
const { getSolutionsByErrorCodeIdDb } = require("../db/brand_code_solution.db");
const {
getAllNotificationErrorLogDb,
getNotificationErrorLogByNotificationErrorIdDb,
} = require("../db/notification_error_log.db");
const { getSparepartsByErrorCodeIdDb } = require("../db/brand_sparepart.db");
const {
getNotificationErrorByIdDb,
} = require("../db/notification_error_user.db");
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
const {
generateTokenRedirect,
shortUrltiny,
sendNotifikasi,
} = require("../db/notification_wa.db");
const { ErrorHandler } = require("../helpers/error");
class NotificationService {
static async getAllNotification(param) {
try {
const results = await getAllNotificationDb(param);
if (results && Array.isArray(results.data)) {
results.data = await Promise.all(
results.data.map(async (notification) => {
const usersNotification =
(await getUsersNotificationErrorDb(
notification.notification_error_id
)) || [];
return {
...notification,
users: usersNotification,
};
})
);
}
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async createNotificationError(data) {
try {
if (!data || typeof data !== "object") data = {};
const result = await InsertNotificationErrorDb(data);
return result;
} catch (error) {
return error;
}
}
static async getNotificationById(id) {
try {
const notification = await getNotificationByIdDb(id);
if (
!notification ||
(Array.isArray(notification) && notification.length < 1)
) {
throw new ErrorHandler(404, "Notification not found");
}
const usersNotification = (await getUsersNotificationErrorDb(id)) || [];
// Get error code details if error_code_id exists
if (notification.error_code_id) {
const errorCode = await getErrorCodeByIdDb(notification.error_code_id);
if (errorCode) {
// Get solutions for this error code
const solutions =
(await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || [];
const spareparts =
(await getSparepartsByErrorCodeIdDb(errorCode.error_code_id)) || [];
const solutionsWithDetails = await Promise.all(
solutions.map(async (solution) => {
let fileData = null;
if (
solution.path_solution &&
solution.type_solution &&
solution.type_solution !== "text"
) {
try {
fileData = await getFileUploadByPathDb(
solution.path_solution
);
} catch (e) {
fileData = null;
}
}
return {
...solution,
file_upload_name: fileData?.file_upload_name || null,
path_document: fileData?.path_document || null,
};
})
);
notification.error_code = {
...errorCode,
solution: solutionsWithDetails,
spareparts: spareparts,
};
}
}
// Get activity logs for this notification
const notificationLogs =
(await getNotificationErrorLogByNotificationErrorIdDb(id)) || [];
notification.users = usersNotification;
notification.activity_logs = notificationLogs;
return notification;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async updateNotificationError(notification_error_id, data) {
try {
const dataExist = await getNotificationErrorByIdDb(notification_error_id);
if (!dataExist || (Array.isArray(dataExist) && dataExist.length < 1)) {
throw new ErrorHandler(404, "Notification Error User not found");
}
const notification = Array.isArray(dataExist) ? dataExist[0] : dataExist;
if (notification.is_read === true) {
return { success: true, message: "Notification has already been read" };
}
if (!notification.is_read) {
const updateStatus = await updateNotificationErrorDb(
notification_error_id,
{ is_read: true }
);
if (!updateStatus) {
throw new ErrorHandler(500, "Failed to update notification");
}
}
return { success: true, message: "Notification marked as read" };
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
static async resendNotification(id) {
const deviceNotification = await getNotificationByIdDb(id);
if (!deviceNotification)
throw new ErrorHandler(404, "Notification Data not found");
const errorCode = await getErrorCodeByIdDb(
deviceNotification.error_code_id
);
const dataExist = await getUsersNotificationErrorDb(id);
const activeUsers =
dataExist?.filter((user) => user.is_active === true) || [];
if (activeUsers.length < 1)
throw new ErrorHandler(404, "No active contacts");
this._executeResendWa(
id,
activeUsers,
deviceNotification,
errorCode
).catch((err) => console.error("Background Process Error:", err));
return {
count: activeUsers.length,
};
}
static async _executeResendWa(
id,
activeUsers,
deviceNotification,
errorCode
) {
console.log(`user active: `, id, activeUsers);
const sendPromises = activeUsers.map(async (user) => {
try {
console.log(`user: ${user.contact_name} (${user.contact_phone})`);
const tokenRedirect = await generateTokenRedirect(
user.contact_phone,
user.contact_name,
id
);
const encodedToken = encodeURIComponent(tokenRedirect);
console.log("token: ", tokenRedirect);
const shortUrl = await shortUrltiny(encodedToken);
console.log("URL:", shortUrl);
const bodyWithUrl =
`Hai ${user.contact_name || "-"}\n` +
`Terjadi peringatan dengan kode ${errorCode?.error_code || "-"} - ${
errorCode?.error_code_name
} pada device ${deviceNotification.device_name || "-"}.\n` +
`Silahkan cek detail pada link berikut:\n ${shortUrl}`;
const resultSend = await sendNotifikasi(
user.contact_phone,
bodyWithUrl
);
console.log("notifikasi wa:", resultSend)
const isSuccess = resultSend?.error ? false : true;
await updateNotificationErrorDb(user.notification_error_id, {
is_send: isSuccess,
is_delivered: isSuccess,
});
return { phone: user.contact_phone, status: "success" };
} catch (err) {
console.error(`Gagal mengirim ke ${user.contact_phone}:`, err.message);
return {
phone: user.contact_phone,
status: "failed",
error: err.message,
};
}
});
const results = await Promise.all(sendPromises);
console.log("result akhir: ", results)
console.log(
`Resend chat: ${
results.filter((r) => r.status === "success").length
}, Gagal: ${results.filter((r) => r.status === "failed").length}`
);
}
}
module.exports = NotificationService;

View File

@@ -0,0 +1,111 @@
const {
getAllNotificationErrorLogDb,
getNotificationErrorLogByIdDb,
getNotificationErrorLogByNotificationErrorIdDb,
createNotificationErrorLogDb,
updateNotificationErrorLogDb,
deleteNotificationErrorLogDb
} = require('../db/notification_error_log.db');
const { getUserByIdDb } = require('../db/user.db');
const { ErrorHandler } = require('../helpers/error');
class NotificationErrorLogService {
// Get all Notification Error Logs
static async getAllNotificationErrorLog() {
try {
const results = await getAllNotificationErrorLogDb();
results.data.map(element => {
});
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get Notification Error Log by ID
static async getNotificationErrorLogById(id) {
try {
const result = await getNotificationErrorLogByIdDb(id);
if (!result) {
throw new ErrorHandler(404, 'Notification Error Log not found');
}
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Create Notification Error Log
static async createNotificationErrorLog(data, userId) {
try {
if (!data || typeof data !== 'object') data = {};
let createdBy = null;
let contactPhone = data.contact_phone || null;
if (userId) {
try {
const user = await getUserByIdDb(userId);
if (user && user.user_id) {
createdBy = Number(user.user_id);
} else {
createdBy = null;
contactPhone = userId;
}
} catch (dbError) {
createdBy = null;
contactPhone = userId;
}
}
const store = {
notification_error_id: data.notification_error_id,
contact_phone: contactPhone,
notification_error_log_description: data.notification_error_log_description,
created_by: createdBy
};
const result = await createNotificationErrorLogDb(store);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get Notification Error Log by notification_error_id
static async getNotificationErrorLogByNotificationErrorId(notificationErrorId) {
try {
const results = await getNotificationErrorLogByNotificationErrorIdDb(notificationErrorId);
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Soft delete Notification Error Log
static async deleteNotificationErrorLog(id, userId) {
try {
const dataExist = await getNotificationErrorLogByIdDb(id);
if (!dataExist) {
throw new ErrorHandler(404, 'Notification Error Log not found');
}
const result = await deleteNotificationErrorLogDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
}
module.exports = NotificationErrorLogService;

View File

@@ -0,0 +1,76 @@
const {
getAllNotificationErrorSparepartDb,
getNotificationErrorSparepartByIdDb,
createNotificationErrorSparepartDb,
updateNotificationErrorSparepartDb,
deleteNotificationErrorSparepartDb,
} = require("../db/notification_error_sparepart.db");
const { ErrorHandler } = require("../helpers/error");
class NotificationErrorSparepartService {
static async getAll(param) {
try {
const results = await getAllNotificationErrorSparepartDb(param);
results.data.map(element => {
});
return results
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async getById(id) {
const result = await getNotificationErrorSparepartByIdDb(id);
if (result.length < 1)
throw new ErrorHandler(404, "Notification Error Sparepart not found");
return result;
}
static async create(data) {
try {
if (!data || typeof data !== 'object') data = {};
const result = await createNotificationErrorSparepartDb(data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async update(id, data) {
try {
if (!data || typeof data !== 'object') data = {};
const dataExist = await getNotificationErrorSparepartByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, 'Notification Error Sparepart not found');
}
const result = await updateNotificationErrorSparepartDb(id, data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async delete(id) {
const exist = await getNotificationErrorSparepartByIdDb(id);
if (exist.length < 1)
throw new ErrorHandler(404, "Notification Error Sparepart not found");
return await deleteNotificationErrorSparepartDb(id);
}
}
module.exports = NotificationErrorSparepartService;

View File

@@ -0,0 +1,195 @@
const {
getAllNotificationErrorUserDb,
getNotificationErrorUserByIdDb,
createNotificationErrorUserDb,
updateNotificationErrorUserDb,
deleteNotificationErrorUserDb,
} = require("../db/notification_error_user.db");
const {
generateTokenRedirect,
shortUrltiny,
sendNotifikasi,
} = require("../db/notification_wa.db");
const { ErrorHandler } = require("../helpers/error");
class NotificationErrorUserService {
// Get all Contact
static async getAllNotificationErrorUser(param) {
try {
const results = await getAllNotificationErrorUserDb(param);
results.data.map((element) => {});
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get NotificationErrorUser by ID
static async getNotificationErrorUserById(id) {
try {
const result = await getNotificationErrorUserByIdDb(id);
if (result.length < 1)
throw new ErrorHandler(404, "Notification Error User not found");
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Create NotificationErrorUser
static async createNotificationErrorUser(data) {
try {
if (!data || typeof data !== "object") data = {};
const result = await createNotificationErrorUserDb(data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Update NotificationErrorUser
static async updateNotificationErrorUser(id, data) {
try {
if (!data || typeof data !== "object") data = {};
const dataExist = await getNotificationErrorUserByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, "Notification Error User not found");
}
const result = await updateNotificationErrorUserDb(id, data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Soft delete NotificationErrorUser
static async deleteNotificationErrorUser(id, userId) {
try {
const dataExist = await getNotificationErrorUserByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, "Notification Error User not found");
}
const result = await deleteNotificationErrorUserDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async resendNotificationByUser(id, contact_phone) {
const results = [];
const idUser = Array.isArray(id) ? id : [id];
for (const id of idUser) {
try {
const dataExist = await getNotificationErrorUserByIdDb(id);
if (!dataExist || dataExist.length < 1) {
results.push({
id,
status: "failed",
message: "Data Notification Error User not found",
});
continue;
}
const data = dataExist[0];
if (data.contact_phone !== contact_phone) {
results.push({
id,
status: "failed",
message: `Phone ${contact_phone} not found.`,
});
continue;
}
if (data.contact_is_active === false) {
results.push({
id,
status: "failed",
message: `Contact ${data.contact_phone} not active.`,
});
continue;
}
const tokenRedirect = await generateTokenRedirect(
data.contact_phone,
data.contact_name,
data.notification_error_id
);
const encodedToken = encodeURIComponent(tokenRedirect);
const shortUrl = await shortUrltiny(encodedToken);
const bodyWithUrl =
`Hai ${data.contact_name || "-"}\n` +
`Terjadi peringatan dengan kode error ${data.error_code || "-"} - ${
data.error_code_name || "-"
} ` +
`pada device ${
data.device_name || "-"
}, silahkan cek detail pada link berikut:\n` +
`${shortUrl}`;
const resultSend = await sendNotifikasi(
data.contact_phone,
bodyWithUrl
);
const isSuccess = resultSend?.error ? false : true;
const updateData = {
is_send: isSuccess,
message_error_issue: bodyWithUrl,
};
await updateNotificationErrorUserDb(id, updateData);
if (!isSuccess) {
results.push({
id,
status: "failed",
message: `WhatsApp API Gagal: ${
resultSend?.message || "Unknown Error"
}`,
});
} else {
results.push({
status: 200,
notification_error_user_id: id,
notification_error_id: data.notification_error_id,
device_name: data.device_name,
error_code: data?.error_code,
error_code_name: data?.error_code_name,
users: {
contact_name: data.contact_name,
contact_phone: data.contact_phone,
is_send: isSuccess,
},
});
}
} catch (err) {
results.push({ id, status: "error", message: err.message });
}
}
return results;
}
}
module.exports = NotificationErrorUserService;

View File

@@ -0,0 +1,125 @@
const { getAllContactDb } = require("../db/contact.db");
const { InsertNotificationErrorDb } = require("../db/notification_error.db");
const {
createNotificationErrorUserDb,
updateNotificationErrorUserDb,
} = require("../db/notification_error_user.db");
const {
generateTokenRedirect,
shortUrltiny,
sendNotifikasi,
} = require("../db/notification_wa.db");
const { getErrorCodeByIdDb } = require("../db/brand_code.db");
const { getDeviceNotificationByIdDb } = require("../db/notification_error.db");
class NotifikasiWaService {
async onNotification(topic, message) {
try {
const paramDb = {
limit: 100,
page: 1,
criteria: "",
active: 1,
};
// const chanel = {
// "time": "2025-12-11 11:10:58",
// "c_4501": 4,
// "c_5501": 3,
// "c_6501": 0
// }
if (topic === process.env.TOPIC_COD ?? "morek") {
const dataMqtt = JSON.parse(message);
const resultChanel = [];
Object.entries(dataMqtt).forEach(([key, value]) => {
if (key.startsWith("c_")) {
resultChanel.push({
chanel_id: Number(key.slice(2)),
value,
});
}
});
const results = await getAllContactDb(paramDb);
const dataUsers = results.data;
for (const chanel of resultChanel) {
const errorCode = await getErrorCodeByIdDb(chanel.value);
const deviceNotification = await getDeviceNotificationByIdDb(
chanel.chanel_id
);
const data = {
error_code_id: chanel.value,
error_chanel: chanel.chanel_id,
is_send: false,
is_delivered: false,
is_read: false,
is_active: true,
};
const resultNotificationError = await InsertNotificationErrorDb(data);
for (const dataUser of dataUsers) {
if (dataUser.is_active) {
const tokenRedirect = await generateTokenRedirect(
dataUser.userPhone,
dataUser.userName,
resultNotificationError.notification_error_id
);
const encodedToken = encodeURIComponent(tokenRedirect);
const shortUrl = await shortUrltiny(encodedToken);
const bodyMessage =
`Hai ${dataUser.contact_name || "-"}\n` +
`Terjadi peringatan dengan kode error ${errorCode?.error_code || "-"
} - ${errorCode?.error_code_name || "-"} ` +
`pada device ${deviceNotification?.device_name || "-"
}, silahkan cek detail pada link berikut:\n` +
`${shortUrl}`;
const param = {
idData: resultNotificationError.notification_error_id,
userPhone: dataUser.contact_phone,
userName: dataUser.contact_name,
bodyMessage: bodyMessage,
};
const resultNotificationErrorUser =
await createNotificationErrorUserDb({
notification_error_id:
resultNotificationError.notification_error_id,
contact_phone: param.userPhone,
contact_name: param.userName,
is_send: false,
});
const resultSend = await sendNotifikasi(
param.userPhone,
param.bodyMessage
);
await updateNotificationErrorUserDb(
resultNotificationErrorUser[0].notification_error_user_id,
{
is_send: resultSend?.error ? false : true,
}
);
}
}
}
}
} catch (error) {
// throw new ErrorHandler(error.statusCode, error.message);
return error;
}
}
}
module.exports = new NotifikasiWaService();

View File

@@ -0,0 +1,88 @@
const {
getAllSparepartDb,
getSparepartByIdDb,
createSparepartDb,
updateSparepartDb,
deleteSparepartDb,
checkSparepartNameExistsDb,
} = require("../db/sparepart.db");
const { ErrorHandler } = require("../helpers/error");
class SparepartService {
static async getAllSparepart(param) {
try {
const results = await getAllSparepartDb(param);
results.data.map((item) => {});
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
static async getSparepartById(id) {
try {
const sparepart = await getSparepartByIdDb(id);
if (!sparepart || sparepart.length === 0) {
throw new ErrorHandler(404, "Sparepart not found");
}
return sparepart[0];
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
static async createSparepart(data) {
try {
if (!data || typeof data !== "object") data = {};
if (data.sparepart_name) {
const exists = await checkSparepartNameExistsDb(data.sparepart_name);
if (exists)
throw new ErrorHandler(400, "Sparepart name already exists");
}
const created = await createSparepartDb(data);
if (!created) throw new ErrorHandler(500, "Failed to create Sparepart");
return created;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
static async updateSparepart(id, data) {
try {
const existing = await getSparepartByIdDb(id);
if (!existing) throw new ErrorHandler(404, "Sparepart not found");
if (
data.sparepart_name &&
data.sparepart_name !== existing.sparepart_name
) {
const exists = await checkSparepartNameExistsDb(
data.sparepart_name,
id
);
if (exists)
throw new ErrorHandler(400, "Sparepart name already exists");
}
const updated = await updateSparepartDb(id, data);
if (!updated) throw new ErrorHandler(500, "Failed to update Sparepart");
return await this.getSparepartById(id);
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
static async deleteSparepart(id, userId) {
try {
const existing = await getSparepartByIdDb(id);
if (!existing) throw new ErrorHandler(404, "Sparepart not found");
const deleted = await deleteSparepartDb(id, userId);
if (!deleted) throw new ErrorHandler(500, "Failed to delete Sparepart");
return deleted;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
}
module.exports = SparepartService;

View File

@@ -1,6 +1,7 @@
const {
getAllUserScheduleDb,
getUserScheduleByIdDb,
getUserScheduleById,
insertUserScheduleDb,
updateUserScheduleDb,
deleteUserScheduleDb
@@ -35,20 +36,30 @@ const {
}
}
// Create device
static async createUserSchedules(data) {
try {
if (!data || typeof data !== 'object') data = {};
const result = await insertUserScheduleDb(data);
const exist = await getUserScheduleById(
data.user_id,
data.shift_id
);
if (exist.length > 0) {
throw new ErrorHandler(
400,
`User dengan ID ${data.user_id} sudah terdaftar pada shift ${data.shift_id}`
);
}
const result = await insertUserScheduleDb(data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Update device
// Update user schedule
static async updateUserSchedules(id, data) {
try {
if (!data || typeof data !== 'object') data = {};
@@ -59,8 +70,22 @@ const {
throw new ErrorHandler(404, 'UserSchedules not found');
}
const result = await updateUserScheduleDb(id, data);
// 🧩 VALIDASI SAAT UPDATE
if (data.user_id && data.shift_id) {
const exist = await getUserScheduleById(
data.user_id,
data.shift_id
);
if (exist.length > 0 && exist[0].id !== Number(id)) {
throw new ErrorHandler(
400,
`User dengan ID ${data.user_id} sudah terdaftar pada shift ${data.shift_id}`
);
}
}
const result = await updateUserScheduleDb(id, data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);

BIN
uploads/images/tesimage.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

28
validate/brand.schema.js Normal file
View File

@@ -0,0 +1,28 @@
const Joi = require("joi");
// ========================
// Brand Validation
// ========================
const insertBrandSchema = Joi.object({
brand_name: Joi.string().max(100).required(),
brand_type: Joi.string().max(50).optional().allow(""),
brand_manufacture: Joi.string().max(100).required(),
brand_model: Joi.string().max(100).optional().allow(""),
is_active: Joi.boolean().optional().default(true),
description: Joi.string().max(255).optional().allow(""),
});
// Update Brand Validation
const updateBrandSchema = Joi.object({
brand_name: Joi.string().max(100).optional(),
brand_type: Joi.string().max(50).optional().allow(""),
brand_manufacture: Joi.string().max(100).optional(),
brand_model: Joi.string().max(100).optional().allow(""),
is_active: Joi.boolean().optional(),
description: Joi.string().max(255).optional().allow(""),
}).min(1);
module.exports = {
insertBrandSchema,
updateBrandSchema,
};

View File

@@ -0,0 +1,35 @@
const Joi = require("joi");
// ========================
// Contacts Validation
// ========================
const insertContactSchema = Joi.object({
contact_name: Joi.string().min(3).max(100).required(),
contact_phone: Joi.string()
.pattern(/^(?:\+62|0)8\d{7,10}$/)
.required()
.messages({
"string.pattern.base":
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
}),
is_active: Joi.boolean().required(),
contact_type: Joi.string().max(255).optional().allow(null)
});
const updateContactSchema = Joi.object({
contact_name: Joi.string().min(3).max(100).optional(),
contact_phone: Joi.string()
.pattern(/^(?:\+62|0)8\d{7,10}$/)
.optional()
.messages({
"string.pattern.base":
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
}),
is_active: Joi.boolean().optional(),
contact_type: Joi.string().max(255).optional().allow(null)
});
module.exports = {
insertContactSchema,
updateContactSchema,
};

View File

@@ -7,30 +7,33 @@ const Joi = require("joi");
const insertDeviceSchema = Joi.object({
device_name: Joi.string().max(100).required(),
is_active: Joi.boolean().required(),
brand_id: Joi.number().integer().min(1),
device_location: Joi.string().max(100).required(),
device_description: Joi.string().required(),
device_description: Joi.string(),
ip_address: Joi.string()
.ip({ version: ['ipv4', 'ipv6'] })
.required()
.messages({
'string.ip': 'IP address must be a valid IPv4 or IPv6 address'
})
}),
listen_channel: Joi.string().max(100).required()
});
const updateDeviceSchema = Joi.object({
device_name: Joi.string().max(100),
is_active: Joi.boolean(),
brand_id: Joi.number().integer().min(1),
device_location: Joi.string().max(100),
device_description: Joi.string(),
ip_address: Joi.string()
.ip({ version: ['ipv4', 'ipv6'] })
.messages({
'string.ip': 'IP address must be a valid IPv4 or IPv6 address'
})
}),
listen_channel: Joi.string().max(100)
}).min(1);
// ✅ Export dengan CommonJS
module.exports = {
insertDeviceSchema, updateDeviceSchema
};

View File

@@ -0,0 +1,73 @@
const Joi = require("joi");
// ========================
// Error Code Validation
// ========================
const solutionSchema = Joi.object({
solution_name: Joi.string().max(100).required(),
type_solution: Joi.string()
.valid("text", "pdf", "image", "video", "link")
.required(),
text_solution: Joi.when("type_solution", {
is: "text",
then: Joi.string().required(),
otherwise: Joi.string().optional().allow(""),
}),
path_solution: Joi.when("type_solution", {
is: "text",
then: Joi.string().optional().allow(""),
otherwise: Joi.string().required(),
}),
is_active: Joi.boolean().default(true),
});
const insertErrorCodeSchema = Joi.object({
error_code: Joi.string().max(100).required(),
error_code_name: Joi.string().max(100).required(),
error_code_description: Joi.string().optional().allow(""),
error_code_color: Joi.string().optional().allow(""),
path_icon: Joi.string().optional().allow(""),
is_active: Joi.boolean().default(true),
solution: Joi.array()
.items(solutionSchema)
.optional(),
// .min(1)
// .required()
// .messages({
// "array.min": "Error code must have at least 1 solution",
// }),
spareparts: Joi.array()
.items(Joi.number().integer())
.optional(),
}).messages({
"object.unknown": "{{#child}} is not allowed",
});
const updateErrorCodeSchema = Joi.object({
error_code: Joi.string().max(100).optional(),
error_code_name: Joi.string().max(100).optional(),
error_code_description: Joi.string().optional().allow(""),
error_code_color: Joi.string().optional().allow(""),
path_icon: Joi.string().optional().allow(""),
is_active: Joi.boolean().optional(),
solution: Joi.array()
.items(solutionSchema)
.min(1)
.optional()
.messages({
"array.min": "Error code must have at least 1 solution",
}),
spareparts: Joi.array()
.items(Joi.number().integer())
.optional(),
}).min(1).messages({
"object.min": "At least one field must be provided for update",
"object.unknown": "{{#child}} is not allowed",
});
module.exports = {
insertErrorCodeSchema,
updateErrorCodeSchema,
solutionSchema,
};

View File

@@ -0,0 +1,53 @@
// ========================
// Notification Validation
// ========================
const Joi = require("joi");
// ========================
// Insert Notification Schema
// ========================
const insertNotificationSchema = Joi.object({
error_code_id: Joi.number().required().messages({
"any.required": "error_code_id is required",
"number.base": "error_code_id must be a number",
}),
message_error_issue: Joi.string().max(255).optional(),
is_send: Joi.boolean().required().messages({
"any.required": "is_send is required",
"boolean.base": "is_send must be a boolean",
}),
is_delivered: Joi.boolean().required().messages({
"any.required": "is_delivered is required",
"boolean.base": "is_delivered must be a boolean",
}),
is_read: Joi.boolean().required().messages({
"any.required": "is_read is required",
"boolean.base": "is_read must be a boolean",
}),
is_active: Joi.boolean().required().messages({
"any.required": "is_active is required",
"boolean.base": "is_active must be a boolean",
}),
});
// ========================
// Update Notification Schema
// ========================
const updateNotificationSchema = Joi.object({
is_read: Joi.boolean().optional().messages({
"boolean.base": "is_read must be a boolean",
}),
});
module.exports = {
insertNotificationSchema,
updateNotificationSchema,
};

View File

@@ -0,0 +1,11 @@
const Joi = require("joi");
const insertNotificationErrorLogSchema = Joi.object({
notification_error_id: Joi.number().integer().required(),
contact_phone: Joi.string().optional(),
notification_error_log_description: Joi.string().required()
});
module.exports = {
insertNotificationErrorLogSchema,
};

View File

@@ -0,0 +1,30 @@
const Joi = require("joi");
const insertNotificationErrorSparepartSchema = Joi.object({
contact_id: Joi.number().required(),
brand_sparepart_id: Joi.number().required(),
is_verification: Joi.boolean().required(),
is_available: Joi.boolean().required(),
is_active: Joi.boolean().required(),
});
const updateNotificationErrorSparepartSchema = Joi.object({
contact_id: Joi.number().required(),
brand_sparepart_id: Joi.number().optional(),
is_verification: Joi.boolean().optional(),
is_available: Joi.boolean().optional(),
is_active: Joi.boolean().optional(),
});
module.exports = {
insertNotificationErrorSparepartSchema,
updateNotificationErrorSparepartSchema,
};

View File

@@ -0,0 +1,44 @@
const Joi = require("joi");
// ========================
// Insert Notification Error Schema
// ========================
const insertNotificationErrorUserSchema = Joi.object({
notification_error_id: Joi.number().required().messages({
"any.required": "notification_error_id is required",
"number.base": "notification_error_id must be a number",
}),
contact_id: Joi.number().required().messages({
"any.required": "contact_id is required",
"number.base": "contact_id must be a number",
}),
is_send: Joi.boolean().required().messages({
"any.required": "is_send is required",
"boolean.base": "is_send must be a boolean",
}),
});
// ========================
// Update Notification Error Schema
// ========================
const updateNotificationErrorUserSchema = Joi.object({
notification_error_id: Joi.number().optional().messages({
"number.base": "notification_error_id must be a number",
}),
contact_id: Joi.number().required().messages({
"any.required": "contact_id is required",
"number.base": "contact_id must be a number",
}),
is_send: Joi.boolean().optional().messages({
"boolean.base": "is_send must be a boolean",
}),
});
module.exports = {
insertNotificationErrorUserSchema,
updateNotificationErrorUserSchema,
};

View File

@@ -0,0 +1,65 @@
const Joi = require("joi");
// ========================
// Plant Sub Section Validation
// ========================
const insertSubSectionSchema = Joi.object({
plant_sub_section_name: Joi.string()
.max(200)
.required()
.messages({
"string.base": "Sub section name must be a string",
"string.max": "Sub section name cannot exceed 200 characters",
"any.required": "Sub section name is required"
}),
plant_sub_section_description: Joi.string()
.max(200)
.allow('')
.optional()
.messages({
"string.base": "Description must be a string",
"string.max": "Description cannot exceed 200 characters"
}),
table_name_value: Joi.string()
.max(255)
.allow('')
.optional()
.messages({
"string.base": "Table name value must be a string",
"string.max": "Table name value cannot exceed 255 characters"
}),
is_active: Joi.boolean()
.default(true)
.optional()
});
const updateSubSectionSchema = Joi.object({
plant_sub_section_name: Joi.string()
.max(200)
.messages({
"string.base": "Sub section name must be a string",
"string.max": "Sub section name cannot exceed 200 characters",
}).optional(),
plant_sub_section_description: Joi.string()
.max(200)
.allow('')
.optional()
.messages({
"string.base": "Description must be a string",
"string.max": "Description cannot exceed 200 characters"
}),
table_name_value: Joi.string()
.max(255)
.allow('')
.optional()
.messages({
"string.base": "Table name value must be a string",
"string.max": "Table name value cannot exceed 255 characters"
}),
is_active: Joi.boolean().optional()
}).min(1);
module.exports = {
insertSubSectionSchema,
updateSubSectionSchema
};

View File

@@ -0,0 +1,32 @@
const Joi = require("joi");
// ========================
// Sparepart Validation
// ========================
const insertSparepartSchema = Joi.object({
sparepart_name: Joi.string().max(255).required(),
sparepart_description: Joi.string().max(255).optional(),
sparepart_model: Joi.string().max(255).optional(),
sparepart_foto: Joi.string().max(255).optional().allow(""),
sparepart_item_type: Joi.string().max(255).optional(),
sparepart_qty: Joi.number().integer().min(0),
sparepart_unit: Joi.string().max(255).optional(),
sparepart_merk: Joi.string().max(255).optional(),
sparepart_stok: Joi.string().max(255).optional(),
});
// Update Validation
const updateSparepartSchema = Joi.object({
sparepart_name: Joi.string().max(255).optional(),
sparepart_description: Joi.string().max(255).optional(),
sparepart_model: Joi.string().max(255).optional(),
sparepart_foto: Joi.string().max(255).optional().allow(''),
sparepart_item_type: Joi.string().max(255).optional(),
sparepart_qty: Joi.number().integer().min(0),
sparepart_unit: Joi.string().max(255).optional(),
sparepart_merk: Joi.string().max(255).optional(),
sparepart_stok: Joi.string().max(255).optional(),
});
module.exports = {
insertSparepartSchema,
updateSparepartSchema,
};

View File

@@ -1,35 +0,0 @@
const Joi = require("joi");
// ========================
// Plant Sub Section Validation
// ========================
const insertSubSectionSchema = Joi.object({
plant_sub_section_name: Joi.string()
.max(200)
.required()
.messages({
"string.base": "Sub section name must be a string",
"string.max": "Sub section name cannot exceed 200 characters",
"any.required": "Sub section name is required"
}).required(),
is_active: Joi.boolean().required(),
value: Joi.string().max(100).optional()
});
const updateSubSectionSchema = Joi.object({
plant_sub_section_namesub_section_name: Joi.string()
.max(200)
.messages({
"string.base": "Sub section name must be a string",
"string.max": "Sub section name cannot exceed 200 characters",
}).optional(),
is_active: Joi.boolean().optional(),
value: Joi.string().max(100).optional()
}).min(1).messages({
"object.min": "At least one field must be provided to update",
});
module.exports = {
insertSubSectionSchema,
updateSubSectionSchema
};

View File

@@ -8,6 +8,7 @@ const insertTagsSchema = Joi.object({
device_id: Joi.number().optional(),
tag_name: Joi.string().max(200).required(),
tag_number: Joi.number().required(),
tag_description: Joi.string().max(200).optional(),
is_active: Joi.boolean().optional(),
data_type: Joi.string().max(50).optional(),
unit: Joi.string().max(50).optional(),
@@ -22,9 +23,10 @@ const insertTagsSchema = Joi.object({
});
const updateTagsSchema = Joi.object({
device_id: Joi.number().required(),
device_id: Joi.number().optional(),
tag_name: Joi.string().max(200),
tag_number: Joi.number(),
tag_description: Joi.string().max(200).optional(),
is_active: Joi.boolean(),
data_type: Joi.string().max(50),
unit: Joi.string().max(50),

View File

@@ -5,16 +5,14 @@ const Joi = require("joi");
// ========================
const insertUnitSchema = Joi.object({
unit_name: Joi.string().max(100).required(),
tag_id: Joi.number().integer().optional(),
is_active: Joi.boolean().required(),
unit_description: Joi. string().max(255).optional()
unit_description: Joi.string().max(255).allow('')
});
const updateUnitSchema = Joi.object({
unit_name: Joi.string().max(100).optional(),
tag_id: Joi.number().integer().optional(),
is_active: Joi.boolean().optional(),
unit_description: Joi. string().max(255).optional()
unit_description: Joi.string().max(255).allow('')
}).min(1);
module.exports = {

View File

@@ -5,7 +5,7 @@ const Joi = require("joi");
// ========================
const insertUserScheduleSchema = Joi.object({
user_id: Joi.number().integer().required(),
schedule_id: Joi.number().integer().required(),
schedule_id: Joi.number().integer().optional(),
shift_id: Joi.number().required(),
});