Compare commits
89 Commits
31daa470b7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| c09d51591d | |||
| b680a249d5 | |||
| 2a2df58b7d | |||
| b1cf4ff624 | |||
| 747a96ac30 | |||
| 026a88a9a9 | |||
| ef491995f9 | |||
| 4d2c18edfb | |||
| d9975b832b | |||
| a4d8d55dbf | |||
| 205cb9d7cc | |||
| a6075174f5 | |||
| 41f5cc9011 | |||
| 3d163f4507 | |||
| bc265ccc33 | |||
| 6885443bc2 | |||
| cecdc09719 | |||
| f5494fb4a1 | |||
| 2a25339478 | |||
| ed77576958 | |||
| 3faa3656c1 | |||
| 9e862d1a48 | |||
| aa7cd2fbaa | |||
| 9913724d08 | |||
| f3abaeac39 | |||
| b025c5ea82 | |||
| 63a646fce3 | |||
| 6f4d171537 | |||
| 8d947a818b | |||
| 71c5e94f42 | |||
| 81e07ed927 | |||
| 0c16b2a3fd | |||
| 402c1c0705 | |||
| 019c79d5bc | |||
| adaa9fda9a | |||
| 3eb403c557 | |||
| bedc948a74 | |||
| 889aa04808 | |||
| 25ba80ab7e | |||
| fae6bb7a43 | |||
| a704eb3235 | |||
| 8ecb00a4d3 | |||
| 10b7ac5e68 | |||
| 37185a9fbc | |||
| b62ca35185 | |||
| c9dba276bb | |||
| 706fd401f4 | |||
| 518d6ff427 | |||
| 9f7a73e149 | |||
| bba50177e9 | |||
| 85750b397b | |||
|
|
1496b80fdf | ||
|
|
c112ff165a | ||
| 5e7de6d144 | |||
| dd5e1cc713 | |||
| 1aa7b1bc08 | |||
| f2c8c3818d | |||
| 907f5767c1 | |||
| 2b93baa648 | |||
| fb3061e0d1 | |||
| d063478fc2 | |||
| 555a68e90c | |||
| dc7712a79f | |||
| 20d035a1ca | |||
| 1d3de9ae41 | |||
| 198346ff0b | |||
| a8eb785a5b | |||
| 096fe9461d | |||
| 5e74122b9e | |||
| 050543dbbf | |||
| e1b397e1d3 | |||
| 34db6b8d89 | |||
| 5d1b6daef6 | |||
| 30431be379 | |||
| 361f750330 | |||
| 31f50d05ab | |||
| 961f0d6314 | |||
| d87fc07a8e | |||
| 95e0c90a16 | |||
| 55e8a6d9ca | |||
| 253d83357f | |||
| 88a0404af0 | |||
| d11207aedb | |||
| d7044521bd | |||
| e2a008c2e1 | |||
| 6d575f649a | |||
| e8fd307a05 | |||
| 00239db472 | |||
| 251f7148b6 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -3,4 +3,5 @@ node_modules
|
|||||||
.vscode
|
.vscode
|
||||||
request.http
|
request.http
|
||||||
*.rest
|
*.rest
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
*.log
|
||||||
9
app.js
9
app.js
@@ -8,7 +8,8 @@ const helmet = require("helmet");
|
|||||||
const compression = require("compression");
|
const compression = require("compression");
|
||||||
const unknownEndpoint = require("./middleware/unKnownEndpoint");
|
const unknownEndpoint = require("./middleware/unKnownEndpoint");
|
||||||
const { handleError } = require("./helpers/error");
|
const { handleError } = require("./helpers/error");
|
||||||
const { checkConnection } = require("./config");
|
const { checkConnection, mqttClient } = require("./config");
|
||||||
|
const { onNotification } = require("./services/notifikasi-wa.service");
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
@@ -47,4 +48,10 @@ app.get("/check-db", async (req, res) => {
|
|||||||
app.use(unknownEndpoint);
|
app.use(unknownEndpoint);
|
||||||
app.use(handleError);
|
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;
|
module.exports = app;
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
require("dotenv").config();
|
require("dotenv").config();
|
||||||
|
const { default: mqtt } = require("mqtt");
|
||||||
const sql = require("mssql");
|
const sql = require("mssql");
|
||||||
|
|
||||||
const isProduction = process.env.NODE_ENV === "production";
|
const isProduction = process.env.NODE_ENV === "production";
|
||||||
|
|
||||||
|
const endPointWhatsapp = process.env.ENDPOINT_WHATSAPP;
|
||||||
|
|
||||||
// Config SQL Server
|
// Config SQL Server
|
||||||
const config = {
|
const config = {
|
||||||
user: process.env.SQL_USERNAME,
|
user: process.env.SQL_USERNAME,
|
||||||
@@ -284,6 +287,34 @@ async function generateKode(prefix, tableName, columnName) {
|
|||||||
return prefix + String(nextNumber).padStart(3, "0");
|
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 = {
|
module.exports = {
|
||||||
checkConnection,
|
checkConnection,
|
||||||
query,
|
query,
|
||||||
@@ -293,4 +324,6 @@ module.exports = {
|
|||||||
buildDynamicInsert,
|
buildDynamicInsert,
|
||||||
buildDynamicUpdate,
|
buildDynamicUpdate,
|
||||||
generateKode,
|
generateKode,
|
||||||
|
endPointWhatsapp,
|
||||||
|
mqttClient
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ const AuthService = require('../services/auth.service');
|
|||||||
const { setResponse, checkValidate } = require('../helpers/utils');
|
const { setResponse, checkValidate } = require('../helpers/utils');
|
||||||
const { registerSchema, loginSchema } = require('../validate/auth.schema');
|
const { registerSchema, loginSchema } = require('../validate/auth.schema');
|
||||||
const { createCaptcha } = require('../utils/captcha');
|
const { createCaptcha } = require('../utils/captcha');
|
||||||
|
const JWTService = require('../utils/jwt');
|
||||||
|
|
||||||
|
const CryptoJS = require('crypto-js');
|
||||||
|
|
||||||
class AuthController {
|
class AuthController {
|
||||||
// Register
|
// Register
|
||||||
@@ -94,6 +97,42 @@ class AuthController {
|
|||||||
const response = await setResponse({ svg, text }, 'Captcha generated');
|
const response = await setResponse({ svg, text }, 'Captcha generated');
|
||||||
res.status(response.statusCode).json(response);
|
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;
|
module.exports = AuthController;
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ class BrandController {
|
|||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create brand with nested error codes and solutions
|
// Create brand
|
||||||
static async create(req, res) {
|
static async create(req, res) {
|
||||||
const { error, value } = await checkValidate(insertBrandSchema, req);
|
const { error, value } = await checkValidate(insertBrandSchema, req);
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ class BrandController {
|
|||||||
|
|
||||||
value.created_by = req.user?.user_id || null;
|
value.created_by = req.user?.user_id || null;
|
||||||
|
|
||||||
const results = await BrandService.createBrandWithFullData(value);
|
const results = await BrandService.createBrand(value);
|
||||||
const response = await setResponse(results, 'Brand created successfully');
|
const response = await setResponse(results, 'Brand created successfully');
|
||||||
|
|
||||||
return res.status(response.statusCode).json(response);
|
return res.status(response.statusCode).json(response);
|
||||||
@@ -49,29 +49,15 @@ class BrandController {
|
|||||||
static async update(req, res) {
|
static async update(req, res) {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
// Debug logging untuk lihat request body
|
|
||||||
console.log('🔍 BE Raw Request Body:', req.body);
|
|
||||||
console.log('🔍 BE Request Headers:', req.headers);
|
|
||||||
console.log('🔍 BE Request Method:', req.method);
|
|
||||||
|
|
||||||
const { error, value } = await checkValidate(updateBrandSchema, req);
|
const { error, value } = await checkValidate(updateBrandSchema, req);
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log('❌ BE Validation Error:', {
|
|
||||||
error,
|
|
||||||
details: error.details?.map(d => ({
|
|
||||||
field: d.path.join('.'),
|
|
||||||
message: d.message,
|
|
||||||
value: d.context?.value
|
|
||||||
})),
|
|
||||||
requestBody: req.body
|
|
||||||
});
|
|
||||||
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
}
|
}
|
||||||
|
|
||||||
value.updated_by = req.user?.user_id || null;
|
value.updated_by = req.user?.user_id || null;
|
||||||
|
|
||||||
const results = await BrandService.updateBrandWithFullData(id, value);
|
const results = await BrandService.updateBrand(id, value);
|
||||||
const response = await setResponse(results, 'Brand updated successfully');
|
const response = await setResponse(results, 'Brand updated successfully');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
const ErrorCodeService = require('../services/error_code.service');
|
const ErrorCodeService = require('../services/error_code.service');
|
||||||
const { setResponse, setResponsePaging } = require('../helpers/utils');
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const {
|
||||||
|
insertErrorCodeSchema,
|
||||||
|
updateErrorCodeSchema,
|
||||||
|
} = require('../validate/error_code.schema');
|
||||||
|
|
||||||
class ErrorCodeController {
|
class ErrorCodeController {
|
||||||
static async getByBrandId(req, res) {
|
static async getByBrandId(req, res) {
|
||||||
const { brandId } = req.params;
|
const { brandId } = req.params;
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await ErrorCodeService.getErrorCodesByBrandId(brandId);
|
const results = await ErrorCodeService.getErrorCodesByBrandId(brandId, queryParams);
|
||||||
const response = setResponse(results, 'Error codes found');
|
const response = await setResponsePaging(queryParams, results, 'Error codes found');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
}
|
}
|
||||||
@@ -22,15 +27,16 @@ class ErrorCodeController {
|
|||||||
|
|
||||||
// Create error code with solutions and spareparts
|
// Create error code with solutions and spareparts
|
||||||
static async create(req, res) {
|
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;
|
const { brandId } = req.params;
|
||||||
const createdBy = req.user?.user_id || null;
|
value.created_by = req.user?.user_id || null;
|
||||||
|
|
||||||
const data = {
|
const result = await ErrorCodeService.createErrorCodeWithFullData(brandId, value);
|
||||||
...req.body,
|
|
||||||
created_by: createdBy
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = await ErrorCodeService.createErrorCodeWithFullData(brandId, data);
|
|
||||||
const response = setResponse(result, 'Error code created successfully');
|
const response = setResponse(result, 'Error code created successfully');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
@@ -38,15 +44,16 @@ class ErrorCodeController {
|
|||||||
|
|
||||||
// Update error code with solutions and spareparts
|
// Update error code with solutions and spareparts
|
||||||
static async update(req, res) {
|
static async update(req, res) {
|
||||||
const { brandId, errorCode } = req.params;
|
const { error, value } = await checkValidate(updateErrorCodeSchema, req);
|
||||||
const updatedBy = req.user?.user_id || null;
|
|
||||||
|
|
||||||
const data = {
|
if (error) {
|
||||||
...req.body,
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
updated_by: updatedBy
|
}
|
||||||
};
|
|
||||||
|
|
||||||
const result = await ErrorCodeService.updateErrorCodeWithFullData(brandId, errorCode, data);
|
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');
|
const response = setResponse(result, 'Error code updated successfully');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
@@ -54,10 +61,10 @@ class ErrorCodeController {
|
|||||||
|
|
||||||
// Soft delete error code
|
// Soft delete error code
|
||||||
static async delete(req, res) {
|
static async delete(req, res) {
|
||||||
const { brandId, errorCode } = req.params;
|
const { brandId, errorCodeId } = req.params;
|
||||||
const deletedBy = req.user?.user_id || null;
|
const deletedBy = req.user?.user_id || null;
|
||||||
|
|
||||||
const result = await ErrorCodeService.deleteErrorCode(brandId, errorCode, deletedBy);
|
const result = await ErrorCodeService.deleteErrorCode(brandId, errorCodeId, deletedBy);
|
||||||
const response = setResponse(result, 'Error code deleted successfully');
|
const response = setResponse(result, 'Error code deleted successfully');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
|
|||||||
@@ -4,53 +4,102 @@ const { setResponsePaging } = require('../helpers/utils');
|
|||||||
class HistoryValueController {
|
class HistoryValueController {
|
||||||
|
|
||||||
static async getAllHistoryAlarm(req, res) {
|
static async getAllHistoryAlarm(req, res) {
|
||||||
const queryParams = req.query;
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await HistoryValue.getAllHistoryAlarm(queryParams);
|
const results = await HistoryValue.getAllHistoryAlarm(queryParams);
|
||||||
const response = await setResponsePaging(queryParams, results, 'Data found');
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
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) {
|
static async getAllHistoryEvent(req, res) {
|
||||||
const queryParams = req.query;
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await HistoryValue.getAllHistoryEvent(queryParams);
|
const results = await HistoryValue.getAllHistoryEvent(queryParams);
|
||||||
const response = await setResponsePaging(queryParams, results, 'Data found');
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
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) {
|
static async getHistoryValueReport(req, res) {
|
||||||
const queryParams = req.query;
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await HistoryValue.getHistoryValueReport(queryParams);
|
const results = await HistoryValue.getHistoryValueReport(queryParams);
|
||||||
const response = await setResponsePaging(queryParams, results, 'Data found');
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
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) {
|
static async getHistoryValueReportPivot(req, res) {
|
||||||
const queryParams = req.query;
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await HistoryValue.getHistoryValueReportPivot(queryParams);
|
const results = await HistoryValue.getHistoryValueReportPivot(queryParams);
|
||||||
const response = await setResponsePaging(queryParams, results, 'Data found');
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
response.columns = results.column
|
if (results.column) {
|
||||||
|
response.columns = results.column;
|
||||||
|
}
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
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) {
|
static async getHistoryValueTrendingPivot(req, res) {
|
||||||
const queryParams = req.query;
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await HistoryValue.getHistoryValueTrendingPivot(queryParams);
|
const results = await HistoryValue.getHistoryValueTrendingPivot(queryParams);
|
||||||
const response = await setResponsePaging(queryParams, results, 'Data found');
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
response.columns = results.column
|
if (results.column) {
|
||||||
|
response.columns = results.column;
|
||||||
|
}
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
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;
|
module.exports = HistoryValueController;
|
||||||
@@ -1,12 +1,26 @@
|
|||||||
const NotificationErrorService = require('../services/notification_error.service');
|
const NotificationErrorService = require("../services/notification_error.service");
|
||||||
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
const {
|
||||||
|
setResponse,
|
||||||
|
setResponsePaging,
|
||||||
|
checkValidate,
|
||||||
|
} = require("../helpers/utils");
|
||||||
|
const {
|
||||||
|
insertNotificationSchema,
|
||||||
|
updateNotificationSchema,
|
||||||
|
} = require("../validate/notification.schema");
|
||||||
|
|
||||||
class NotificationErrorController {
|
class NotificationErrorController {
|
||||||
static async getAll(req, res) {
|
static async getAll(req, res) {
|
||||||
const queryParams = req.query;
|
const queryParams = req.query;
|
||||||
|
|
||||||
const results = await NotificationErrorService.getAllNotification(queryParams);
|
const results = await NotificationErrorService.getAllNotification(
|
||||||
const response = await setResponsePaging(queryParams, results, 'Notification found')
|
queryParams
|
||||||
|
);
|
||||||
|
const response = await setResponsePaging(
|
||||||
|
queryParams,
|
||||||
|
results,
|
||||||
|
"Notification found"
|
||||||
|
);
|
||||||
|
|
||||||
res.status(response.statusCode).json(response);
|
res.status(response.statusCode).json(response);
|
||||||
}
|
}
|
||||||
@@ -15,11 +29,60 @@ class NotificationErrorController {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
const results = await NotificationErrorService.getNotificationById(id);
|
const results = await NotificationErrorService.getNotificationById(id);
|
||||||
const response = await setResponse(results, 'Notification retrieved successfully');
|
const response = await setResponse(
|
||||||
|
results,
|
||||||
|
"Notification retrieved successfully"
|
||||||
|
);
|
||||||
|
|
||||||
return res.status(response.statusCode).json(response);
|
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;
|
module.exports = NotificationErrorController;
|
||||||
|
|||||||
@@ -55,9 +55,7 @@ class NotificationErrorLogController {
|
|||||||
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
}
|
}
|
||||||
|
|
||||||
value.created_by = req.user.user_id;
|
const results = await NotificationErrorLogService.createNotificationErrorLog(value, req.user.user_id);
|
||||||
|
|
||||||
const results = await NotificationErrorLogService.createNotificationErrorLog(value);
|
|
||||||
const response = await setResponse(results, 'Notification Error Log created successfully')
|
const response = await setResponse(results, 'Notification Error Log created successfully')
|
||||||
|
|
||||||
return res.status(response.statusCode).json(response);
|
return res.status(response.statusCode).json(response);
|
||||||
|
|||||||
123
controllers/notification_error_user.controller.js
Normal file
123
controllers/notification_error_user.controller.js
Normal 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;
|
||||||
@@ -1,15 +1,55 @@
|
|||||||
const pool = require("../config");
|
const pool = require("../config");
|
||||||
|
|
||||||
// Get error codes by brand ID
|
// Get error codes by brand ID
|
||||||
const getErrorCodesByBrandIdDb = async (brandId) => {
|
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 = `
|
const queryText = `
|
||||||
SELECT
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
a.*
|
a.*
|
||||||
FROM brand_code a
|
FROM brand_code a
|
||||||
WHERE a.brand_id = $1 AND a.deleted_at IS NULL
|
WHERE a.brand_id = $1 AND a.deleted_at IS NULL
|
||||||
ORDER BY a.error_code_id
|
${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, [brandId]);
|
|
||||||
|
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;
|
return result.recordset;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const getSparepartsByErrorCodeIdDb = async (errorCodeId) => {
|
|||||||
s.sparepart_stok,
|
s.sparepart_stok,
|
||||||
bs.created_at,
|
bs.created_at,
|
||||||
bs.created_by
|
bs.created_by
|
||||||
FROM brand_spareparts bs
|
FROM brand_sparepart bs
|
||||||
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
||||||
WHERE bs.error_code_id = $1
|
WHERE bs.error_code_id = $1
|
||||||
AND s.deleted_at IS NULL
|
AND s.deleted_at IS NULL
|
||||||
@@ -40,7 +40,7 @@ const getErrorCodesBySparepartIdDb = async (sparepartId) => {
|
|||||||
ec.is_active,
|
ec.is_active,
|
||||||
ec.created_at,
|
ec.created_at,
|
||||||
ec.updated_at
|
ec.updated_at
|
||||||
FROM brand_spareparts bs
|
FROM brand_sparepart bs
|
||||||
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
|
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
|
||||||
WHERE bs.sparepart_id = $1
|
WHERE bs.sparepart_id = $1
|
||||||
AND ec.deleted_at IS NULL
|
AND ec.deleted_at IS NULL
|
||||||
@@ -53,7 +53,7 @@ const getErrorCodesBySparepartIdDb = async (sparepartId) => {
|
|||||||
// Insert error_code-spareparts relationship
|
// Insert error_code-spareparts relationship
|
||||||
const insertErrorCodeSparepartDb = async (errorCodeId, sparepartId, createdBy) => {
|
const insertErrorCodeSparepartDb = async (errorCodeId, sparepartId, createdBy) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
INSERT INTO brand_spareparts (error_code_id, sparepart_id, created_by, created_at)
|
INSERT INTO brand_sparepart (error_code_id, sparepart_id, created_by, created_at)
|
||||||
VALUES ($1, $2, $3, CURRENT_TIMESTAMP)
|
VALUES ($1, $2, $3, CURRENT_TIMESTAMP)
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [errorCodeId, sparepartId, createdBy]);
|
const result = await pool.query(queryText, [errorCodeId, sparepartId, createdBy]);
|
||||||
@@ -66,7 +66,7 @@ const insertMultipleErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, cr
|
|||||||
|
|
||||||
const values = sparepartIds.map((_, index) => `($1, $${index + 2}, $${sparepartIds.length + 2}, CURRENT_TIMESTAMP)`).join(', ');
|
const values = sparepartIds.map((_, index) => `($1, $${index + 2}, $${sparepartIds.length + 2}, CURRENT_TIMESTAMP)`).join(', ');
|
||||||
const queryText = `
|
const queryText = `
|
||||||
INSERT INTO brand_spareparts (error_code_id, sparepart_id, created_by, created_at)
|
INSERT INTO brand_sparepart (error_code_id, sparepart_id, created_by, created_at)
|
||||||
VALUES ${values}
|
VALUES ${values}
|
||||||
`;
|
`;
|
||||||
const params = [errorCodeId, ...sparepartIds, createdBy];
|
const params = [errorCodeId, ...sparepartIds, createdBy];
|
||||||
@@ -77,7 +77,7 @@ const insertMultipleErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, cr
|
|||||||
// Delete specific error_code-sparepart relationship
|
// Delete specific error_code-sparepart relationship
|
||||||
const deleteErrorCodeSparepartDb = async (errorCodeId, sparepartId) => {
|
const deleteErrorCodeSparepartDb = async (errorCodeId, sparepartId) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
DELETE FROM brand_spareparts
|
DELETE FROM brand_sparepart
|
||||||
WHERE error_code_id = $1 AND sparepart_id = $2
|
WHERE error_code_id = $1 AND sparepart_id = $2
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [errorCodeId, sparepartId]);
|
const result = await pool.query(queryText, [errorCodeId, sparepartId]);
|
||||||
@@ -87,7 +87,7 @@ const deleteErrorCodeSparepartDb = async (errorCodeId, sparepartId) => {
|
|||||||
// Delete all spareparts for an error_code
|
// Delete all spareparts for an error_code
|
||||||
const deleteAllErrorCodeSparepartsDb = async (errorCodeId) => {
|
const deleteAllErrorCodeSparepartsDb = async (errorCodeId) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
DELETE FROM brand_spareparts
|
DELETE FROM brand_sparepart
|
||||||
WHERE error_code_id = $1
|
WHERE error_code_id = $1
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [errorCodeId]);
|
const result = await pool.query(queryText, [errorCodeId]);
|
||||||
@@ -107,7 +107,6 @@ const updateErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, updatedBy)
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if error_code-sparepart relationship exists
|
|
||||||
const checkErrorCodeSparepartExistsDb = async (errorCodeId, sparepartId) => {
|
const checkErrorCodeSparepartExistsDb = async (errorCodeId, sparepartId) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT 1
|
SELECT 1
|
||||||
@@ -118,8 +117,6 @@ const checkErrorCodeSparepartExistsDb = async (errorCodeId, sparepartId) => {
|
|||||||
return result.recordset.length > 0;
|
return result.recordset.length > 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Legacy functions for backward compatibility (deprecated)
|
|
||||||
// Get spareparts by brand_id (now using error_code_id mapping via error codes)
|
|
||||||
const getSparepartsByBrandIdDb = async (brandId) => {
|
const getSparepartsByBrandIdDb = async (brandId) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT DISTINCT
|
SELECT DISTINCT
|
||||||
@@ -136,7 +133,7 @@ const getSparepartsByBrandIdDb = async (brandId) => {
|
|||||||
s.sparepart_stok,
|
s.sparepart_stok,
|
||||||
s.created_at,
|
s.created_at,
|
||||||
s.updated_at
|
s.updated_at
|
||||||
FROM brand_spareparts bs
|
FROM brand_sparepart bs
|
||||||
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
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_error_codes ec ON bs.error_code_id = ec.error_code_id
|
||||||
WHERE ec.brand_id = $1
|
WHERE ec.brand_id = $1
|
||||||
@@ -161,7 +158,7 @@ const getBrandsBySparepartIdDb = async (sparepartId) => {
|
|||||||
b.is_active,
|
b.is_active,
|
||||||
b.created_at,
|
b.created_at,
|
||||||
b.updated_at
|
b.updated_at
|
||||||
FROM brand_spareparts bs
|
FROM brand_sparepart bs
|
||||||
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
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_error_codes ec ON bs.error_code_id = ec.error_code_id
|
||||||
JOIN m_brands b ON ec.brand_id = b.brand_id
|
JOIN m_brands b ON ec.brand_id = b.brand_id
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const getAllContactDb = async (searchParams = {}) => {
|
|||||||
[
|
[
|
||||||
{ column: "a.contact_name", param: searchParams.name, type: "string" },
|
{ column: "a.contact_name", param: searchParams.name, type: "string" },
|
||||||
{ column: "a.contact_type", param: searchParams.code, type: "string" },
|
{ column: "a.contact_type", param: searchParams.code, type: "string" },
|
||||||
|
{ column: "a.is_active", param: searchParams.active, type: "boolean" },
|
||||||
],
|
],
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -115,160 +115,321 @@ const getHistoryEventDb = async (searchParams = {}) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const checkTableNamedDb = async (tableName) => {
|
const checkTableNamedDb = async (tableName) => {
|
||||||
const queryText = `
|
try {
|
||||||
SELECT *
|
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||||
FROM INFORMATION_SCHEMA.TABLES
|
throw new Error('Invalid table name format');
|
||||||
WHERE TABLE_NAME = $1;`;
|
}
|
||||||
const result = await pool.query(queryText, [tableName]);
|
|
||||||
return result.recordset;
|
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 = {}) => {
|
const getHistoryValueReportDb = async (tableName, searchParams = {}) => {
|
||||||
let queryParams = [];
|
try {
|
||||||
|
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||||
|
throw new Error('Invalid table name format');
|
||||||
|
}
|
||||||
|
|
||||||
if (searchParams.limit) {
|
let queryParams = [];
|
||||||
const page = Number(searchParams.page ?? 1) - 1;
|
|
||||||
queryParams = [Number(searchParams.limit ?? 10), page];
|
if (searchParams.limit) {
|
||||||
}
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
[
|
["b.tag_name", "CAST(a.tagnum AS VARCHAR)"],
|
||||||
"b.tag_name",
|
searchParams.criteria,
|
||||||
"a.tagnum"
|
queryParams
|
||||||
],
|
);
|
||||||
searchParams.criteria,
|
|
||||||
queryParams
|
|
||||||
);
|
|
||||||
|
|
||||||
if (whereParamOr) queryParams = whereParamOr;
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
[
|
[
|
||||||
{ column: "b.tag_name", param: searchParams.name, type: "string" },
|
{ column: "b.tag_name", param: searchParams.name, type: "string" },
|
||||||
{ column: "b.tag_number", param: searchParams.name, type: "number" },
|
{ column: "b.tag_number", param: searchParams.name, type: "number" },
|
||||||
{ column: "a.datetime", param: [searchParams.from, searchParams.to], type: "between" },
|
{ column: "a.datetime", param: [searchParams.from, searchParams.to], type: "between" },
|
||||||
],
|
],
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
|
|
||||||
if (whereParamAnd) queryParams = whereParamAnd;
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT
|
SELECT
|
||||||
COUNT(*) OVER() AS total_data,
|
COUNT(*) OVER() AS total_data,
|
||||||
a.*,
|
a.*,
|
||||||
b.tag_name,
|
b.tag_name,
|
||||||
b.tag_number,
|
b.tag_number,
|
||||||
b.lim_low_crash,
|
b.lim_low_crash,
|
||||||
b.lim_low,
|
b.lim_low,
|
||||||
b.lim_high,
|
b.lim_high,
|
||||||
b.lim_high_crash,
|
b.lim_high_crash,
|
||||||
c.status_color
|
c.status_color
|
||||||
FROM ${tableName} a
|
FROM ${tableName} a
|
||||||
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
|
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
|
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
|
WHERE a.datetime IS NOT NULL AND b.is_report = 1
|
||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
ORDER BY a.datetime DESC
|
ORDER BY a.datetime DESC
|
||||||
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await pool.query(queryText, queryParams);
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
const total =
|
const total = result.recordset?.length > 0
|
||||||
result?.recordset?.length > 0
|
|
||||||
? parseInt(result.recordset[0].total_data, 10)
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
return { data: result.recordset, total };
|
return { data: result.recordset, total };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getHistoryValueReportDb:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getHistoryValueReportPivotDb = async (tableName, searchParams = {}) => {
|
const getHistoryValueReportPivotDb = async (tableName, searchParams = {}) => {
|
||||||
let from = searchParams.from;
|
try {
|
||||||
let to = searchParams.to;
|
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||||
const interval = Number(searchParams.interval ?? 10); // menit
|
throw new Error('Invalid table name format');
|
||||||
const limit = Number(searchParams.limit ?? 10);
|
}
|
||||||
const page = Number(searchParams.page ?? 1);
|
|
||||||
|
|
||||||
// --- Normalisasi tanggal
|
let from = searchParams.from || '';
|
||||||
if (from.length === 10) from += ' 00:00:00';
|
let to = searchParams.to || '';
|
||||||
if (to.length === 10) to += ' 23:59:59';
|
const interval = Math.max(1, Math.min(1440, Number(searchParams.interval ?? 10)));
|
||||||
|
|
||||||
// --- Ambil semua tag yang di-report
|
if (from.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(from)) {
|
||||||
const tags = await pool.query(`
|
from += ' 00:00:00';
|
||||||
SELECT tag_name
|
}
|
||||||
FROM m_tags
|
if (to.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(to)) {
|
||||||
WHERE is_report = 1 AND deleted_at IS NULL
|
to += ' 23:59:59';
|
||||||
`);
|
}
|
||||||
|
|
||||||
if (tags.recordset.length === 0) {
|
console.log('Table:', tableName);
|
||||||
return { data: [], total: 0 };
|
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 tagNames = tags.recordset.map(r => `[${r.tag_name}]`).join(', ');
|
|
||||||
const tagNamesColumn = tags.recordset.map(r => `${r.tag_name}`).join(', ');
|
|
||||||
|
|
||||||
// --- Query utama
|
|
||||||
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
|
|
||||||
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
|
|
||||||
),
|
|
||||||
FinalResult AS (
|
|
||||||
SELECT
|
|
||||||
CONVERT(VARCHAR(16), ts.waktu, 120) AS datetime,
|
|
||||||
${tagNames}
|
|
||||||
FROM TimeSeries ts
|
|
||||||
LEFT JOIN Pivoted p ON ts.waktu = p.waktu_group
|
|
||||||
)
|
|
||||||
SELECT
|
|
||||||
COUNT(*) OVER() AS total_data,
|
|
||||||
*
|
|
||||||
FROM FinalResult
|
|
||||||
ORDER BY datetime
|
|
||||||
${searchParams.limit ? `OFFSET ${(page - 1) * limit} ROWS FETCH NEXT ${limit} ROWS ONLY` : ''}
|
|
||||||
OPTION (MAXRECURSION 0);
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await pool.query(queryText);
|
|
||||||
|
|
||||||
const total =
|
|
||||||
result?.recordset?.length > 0
|
|
||||||
? parseInt(result.recordset[0].total_data, 10)
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
return { data: result.recordset, column: tagNamesColumn, total };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
|
const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
|
||||||
@@ -282,18 +443,55 @@ const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
|
|||||||
if (from.length === 10) from += ' 00:00:00';
|
if (from.length === 10) from += ' 00:00:00';
|
||||||
if (to.length === 10) to += ' 23:59:59';
|
if (to.length === 10) to += ' 23:59:59';
|
||||||
|
|
||||||
// --- Ambil semua tag yang di-report
|
let tagQueryParams = [];
|
||||||
const tags = await pool.query(`
|
let tagWhereConditions = [];
|
||||||
SELECT tag_name
|
|
||||||
|
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
|
FROM m_tags
|
||||||
WHERE is_report = 1 AND deleted_at IS NULL
|
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) {
|
if (tags.recordset.length === 0) {
|
||||||
return { data: [] };
|
return { data: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
const tagNames = tags.recordset.map(r => `[${r.tag_name}]`).join(', ');
|
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 = `
|
const queryText = `
|
||||||
DECLARE
|
DECLARE
|
||||||
@@ -316,6 +514,7 @@ const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
|
|||||||
FROM ${tableName} a
|
FROM ${tableName} a
|
||||||
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
|
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
|
||||||
WHERE a.datetime BETWEEN @fromParam AND @toParam
|
WHERE a.datetime BETWEEN @fromParam AND @toParam
|
||||||
|
${tagNumbersFilter}
|
||||||
GROUP BY
|
GROUP BY
|
||||||
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, CAST(a.datetime AS DATETIME)) / @intervalParam * @intervalParam, 0),
|
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, CAST(a.datetime AS DATETIME)) / @intervalParam * @intervalParam, 0),
|
||||||
b.tag_name
|
b.tag_name
|
||||||
@@ -359,7 +558,6 @@ const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
|
|||||||
return { data: nivoData };
|
return { data: nivoData };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getHistoryAlarmDb,
|
getHistoryAlarmDb,
|
||||||
getHistoryEventDb,
|
getHistoryEventDb,
|
||||||
@@ -367,4 +565,4 @@ module.exports = {
|
|||||||
getHistoryValueReportDb,
|
getHistoryValueReportDb,
|
||||||
getHistoryValueReportPivotDb,
|
getHistoryValueReportPivotDb,
|
||||||
getHistoryValueTrendingPivotDb
|
getHistoryValueTrendingPivotDb
|
||||||
};
|
};
|
||||||
@@ -1,71 +1,68 @@
|
|||||||
const pool = require("../config");
|
const pool = require("../config");
|
||||||
|
|
||||||
const InsertNotificationErrorDb = async () => {
|
const InsertNotificationErrorDb = async (store) => {
|
||||||
const insertQuery = `
|
const { query: queryText, values } = pool.buildDynamicInsert(
|
||||||
INSERT INTO notification_error (
|
"notification_error",
|
||||||
error_code_id,
|
store
|
||||||
is_active,
|
);
|
||||||
is_delivered,
|
const result = await pool.query(queryText, values);
|
||||||
is_read,
|
const insertedId = result.recordset?.[0]?.inserted_id;
|
||||||
is_send,
|
|
||||||
message_error_issue
|
|
||||||
)
|
|
||||||
SELECT
|
|
||||||
b.error_code_id,
|
|
||||||
1 AS is_active,
|
|
||||||
1 AS is_delivered,
|
|
||||||
0 AS is_read,
|
|
||||||
1 AS is_send,
|
|
||||||
|
|
||||||
CONCAT(
|
return insertedId ? await getNotificationByIdDb(insertedId) : null;
|
||||||
COALESCE(b.error_code_description, '-'),
|
|
||||||
' pada ',
|
|
||||||
COALESCE(d.device_name, '-'),
|
|
||||||
'. Pengecekan potensi kerusakan dibutuhkan'
|
|
||||||
) AS message_error_issue
|
|
||||||
|
|
||||||
FROM brand_code b
|
|
||||||
|
|
||||||
LEFT JOIN notification_error a
|
|
||||||
ON a.error_code_id = b.error_code_id
|
|
||||||
AND a.deleted_at IS NULL
|
|
||||||
|
|
||||||
LEFT JOIN m_device d
|
|
||||||
ON b.brand_id = d.brand_id
|
|
||||||
AND d.deleted_at IS NULL
|
|
||||||
|
|
||||||
WHERE b.deleted_at IS NULL
|
|
||||||
AND a.notification_error_id IS NULL;
|
|
||||||
`;
|
|
||||||
|
|
||||||
await pool.query(insertQuery);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getNotificationByIdDb = async (id) => {
|
const getNotificationByIdDb = async (id) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT
|
SELECT
|
||||||
a.*
|
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
|
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
|
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [id]);
|
const result = await pool.query(queryText, [id]);
|
||||||
return result.recordset[0];
|
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 = {}) => {
|
const getAllNotificationDb = async (searchParams = {}) => {
|
||||||
let queryParams = [];
|
let queryParams = [];
|
||||||
|
|
||||||
await InsertNotificationErrorDb();
|
|
||||||
|
|
||||||
const boolFields = ["is_send", "is_delivered", "is_read", "is_active"];
|
|
||||||
|
|
||||||
boolFields.forEach((f) => {
|
|
||||||
if (searchParams[f] !== undefined && searchParams[f] !== null && searchParams[f] !== "") {
|
|
||||||
const v = searchParams[f];
|
|
||||||
searchParams[f] = v == "1" ? 1 : v == "0" ? 0 : null;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (searchParams.limit) {
|
if (searchParams.limit) {
|
||||||
const page = Number(searchParams.page ?? 1) - 1;
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
queryParams = [Number(searchParams.limit ?? 10), page];
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
@@ -73,13 +70,13 @@ const getAllNotificationDb = async (searchParams = {}) => {
|
|||||||
|
|
||||||
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
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",
|
||||||
"b.error_code_name",
|
"b.error_code_name",
|
||||||
"c.solution_name",
|
|
||||||
"COALESCE(a.is_send, 0)",
|
|
||||||
"COALESCE(a.is_delivered, 0)",
|
|
||||||
"COALESCE(a.is_read, 0)",
|
|
||||||
"COALESCE(a.is_active, 0)",
|
|
||||||
],
|
],
|
||||||
searchParams.criteria,
|
searchParams.criteria,
|
||||||
queryParams
|
queryParams
|
||||||
@@ -88,10 +85,13 @@ const getAllNotificationDb = async (searchParams = {}) => {
|
|||||||
|
|
||||||
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
[
|
[
|
||||||
{ column: "COALESCE(a.is_send, 0)", param: searchParams.is_send, type: "number" },
|
{ column: "a.message_error_issue", param: searchParams.message_error_issue, type: "string" },
|
||||||
{ column: "COALESCE(a.is_delivered, 0)", param: searchParams.is_delivered, type: "number" },
|
{ column: "a.is_send", param: searchParams.is_send, type: "number" },
|
||||||
{ column: "COALESCE(a.is_read, 0)", param: searchParams.is_read, type: "number" },
|
{ column: "a.is_delivered", param: searchParams.is_delivered, type: "number" },
|
||||||
{ column: "COALESCE(a.is_active, 0)", param: searchParams.is_active, 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
|
queryParams
|
||||||
);
|
);
|
||||||
@@ -111,24 +111,35 @@ const getAllNotificationDb = async (searchParams = {}) => {
|
|||||||
|
|
||||||
b.error_code,
|
b.error_code,
|
||||||
b.error_code_name,
|
b.error_code_name,
|
||||||
|
b.error_code_color,
|
||||||
|
b.path_icon,
|
||||||
b.created_at,
|
b.created_at,
|
||||||
|
|
||||||
c.solution_name,
|
c.solution_name,
|
||||||
c.type_solution,
|
c.type_solution,
|
||||||
c.path_solution,
|
c.path_solution,
|
||||||
|
|
||||||
|
d.device_code,
|
||||||
d.device_name,
|
d.device_name,
|
||||||
d.device_location,
|
d.device_location,
|
||||||
|
d.listen_channel,
|
||||||
|
e.brand_name,
|
||||||
|
|
||||||
COALESCE(d.device_name, '') + ' - ' + COALESCE(b.error_code_name, '') AS device_name_error
|
COALESCE(d.device_name, '') + ' - ' + COALESCE(b.error_code_name, '') AS device_name_error
|
||||||
|
|
||||||
FROM notification_error a
|
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 b
|
||||||
LEFT JOIN brand_code_solution c
|
ON a.error_code_id = b.error_code_id AND b.deleted_at IS NULL
|
||||||
ON b.error_code_id = c.error_code_id AND c.deleted_at IS NULL
|
|
||||||
LEFT JOIN m_device d
|
LEFT JOIN brand_code_solution c
|
||||||
ON b.brand_id = d.brand_id AND d.deleted_at IS NULL
|
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
|
WHERE a.deleted_at IS NULL
|
||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
@@ -149,8 +160,51 @@ const getAllNotificationDb = async (searchParams = {}) => {
|
|||||||
return { data: result.recordset, total };
|
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 = {
|
module.exports = {
|
||||||
getNotificationByIdDb,
|
getNotificationByIdDb,
|
||||||
|
getDeviceNotificationByIdDb,
|
||||||
getAllNotificationDb,
|
getAllNotificationDb,
|
||||||
|
InsertNotificationErrorDb,
|
||||||
|
updateNotificationErrorDb,
|
||||||
|
getUsersNotificationErrorDb
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ const getAllNotificationErrorLogDb = async () => {
|
|||||||
b.contact_name,
|
b.contact_name,
|
||||||
b.contact_type
|
b.contact_type
|
||||||
FROM notification_error_log a
|
FROM notification_error_log a
|
||||||
LEFT JOIN contact b ON a.contact_id = b.contact_id
|
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
|
||||||
WHERE a.deleted_at IS NULL
|
WHERE a.deleted_at IS NULL
|
||||||
ORDER BY a.notification_error_log_id DESC
|
ORDER BY a.notification_error_log_id DESC
|
||||||
`;
|
`;
|
||||||
@@ -22,7 +22,7 @@ const getNotificationErrorLogByIdDb = async (id) => {
|
|||||||
b.contact_name,
|
b.contact_name,
|
||||||
b.contact_type
|
b.contact_type
|
||||||
FROM notification_error_log a
|
FROM notification_error_log a
|
||||||
LEFT JOIN contact b ON a.contact_id = b.contact_id
|
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
|
||||||
WHERE a.notification_error_log_id = $1 AND a.deleted_at IS NULL
|
WHERE a.notification_error_log_id = $1 AND a.deleted_at IS NULL
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [id]);
|
const result = await pool.query(queryText, [id]);
|
||||||
@@ -32,11 +32,15 @@ const getNotificationErrorLogByIdDb = async (id) => {
|
|||||||
const getNotificationErrorLogByNotificationErrorIdDb = async (notificationErrorId) => {
|
const getNotificationErrorLogByNotificationErrorIdDb = async (notificationErrorId) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT
|
SELECT
|
||||||
a.*,
|
a.notification_error_log_description,
|
||||||
b.contact_name,
|
a.created_at,
|
||||||
b.contact_type
|
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
|
FROM notification_error_log a
|
||||||
LEFT JOIN contact b ON a.contact_id = b.contact_id
|
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
|
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
|
||||||
ORDER BY a.created_at DESC
|
ORDER BY a.created_at DESC
|
||||||
`;
|
`;
|
||||||
@@ -45,7 +49,27 @@ const getNotificationErrorLogByNotificationErrorIdDb = async (notificationErrorI
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createNotificationErrorLogDb = async (store) => {
|
const createNotificationErrorLogDb = async (store) => {
|
||||||
const { query: queryText, values } = pool.buildDynamicInsert("notification_error_log", 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 result = await pool.query(queryText, values);
|
||||||
const insertedId = result.recordset[0]?.inserted_id;
|
const insertedId = result.recordset[0]?.inserted_id;
|
||||||
return insertedId ? await getNotificationErrorLogByIdDb(insertedId) : null;
|
return insertedId ? await getNotificationErrorLogByIdDb(insertedId) : null;
|
||||||
|
|||||||
@@ -1,6 +1,34 @@
|
|||||||
const pool = require("../config");
|
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 = {}) => {
|
const getAllNotificationErrorSparepartDb = async (searchParams = {}) => {
|
||||||
|
await insertNotificationErrorSparepartDb();
|
||||||
let queryParams = [];
|
let queryParams = [];
|
||||||
|
|
||||||
if (searchParams.limit) {
|
if (searchParams.limit) {
|
||||||
|
|||||||
147
db/notification_error_user.db.js
Normal file
147
db/notification_error_user.db.js
Normal 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
62
db/notification_wa.db.js
Normal 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,
|
||||||
|
};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
apps: [
|
apps: [
|
||||||
{
|
{
|
||||||
name: "bengkel-api",
|
name: "cod-api",
|
||||||
script: "./index.js", // Path to your entry file
|
script: "./index.js", // Path to your entry file
|
||||||
env: {
|
env: {
|
||||||
NODE_ENV: "development",
|
NODE_ENV: "development",
|
||||||
@@ -9,6 +9,14 @@ module.exports = {
|
|||||||
env_production: {
|
env_production: {
|
||||||
NODE_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
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
const { ErrorHandler } = require("../helpers/error");
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
const { getUserByIdDb } = require("../db/user.db");
|
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) => {
|
const verifyAccess = (minLevel = 1, allowUnapprovedReadOnly = false) => {
|
||||||
return async (req, res, next) => {
|
return async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
@@ -11,21 +15,31 @@ const verifyAccess = (minLevel = 1, allowUnapprovedReadOnly = false) => {
|
|||||||
// Super Admin bypass semua
|
// Super Admin bypass semua
|
||||||
if (user.is_sa) return next();
|
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 (!isPhoneNumberID(user.user_id) && user.user_id) {
|
||||||
if (req.method !== "GET") {
|
const fullUser = await getUserByIdDb(user.user_id);
|
||||||
throw new ErrorHandler(403, "Account not approved — read-only access");
|
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();
|
next();
|
||||||
|
|||||||
@@ -7,5 +7,6 @@ router.post('/login', AuthController.login);
|
|||||||
router.post('/register', AuthController.register);
|
router.post('/register', AuthController.register);
|
||||||
router.get('/generate-captcha', AuthController.generateCaptcha);
|
router.get('/generate-captcha', AuthController.generateCaptcha);
|
||||||
router.post('/refresh-token', AuthController.refreshToken);
|
router.post('/refresh-token', AuthController.refreshToken);
|
||||||
|
router.post('/verify-redirect', AuthController.verifyTokenRedirect);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
@@ -9,7 +9,7 @@ router.route('/brand/:brandId')
|
|||||||
.get(verifyToken.verifyAccessToken, ErrorCodeController.getByBrandId)
|
.get(verifyToken.verifyAccessToken, ErrorCodeController.getByBrandId)
|
||||||
.post(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.create);
|
.post(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.create);
|
||||||
|
|
||||||
router.route('/brand/:brandId/:errorCode')
|
router.route('/brand/:brandId/:errorCodeId')
|
||||||
.put(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.update)
|
.put(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.update)
|
||||||
.delete(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.delete);
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.delete);
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ const notificationError = require("./notification_error.route")
|
|||||||
const notificationErrorSparepart = require("./notification_error_sparepart.route")
|
const notificationErrorSparepart = require("./notification_error_sparepart.route")
|
||||||
const sparepart = require("./sparepart.route")
|
const sparepart = require("./sparepart.route")
|
||||||
const notificationErrorLog = require("./notification_error_log.route")
|
const notificationErrorLog = require("./notification_error_log.route")
|
||||||
|
const notificationErrorUser = require("./notification_error_user.route")
|
||||||
const errorCode = require("./error_code.route")
|
const errorCode = require("./error_code.route")
|
||||||
|
|
||||||
router.use("/auth", auth);
|
router.use("/auth", auth);
|
||||||
@@ -39,6 +40,7 @@ router.use("/notification", notificationError)
|
|||||||
router.use("/notification-sparepart", notificationErrorSparepart)
|
router.use("/notification-sparepart", notificationErrorSparepart)
|
||||||
router.use("/sparepart", sparepart)
|
router.use("/sparepart", sparepart)
|
||||||
router.use("/notification-log", notificationErrorLog)
|
router.use("/notification-log", notificationErrorLog)
|
||||||
|
router.use("/notification-user", notificationErrorUser)
|
||||||
router.use("/error-code", errorCode)
|
router.use("/error-code", errorCode)
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -1,16 +1,40 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const NotificationErrorController = require('../controllers/notification_error.controller');
|
const NotificationErrorController = require("../controllers/notification_error.controller");
|
||||||
const verifyToken = require('../middleware/verifyToken');
|
const verifyToken = require("../middleware/verifyToken");
|
||||||
const verifyAccess = require('../middleware/verifyAccess');
|
const verifyAccess = require("../middleware/verifyAccess");
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router
|
router
|
||||||
.route('/')
|
.route("/")
|
||||||
.get(verifyToken.verifyAccessToken, NotificationErrorController.getAll)
|
.get(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.getAll
|
||||||
|
);
|
||||||
|
|
||||||
router
|
router
|
||||||
.route('/:id')
|
.route("/")
|
||||||
|
.post(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.create
|
||||||
|
);
|
||||||
|
|
||||||
|
router
|
||||||
|
.route("/:id")
|
||||||
.get(verifyToken.verifyAccessToken, NotificationErrorController.getById)
|
.get(verifyToken.verifyAccessToken, NotificationErrorController.getById)
|
||||||
|
.put(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.update
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
"/resend/:id",
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.resend
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ const router = express.Router();
|
|||||||
|
|
||||||
router.route("/")
|
router.route("/")
|
||||||
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getAll)
|
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getAll)
|
||||||
.post(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorLogController.create);
|
.post(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorLogController.create);
|
||||||
|
|
||||||
router.route("/:id")
|
router.route("/:id")
|
||||||
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getById);
|
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getById);
|
||||||
|
|||||||
38
routes/notification_error_user.route.js
Normal file
38
routes/notification_error_user.route.js
Normal 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;
|
||||||
@@ -7,32 +7,6 @@ const {
|
|||||||
deleteBrandDb,
|
deleteBrandDb,
|
||||||
checkBrandNameExistsDb,
|
checkBrandNameExistsDb,
|
||||||
} = require("../db/brand.db");
|
} = require("../db/brand.db");
|
||||||
|
|
||||||
const {
|
|
||||||
insertMultipleErrorCodeSparepartsDb,
|
|
||||||
updateErrorCodeSparepartsDb,
|
|
||||||
getSparepartsByErrorCodeIdDb,
|
|
||||||
} = require("../db/brand_sparepart.db");
|
|
||||||
|
|
||||||
// Error code operations
|
|
||||||
const {
|
|
||||||
getErrorCodesByBrandIdDb,
|
|
||||||
createErrorCodeDb,
|
|
||||||
updateErrorCodeDb,
|
|
||||||
deleteErrorCodeDb,
|
|
||||||
} = require("../db/brand_code.db");
|
|
||||||
|
|
||||||
// Sparepart operations
|
|
||||||
const { getSparepartsByIdsDb } = require("../db/sparepart.db");
|
|
||||||
|
|
||||||
// Solution operations
|
|
||||||
const {
|
|
||||||
getSolutionsByErrorCodeIdDb,
|
|
||||||
createSolutionDb,
|
|
||||||
updateSolutionDb,
|
|
||||||
deleteSolutionDb,
|
|
||||||
} = require("../db/brand_code_solution.db");
|
|
||||||
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
|
|
||||||
const { ErrorHandler } = require("../helpers/error");
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
|
||||||
class BrandService {
|
class BrandService {
|
||||||
@@ -41,7 +15,6 @@ class BrandService {
|
|||||||
try {
|
try {
|
||||||
const results = await getAllBrandsDb(param);
|
const results = await getAllBrandsDb(param);
|
||||||
|
|
||||||
// Return brands data - spareparts are now associated with error codes, not brands
|
|
||||||
return {
|
return {
|
||||||
...results,
|
...results,
|
||||||
data: results.data
|
data: results.data
|
||||||
@@ -65,10 +38,8 @@ class BrandService {
|
|||||||
|
|
||||||
|
|
||||||
// Create brand
|
// Create brand
|
||||||
static async createBrandWithFullData(data) {
|
static async createBrand(data) {
|
||||||
try {
|
try {
|
||||||
if (!data || typeof data !== "object") data = {};
|
|
||||||
|
|
||||||
if (data.brand_name) {
|
if (data.brand_name) {
|
||||||
const brandExists = await checkBrandNameExistsDb(data.brand_name);
|
const brandExists = await checkBrandNameExistsDb(data.brand_name);
|
||||||
if (brandExists) {
|
if (brandExists) {
|
||||||
@@ -76,85 +47,23 @@ class BrandService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
|
||||||
!data.error_code ||
|
|
||||||
!Array.isArray(data.error_code) ||
|
|
||||||
data.error_code.length === 0
|
|
||||||
) {
|
|
||||||
throw new ErrorHandler(
|
|
||||||
400,
|
|
||||||
"Brand must have at least 1 error code with solution"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const errorCode of data.error_code) {
|
|
||||||
if (
|
|
||||||
!errorCode.solution ||
|
|
||||||
!Array.isArray(errorCode.solution) ||
|
|
||||||
errorCode.solution.length === 0
|
|
||||||
) {
|
|
||||||
throw new ErrorHandler(
|
|
||||||
400,
|
|
||||||
`Error code ${errorCode.error_code} must have at least 1 solution`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const brandData = {
|
const brandData = {
|
||||||
brand_name: data.brand_name,
|
brand_name: data.brand_name,
|
||||||
brand_type: data.brand_type,
|
brand_type: data.brand_type,
|
||||||
brand_manufacture: data.brand_manufacture,
|
brand_manufacture: data.brand_manufacture,
|
||||||
brand_model: data.brand_model,
|
brand_model: data.brand_model,
|
||||||
is_active: data.is_active,
|
is_active: data.is_active !== undefined ? data.is_active : true,
|
||||||
created_by: data.created_by,
|
created_by: data.created_by,
|
||||||
};
|
};
|
||||||
|
|
||||||
const createdBrand = await createBrandDb(brandData);
|
const createdBrand = await createBrandDb(brandData);
|
||||||
if (!createdBrand) {
|
if (!createdBrand) {
|
||||||
throw new Error("Failed to create brand");
|
throw new ErrorHandler(500, "Failed to create brand");
|
||||||
}
|
}
|
||||||
|
|
||||||
const brandId = createdBrand.brand_id;
|
return createdBrand;
|
||||||
|
|
||||||
for (const errorCodeData of data.error_code) {
|
|
||||||
const errorId = await createErrorCodeDb(brandId, {
|
|
||||||
error_code: errorCodeData.error_code,
|
|
||||||
error_code_name: errorCodeData.error_code_name,
|
|
||||||
error_code_description: errorCodeData.error_code_description,
|
|
||||||
error_code_color: errorCodeData.error_code_color,
|
|
||||||
path_icon: errorCodeData.path_icon,
|
|
||||||
is_active: errorCodeData.is_active,
|
|
||||||
created_by: data.created_by,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!errorId) {
|
|
||||||
throw new Error("Failed to create error code");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create sparepart relationships for this error code
|
|
||||||
if (errorCodeData.spareparts && Array.isArray(errorCodeData.spareparts)) {
|
|
||||||
await insertMultipleErrorCodeSparepartsDb(errorId, errorCodeData.spareparts, data.created_by);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create solutions for this error code
|
|
||||||
if (errorCodeData.solution && Array.isArray(errorCodeData.solution)) {
|
|
||||||
for (const solutionData of errorCodeData.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 createdBrandWithSpareparts = await this.getBrandById(brandId);
|
|
||||||
return createdBrandWithSpareparts;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(500, `Bulk insert failed: ${error.message}`);
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,12 +86,11 @@ class BrandService {
|
|||||||
|
|
||||||
|
|
||||||
// Update brand
|
// Update brand
|
||||||
static async updateBrandWithFullData(id, data) {
|
static async updateBrand(id, data) {
|
||||||
try {
|
try {
|
||||||
const existingBrand = await getBrandByIdDb(id);
|
const existingBrand = await getBrandByIdDb(id);
|
||||||
if (!existingBrand) throw new ErrorHandler(404, "Brand not found");
|
if (!existingBrand) throw new ErrorHandler(404, "Brand not found");
|
||||||
|
|
||||||
|
|
||||||
if (data.brand_name && data.brand_name !== existingBrand.brand_name) {
|
if (data.brand_name && data.brand_name !== existingBrand.brand_name) {
|
||||||
const brandExists = await checkBrandNameExistsDb(data.brand_name, id);
|
const brandExists = await checkBrandNameExistsDb(data.brand_name, id);
|
||||||
if (brandExists) {
|
if (brandExists) {
|
||||||
@@ -191,147 +99,22 @@ class BrandService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const brandData = {
|
const brandData = {
|
||||||
brand_name: data.brand_name,
|
brand_name: data.brand_name || existingBrand.brand_name,
|
||||||
brand_type: data.brand_type,
|
brand_type: data.brand_type !== undefined ? data.brand_type : existingBrand.brand_type,
|
||||||
brand_manufacture: data.brand_manufacture,
|
brand_manufacture: data.brand_manufacture !== undefined ? data.brand_manufacture : existingBrand.brand_manufacture,
|
||||||
brand_model: data.brand_model,
|
brand_model: data.brand_model !== undefined ? data.brand_model : existingBrand.brand_model,
|
||||||
is_active: data.is_active,
|
is_active: data.is_active !== undefined ? data.is_active : existingBrand.is_active,
|
||||||
updated_by: data.updated_by,
|
updated_by: data.updated_by,
|
||||||
};
|
};
|
||||||
|
|
||||||
await updateBrandDb(existingBrand.brand_name, brandData);
|
const updatedBrand = await updateBrandDb(existingBrand.brand_name, brandData);
|
||||||
|
if (!updatedBrand) {
|
||||||
if (data.error_code && Array.isArray(data.error_code)) {
|
throw new ErrorHandler(500, "Failed to update brand");
|
||||||
const existingErrorCodes = await getErrorCodesByBrandIdDb(id);
|
|
||||||
const incomingErrorCodes = data.error_code.map((ec) => ec.error_code);
|
|
||||||
|
|
||||||
// Create/update/delete error codes
|
|
||||||
for (const errorCodeData of data.error_code) {
|
|
||||||
// Check if error code already exists
|
|
||||||
const existingEC = existingErrorCodes.find(
|
|
||||||
(ec) => ec.error_code === errorCodeData.error_code
|
|
||||||
);
|
|
||||||
|
|
||||||
if (existingEC) {
|
|
||||||
// Update existing error code using separate db function
|
|
||||||
await updateErrorCodeDb(
|
|
||||||
existingEC.brand_id,
|
|
||||||
existingEC.error_code,
|
|
||||||
{
|
|
||||||
error_code_name: errorCodeData.error_code_name,
|
|
||||||
error_code_description: errorCodeData.error_code_description,
|
|
||||||
error_code_color: errorCodeData.error_code_color,
|
|
||||||
path_icon: errorCodeData.path_icon,
|
|
||||||
is_active: errorCodeData.is_active,
|
|
||||||
updated_by: data.updated_by,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (errorCodeData.spareparts && Array.isArray(errorCodeData.spareparts)) {
|
|
||||||
await updateErrorCodeSparepartsDb(existingEC.error_code_id, errorCodeData.spareparts, data.updated_by);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
errorCodeData.solution &&
|
|
||||||
Array.isArray(errorCodeData.solution)
|
|
||||||
) {
|
|
||||||
const existingSolutions = await getSolutionsByErrorCodeIdDb(
|
|
||||||
existingEC.error_code_id
|
|
||||||
);
|
|
||||||
const incomingSolutionNames = errorCodeData.solution.map(
|
|
||||||
(s) => s.solution_name
|
|
||||||
);
|
|
||||||
|
|
||||||
// Update or create solutions
|
|
||||||
for (const solutionData of errorCodeData.solution) {
|
|
||||||
const existingSolution = existingSolutions.find(
|
|
||||||
(s) => s.solution_name === solutionData.solution_name
|
|
||||||
);
|
|
||||||
|
|
||||||
if (existingSolution) {
|
|
||||||
// Update existing solution
|
|
||||||
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 {
|
|
||||||
// Create new solution
|
|
||||||
await createSolutionDb(existingEC.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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete solutions that are not in the incoming request
|
|
||||||
for (const existingSolution of existingSolutions) {
|
|
||||||
if (
|
|
||||||
!incomingSolutionNames.includes(
|
|
||||||
existingSolution.solution_name
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
await deleteSolutionDb(
|
|
||||||
existingSolution.brand_code_solution_id,
|
|
||||||
data.updated_by
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const errorId = await createErrorCodeDb(id, {
|
|
||||||
error_code: errorCodeData.error_code,
|
|
||||||
error_code_name: errorCodeData.error_code_name,
|
|
||||||
error_code_description: errorCodeData.error_code_description,
|
|
||||||
error_code_color: errorCodeData.error_code_color,
|
|
||||||
path_icon: errorCodeData.path_icon,
|
|
||||||
is_active: errorCodeData.is_active,
|
|
||||||
created_by: data.updated_by,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (errorCodeData.spareparts && Array.isArray(errorCodeData.spareparts)) {
|
|
||||||
await insertMultipleErrorCodeSparepartsDb(errorId, errorCodeData.spareparts, data.updated_by);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
errorCodeData.solution &&
|
|
||||||
Array.isArray(errorCodeData.solution)
|
|
||||||
) {
|
|
||||||
for (const solutionData of errorCodeData.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.updated_by,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const existingEC of existingErrorCodes) {
|
|
||||||
if (!incomingErrorCodes.includes(existingEC.error_code)) {
|
|
||||||
await deleteErrorCodeDb(id, existingEC.error_code, data.updated_by);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const updatedBrandWithSpareparts = await this.getBrandById(id);
|
return updatedBrand;
|
||||||
return updatedBrandWithSpareparts;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(500, `Update failed: ${error.message}`);
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ const {
|
|||||||
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
|
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
|
||||||
|
|
||||||
class ErrorCodeService {
|
class ErrorCodeService {
|
||||||
// Get all error codes with pagination and search (without solutions and spareparts)
|
|
||||||
static async getAllErrorCodes(param) {
|
static async getAllErrorCodes(param) {
|
||||||
try {
|
try {
|
||||||
const results = await getAllErrorCodesDb(param);
|
const results = await getAllErrorCodesDb(param);
|
||||||
@@ -72,12 +71,16 @@ class ErrorCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get error codes by brand ID
|
// Get error codes by brand ID
|
||||||
static async getErrorCodesByBrandId(brandId) {
|
static async getErrorCodesByBrandId(brandId, queryParams = {}) {
|
||||||
try {
|
try {
|
||||||
const errorCodes = await getErrorCodesByBrandIdDb(brandId);
|
const results = await getErrorCodesByBrandIdDb(brandId, queryParams);
|
||||||
|
|
||||||
|
if (results.data && results.total !== undefined) {
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
const errorCodesWithDetails = await Promise.all(
|
const errorCodesWithDetails = await Promise.all(
|
||||||
errorCodes.map(async (errorCode) => {
|
results.map(async (errorCode) => {
|
||||||
const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);
|
const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);
|
||||||
const spareparts = await getSparepartsByErrorCodeIdDb(errorCode.error_code_id);
|
const spareparts = await getSparepartsByErrorCodeIdDb(errorCode.error_code_id);
|
||||||
|
|
||||||
@@ -116,17 +119,6 @@ class ErrorCodeService {
|
|||||||
try {
|
try {
|
||||||
if (!data || typeof data !== "object") data = {};
|
if (!data || typeof data !== "object") data = {};
|
||||||
|
|
||||||
if (
|
|
||||||
!data.solution ||
|
|
||||||
!Array.isArray(data.solution) ||
|
|
||||||
data.solution.length === 0
|
|
||||||
) {
|
|
||||||
throw new ErrorHandler(
|
|
||||||
400,
|
|
||||||
"Error code must have at least 1 solution"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const errorId = await createErrorCodeDb(brandId, {
|
const errorId = await createErrorCodeDb(brandId, {
|
||||||
error_code: data.error_code,
|
error_code: data.error_code,
|
||||||
error_code_name: data.error_code_name,
|
error_code_name: data.error_code_name,
|
||||||
@@ -140,13 +132,10 @@ class ErrorCodeService {
|
|||||||
if (!errorId) {
|
if (!errorId) {
|
||||||
throw new Error("Failed to create error code");
|
throw new Error("Failed to create error code");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create sparepart relationships for this error code
|
|
||||||
if (data.spareparts && Array.isArray(data.spareparts)) {
|
if (data.spareparts && Array.isArray(data.spareparts)) {
|
||||||
await insertMultipleErrorCodeSparepartsDb(errorId, data.spareparts, data.created_by);
|
await insertMultipleErrorCodeSparepartsDb(errorId, data.spareparts, data.created_by);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create solutions for this error code
|
|
||||||
if (data.solution && Array.isArray(data.solution)) {
|
if (data.solution && Array.isArray(data.solution)) {
|
||||||
for (const solutionData of data.solution) {
|
for (const solutionData of data.solution) {
|
||||||
await createSolutionDb(errorId, {
|
await createSolutionDb(errorId, {
|
||||||
@@ -168,39 +157,51 @@ class ErrorCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update error code with solutions and spareparts
|
// Update error code with solutions and spareparts
|
||||||
static async updateErrorCodeWithFullData(brandId, errorCode, data) {
|
static async updateErrorCodeWithFullData(brandId, errorCodeId, data) {
|
||||||
try {
|
try {
|
||||||
const existingErrorCode = await getErrorCodeByBrandAndCodeDb(brandId, errorCode);
|
const existingErrorCode = await getErrorCodeByIdDb(errorCodeId);
|
||||||
if (!existingErrorCode) throw new ErrorHandler(404, "Error code not found");
|
if (!existingErrorCode) throw new ErrorHandler(404, "Error code not found");
|
||||||
|
|
||||||
// Update error code
|
// Verify the error code belongs to the specified brand
|
||||||
await updateErrorCodeDb(brandId, errorCode, {
|
if (existingErrorCode.brand_id !== parseInt(brandId)) {
|
||||||
error_code_name: data.error_code_name,
|
throw new ErrorHandler(403, "Error code does not belong to specified brand");
|
||||||
error_code_description: data.error_code_description,
|
}
|
||||||
error_code_color: data.error_code_color,
|
|
||||||
path_icon: data.path_icon,
|
// Check if there are any error code fields to update
|
||||||
is_active: data.is_active,
|
const hasMainFieldUpdate =
|
||||||
updated_by: data.updated_by,
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Update spareparts if provided
|
|
||||||
if (data.spareparts && Array.isArray(data.spareparts)) {
|
if (data.spareparts && Array.isArray(data.spareparts)) {
|
||||||
await updateErrorCodeSparepartsDb(existingErrorCode.error_code_id, data.spareparts, data.updated_by);
|
await updateErrorCodeSparepartsDb(existingErrorCode.error_code_id, data.spareparts, data.updated_by);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update solutions if provided
|
|
||||||
if (data.solution && Array.isArray(data.solution)) {
|
if (data.solution && Array.isArray(data.solution)) {
|
||||||
const existingSolutions = await getSolutionsByErrorCodeIdDb(existingErrorCode.error_code_id);
|
const existingSolutions = await getSolutionsByErrorCodeIdDb(existingErrorCode.error_code_id);
|
||||||
const incomingSolutionNames = data.solution.map((s) => s.solution_name);
|
const incomingSolutionNames = data.solution.map((s) => s.solution_name);
|
||||||
|
|
||||||
// Update or create solutions
|
|
||||||
for (const solutionData of data.solution) {
|
for (const solutionData of data.solution) {
|
||||||
const existingSolution = existingSolutions.find(
|
const existingSolution = existingSolutions.find(
|
||||||
(s) => s.solution_name === solutionData.solution_name
|
(s) => s.solution_name === solutionData.solution_name
|
||||||
);
|
);
|
||||||
|
|
||||||
if (existingSolution) {
|
if (existingSolution) {
|
||||||
// Update existing solution
|
|
||||||
await updateSolutionDb(
|
await updateSolutionDb(
|
||||||
existingSolution.brand_code_solution_id,
|
existingSolution.brand_code_solution_id,
|
||||||
{
|
{
|
||||||
@@ -213,7 +214,6 @@ class ErrorCodeService {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// Create new solution
|
|
||||||
await createSolutionDb(existingErrorCode.error_code_id, {
|
await createSolutionDb(existingErrorCode.error_code_id, {
|
||||||
solution_name: solutionData.solution_name,
|
solution_name: solutionData.solution_name,
|
||||||
type_solution: solutionData.type_solution,
|
type_solution: solutionData.type_solution,
|
||||||
@@ -225,7 +225,6 @@ class ErrorCodeService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete solutions that are not in the incoming request
|
|
||||||
for (const existingSolution of existingSolutions) {
|
for (const existingSolution of existingSolutions) {
|
||||||
if (!incomingSolutionNames.includes(existingSolution.solution_name)) {
|
if (!incomingSolutionNames.includes(existingSolution.solution_name)) {
|
||||||
await deleteSolutionDb(existingSolution.brand_code_solution_id, data.updated_by);
|
await deleteSolutionDb(existingSolution.brand_code_solution_id, data.updated_by);
|
||||||
@@ -241,15 +240,20 @@ class ErrorCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Soft delete error code
|
// Soft delete error code
|
||||||
static async deleteErrorCode(brandId, errorCode, deletedBy) {
|
static async deleteErrorCode(brandId, errorCodeId, deletedBy) {
|
||||||
try {
|
try {
|
||||||
const errorCodeExist = await getErrorCodeByBrandAndCodeDb(brandId, errorCode);
|
const errorCodeExist = await getErrorCodeByIdDb(errorCodeId);
|
||||||
|
|
||||||
if (!errorCodeExist) {
|
if (!errorCodeExist) {
|
||||||
throw new ErrorHandler(404, "Error code not found");
|
throw new ErrorHandler(404, "Error code not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await deleteErrorCodeDb(brandId, errorCode, deletedBy);
|
// 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;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,4 +1,11 @@
|
|||||||
const { getHistoryAlarmDb, getHistoryEventDb, checkTableNamedDb, getHistoryValueReportDb, getHistoryValueReportPivotDb, getHistoryValueTrendingPivotDb } = require('../db/history_value.db');
|
const {
|
||||||
|
getHistoryAlarmDb,
|
||||||
|
getHistoryEventDb,
|
||||||
|
checkTableNamedDb,
|
||||||
|
getHistoryValueReportDb,
|
||||||
|
getHistoryValueReportPivotDb,
|
||||||
|
getHistoryValueTrendingPivotDb
|
||||||
|
} = require('../db/history_value.db');
|
||||||
const { getSubSectionByIdDb } = require('../db/plant_sub_section.db');
|
const { getSubSectionByIdDb } = require('../db/plant_sub_section.db');
|
||||||
const { ErrorHandler } = require('../helpers/error');
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
@@ -7,94 +14,128 @@ class HistoryValue {
|
|||||||
static async getAllHistoryAlarm(param) {
|
static async getAllHistoryAlarm(param) {
|
||||||
try {
|
try {
|
||||||
const results = await getHistoryAlarmDb(param);
|
const results = await getHistoryAlarmDb(param);
|
||||||
|
return results;
|
||||||
results.data.map(element => {
|
|
||||||
});
|
|
||||||
|
|
||||||
return results
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(error.statusCode, error.message);
|
throw new ErrorHandler(error.statusCode || 500, error.message || 'Error fetching alarm history');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getAllHistoryEvent(param) {
|
static async getAllHistoryEvent(param) {
|
||||||
try {
|
try {
|
||||||
const results = await getHistoryEventDb(param);
|
const results = await getHistoryEventDb(param);
|
||||||
|
return results;
|
||||||
results.data.map(element => {
|
|
||||||
});
|
|
||||||
|
|
||||||
return results
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(error.statusCode, error.message);
|
throw new ErrorHandler(error.statusCode || 500, error.message || 'Error fetching event history');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getHistoryValueReport(param) {
|
static async getHistoryValueReport(param) {
|
||||||
try {
|
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);
|
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
|
||||||
|
|
||||||
if (plantSubSection.length < 1) throw new ErrorHandler(404, 'Plant sub section not found');
|
if (!plantSubSection || plantSubSection.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Plant sub section not found');
|
||||||
|
}
|
||||||
|
|
||||||
const tabelExist = await checkTableNamedDb(plantSubSection[0]?.table_name_value);
|
const tableNameValue = plantSubSection[0]?.table_name_value;
|
||||||
|
|
||||||
|
if (!tableNameValue) {
|
||||||
|
throw new ErrorHandler(404, 'Table name not configured for this sub section');
|
||||||
|
}
|
||||||
|
|
||||||
if (tabelExist.length < 1) throw new ErrorHandler(404, 'Value not found');
|
const tableExist = await checkTableNamedDb(tableNameValue);
|
||||||
|
|
||||||
const results = await getHistoryValueReportDb(tabelExist[0]?.TABLE_NAME, param);
|
if (!tableExist || tableExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
results.data.map(element => {
|
const results = await getHistoryValueReportDb(tableExist[0].TABLE_NAME, param);
|
||||||
});
|
return results;
|
||||||
|
|
||||||
return results
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(error.statusCode, error.message);
|
throw new ErrorHandler(
|
||||||
|
error.statusCode || 500,
|
||||||
|
error.message || 'Error fetching history value report'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getHistoryValueReportPivot(param) {
|
static async getHistoryValueReportPivot(param) {
|
||||||
try {
|
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);
|
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
|
||||||
|
|
||||||
if (plantSubSection.length < 1) throw new ErrorHandler(404, 'Plant sub section not found');
|
if (!plantSubSection || plantSubSection.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Plant sub section not found');
|
||||||
|
}
|
||||||
|
|
||||||
const tabelExist = await checkTableNamedDb(plantSubSection[0]?.table_name_value);
|
const tableNameValue = plantSubSection[0]?.table_name_value;
|
||||||
|
|
||||||
|
if (!tableNameValue) {
|
||||||
|
throw new ErrorHandler(404, 'Table name not configured for this sub section');
|
||||||
|
}
|
||||||
|
|
||||||
if (tabelExist.length < 1) throw new ErrorHandler(404, 'Value not found');
|
const tableExist = await checkTableNamedDb(tableNameValue);
|
||||||
|
|
||||||
const results = await getHistoryValueReportPivotDb(tabelExist[0]?.TABLE_NAME, param);
|
if (!tableExist || tableExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
results.data.map(element => {
|
const results = await getHistoryValueReportPivotDb(tableExist[0].TABLE_NAME, param);
|
||||||
});
|
return results;
|
||||||
|
|
||||||
return results
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(error.statusCode, error.message);
|
throw new ErrorHandler(
|
||||||
|
error.statusCode || 500,
|
||||||
|
error.message || 'Error fetching history value report pivot'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async getHistoryValueTrendingPivot(param) {
|
static async getHistoryValueTrendingPivot(param) {
|
||||||
try {
|
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);
|
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
|
||||||
|
|
||||||
if (plantSubSection.length < 1) throw new ErrorHandler(404, 'Plant sub section not found');
|
if (!plantSubSection || plantSubSection.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Plant sub section not found');
|
||||||
|
}
|
||||||
|
|
||||||
const tabelExist = await checkTableNamedDb(plantSubSection[0]?.table_name_value);
|
const tableNameValue = plantSubSection[0]?.table_name_value;
|
||||||
|
|
||||||
|
if (!tableNameValue) {
|
||||||
|
throw new ErrorHandler(404, 'Table name not configured for this sub section');
|
||||||
|
}
|
||||||
|
|
||||||
if (tabelExist.length < 1) throw new ErrorHandler(404, 'Value not found');
|
const tableExist = await checkTableNamedDb(tableNameValue);
|
||||||
|
|
||||||
const results = await getHistoryValueTrendingPivotDb(tabelExist[0]?.TABLE_NAME, param);
|
if (!tableExist || tableExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
results.data.map(element => {
|
const results = await getHistoryValueTrendingPivotDb(tableExist[0].TABLE_NAME, param);
|
||||||
});
|
return results;
|
||||||
|
|
||||||
return results
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(error.statusCode, error.message);
|
throw new ErrorHandler(
|
||||||
|
error.statusCode || 500,
|
||||||
|
error.message || 'Error fetching history value trending pivot'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = HistoryValue;
|
module.exports = HistoryValue;
|
||||||
@@ -1,64 +1,111 @@
|
|||||||
|
// services/notification_error.service.js
|
||||||
const {
|
const {
|
||||||
getAllNotificationDb,
|
getAllNotificationDb,
|
||||||
getNotificationByIdDb,
|
getNotificationByIdDb,
|
||||||
} = require('../db/notification_error.db');
|
InsertNotificationErrorDb,
|
||||||
|
getUsersNotificationErrorDb,
|
||||||
|
updateNotificationErrorDb,
|
||||||
|
} = require("../db/notification_error.db");
|
||||||
|
|
||||||
const {
|
const { getErrorCodeByIdDb } = require("../db/brand_code.db");
|
||||||
getErrorCodeByIdDb,
|
|
||||||
} = require('../db/brand_code.db');
|
|
||||||
|
|
||||||
const {
|
|
||||||
getSolutionsByErrorCodeIdDb,
|
|
||||||
} = require('../db/brand_code_solution.db');
|
|
||||||
|
|
||||||
|
const { getSolutionsByErrorCodeIdDb } = require("../db/brand_code_solution.db");
|
||||||
|
|
||||||
const {
|
const {
|
||||||
getAllNotificationErrorLogDb,
|
getAllNotificationErrorLogDb,
|
||||||
getNotificationErrorLogByNotificationErrorIdDb,
|
getNotificationErrorLogByNotificationErrorIdDb,
|
||||||
} = require('../db/notification_error_log.db');
|
} = require("../db/notification_error_log.db");
|
||||||
|
|
||||||
const { getFileUploadByPathDb } = require('../db/file_uploads.db');
|
const { getSparepartsByErrorCodeIdDb } = require("../db/brand_sparepart.db");
|
||||||
|
|
||||||
const { ErrorHandler } = require('../helpers/error');
|
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 {
|
class NotificationService {
|
||||||
// Get all Notifications
|
|
||||||
static async getAllNotification(param) {
|
static async getAllNotification(param) {
|
||||||
try {
|
try {
|
||||||
const results = await getAllNotificationDb(param);
|
const results = await getAllNotificationDb(param);
|
||||||
|
|
||||||
results.data.map(element => {
|
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;
|
return results;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ErrorHandler(error.statusCode, error.message);
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get notification by ID
|
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) {
|
static async getNotificationById(id) {
|
||||||
try {
|
try {
|
||||||
const notification = await getNotificationByIdDb(id);
|
const notification = await getNotificationByIdDb(id);
|
||||||
|
|
||||||
if (!notification || (Array.isArray(notification) && notification.length < 1)) {
|
if (
|
||||||
throw new ErrorHandler(404, 'Notification not found');
|
!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
|
// Get error code details if error_code_id exists
|
||||||
if (notification.error_code_id) {
|
if (notification.error_code_id) {
|
||||||
const errorCode = await getErrorCodeByIdDb(notification.error_code_id);
|
const errorCode = await getErrorCodeByIdDb(notification.error_code_id);
|
||||||
|
|
||||||
if (errorCode) {
|
if (errorCode) {
|
||||||
// Get solutions for this error code
|
// Get solutions for this error code
|
||||||
const solutions = (await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || [];
|
const solutions =
|
||||||
|
(await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || [];
|
||||||
|
|
||||||
|
const spareparts =
|
||||||
|
(await getSparepartsByErrorCodeIdDb(errorCode.error_code_id)) || [];
|
||||||
|
|
||||||
const solutionsWithDetails = await Promise.all(
|
const solutionsWithDetails = await Promise.all(
|
||||||
solutions.map(async (solution) => {
|
solutions.map(async (solution) => {
|
||||||
let fileData = null;
|
let fileData = null;
|
||||||
if (solution.path_solution && solution.type_solution && solution.type_solution !== 'text') {
|
if (
|
||||||
|
solution.path_solution &&
|
||||||
|
solution.type_solution &&
|
||||||
|
solution.type_solution !== "text"
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
fileData = await getFileUploadByPathDb(solution.path_solution);
|
fileData = await getFileUploadByPathDb(
|
||||||
|
solution.path_solution
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
fileData = null;
|
fileData = null;
|
||||||
}
|
}
|
||||||
@@ -66,20 +113,24 @@ class NotificationService {
|
|||||||
return {
|
return {
|
||||||
...solution,
|
...solution,
|
||||||
file_upload_name: fileData?.file_upload_name || null,
|
file_upload_name: fileData?.file_upload_name || null,
|
||||||
path_document: fileData?.path_document || null
|
path_document: fileData?.path_document || null,
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
notification.error_code = {
|
notification.error_code = {
|
||||||
...errorCode,
|
...errorCode,
|
||||||
solution: solutionsWithDetails
|
solution: solutionsWithDetails,
|
||||||
|
spareparts: spareparts,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get activity logs for this notification
|
// Get activity logs for this notification
|
||||||
const notificationLogs = (await getNotificationErrorLogByNotificationErrorIdDb(id)) || [];
|
const notificationLogs =
|
||||||
|
(await getNotificationErrorLogByNotificationErrorIdDb(id)) || [];
|
||||||
|
|
||||||
|
notification.users = usersNotification;
|
||||||
|
|
||||||
notification.activity_logs = notificationLogs;
|
notification.activity_logs = notificationLogs;
|
||||||
|
|
||||||
@@ -88,6 +139,129 @@ class NotificationService {
|
|||||||
throw new ErrorHandler(error.statusCode, error.message);
|
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;
|
module.exports = NotificationService;
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ const {
|
|||||||
deleteNotificationErrorLogDb
|
deleteNotificationErrorLogDb
|
||||||
} = require('../db/notification_error_log.db');
|
} = require('../db/notification_error_log.db');
|
||||||
|
|
||||||
|
const { getUserByIdDb } = require('../db/user.db');
|
||||||
const { ErrorHandler } = require('../helpers/error');
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
class NotificationErrorLogService {
|
class NotificationErrorLogService {
|
||||||
@@ -40,15 +41,34 @@ class NotificationErrorLogService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create Notification Error Log
|
// Create Notification Error Log
|
||||||
static async createNotificationErrorLog(data) {
|
static async createNotificationErrorLog(data, userId) {
|
||||||
try {
|
try {
|
||||||
if (!data || typeof data !== 'object') data = {};
|
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 = {
|
const store = {
|
||||||
notification_error_id: data.notification_error_id,
|
notification_error_id: data.notification_error_id,
|
||||||
contact_id: data.contact_id,
|
contact_phone: contactPhone,
|
||||||
notification_error_log_description: data.notification_error_log_description,
|
notification_error_log_description: data.notification_error_log_description,
|
||||||
created_by: data.created_by
|
created_by: createdBy
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = await createNotificationErrorLogDb(store);
|
const result = await createNotificationErrorLogDb(store);
|
||||||
|
|||||||
195
services/notification_error_user.service.js
Normal file
195
services/notification_error_user.service.js
Normal 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;
|
||||||
125
services/notifikasi-wa.service.js
Normal file
125
services/notifikasi-wa.service.js
Normal 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();
|
||||||
@@ -8,91 +8,18 @@ const insertBrandSchema = Joi.object({
|
|||||||
brand_type: Joi.string().max(50).optional().allow(""),
|
brand_type: Joi.string().max(50).optional().allow(""),
|
||||||
brand_manufacture: Joi.string().max(100).required(),
|
brand_manufacture: Joi.string().max(100).required(),
|
||||||
brand_model: Joi.string().max(100).optional().allow(""),
|
brand_model: Joi.string().max(100).optional().allow(""),
|
||||||
is_active: Joi.boolean().required(),
|
is_active: Joi.boolean().optional().default(true),
|
||||||
description: Joi.string().max(255).optional().allow(""),
|
description: Joi.string().max(255).optional().allow(""),
|
||||||
error_code: Joi.array()
|
|
||||||
.items(
|
|
||||||
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().required(),
|
|
||||||
what_action_to_take: Joi.string().optional().allow(""),
|
|
||||||
spareparts: Joi.array().items(Joi.number().integer()).optional(),
|
|
||||||
solution: Joi.array()
|
|
||||||
.items(
|
|
||||||
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().required(),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required(),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update Brand Validation
|
// Update Brand Validation
|
||||||
const updateBrandSchema = Joi.object({
|
const updateBrandSchema = Joi.object({
|
||||||
brand_name: Joi.string().max(100).required(),
|
brand_name: Joi.string().max(100).optional(),
|
||||||
brand_type: Joi.string().max(50).optional().allow(""),
|
brand_type: Joi.string().max(50).optional().allow(""),
|
||||||
brand_manufacture: Joi.string().max(100).required(),
|
brand_manufacture: Joi.string().max(100).optional(),
|
||||||
brand_model: Joi.string().max(100).optional().allow(""),
|
brand_model: Joi.string().max(100).optional().allow(""),
|
||||||
is_active: Joi.boolean().required(),
|
is_active: Joi.boolean().optional(),
|
||||||
description: Joi.string().max(255).optional().allow(""),
|
description: Joi.string().max(255).optional().allow(""),
|
||||||
error_code: Joi.array()
|
|
||||||
.items(
|
|
||||||
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().required(),
|
|
||||||
what_action_to_take: Joi.string().optional().allow(""),
|
|
||||||
spareparts: Joi.array().items(Joi.number().integer()).optional(),
|
|
||||||
solution: Joi.array()
|
|
||||||
.items(
|
|
||||||
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().optional(),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required(),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.optional(),
|
|
||||||
}).min(1);
|
}).min(1);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const insertContactSchema = Joi.object({
|
|||||||
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
|
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
|
||||||
}),
|
}),
|
||||||
is_active: Joi.boolean().required(),
|
is_active: Joi.boolean().required(),
|
||||||
contact_type: Joi.string().max(255).optional()
|
contact_type: Joi.string().max(255).optional().allow(null)
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateContactSchema = Joi.object({
|
const updateContactSchema = Joi.object({
|
||||||
@@ -26,7 +26,7 @@ const updateContactSchema = Joi.object({
|
|||||||
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
|
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
|
||||||
}),
|
}),
|
||||||
is_active: Joi.boolean().optional(),
|
is_active: Joi.boolean().optional(),
|
||||||
contact_type: Joi.string().max(255).optional()
|
contact_type: Joi.string().max(255).optional().allow(null)
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
@@ -9,13 +9,14 @@ const insertDeviceSchema = Joi.object({
|
|||||||
is_active: Joi.boolean().required(),
|
is_active: Joi.boolean().required(),
|
||||||
brand_id: Joi.number().integer().min(1),
|
brand_id: Joi.number().integer().min(1),
|
||||||
device_location: Joi.string().max(100).required(),
|
device_location: Joi.string().max(100).required(),
|
||||||
device_description: Joi.string().required(),
|
device_description: Joi.string(),
|
||||||
ip_address: Joi.string()
|
ip_address: Joi.string()
|
||||||
.ip({ version: ['ipv4', 'ipv6'] })
|
.ip({ version: ['ipv4', 'ipv6'] })
|
||||||
.required()
|
.required()
|
||||||
.messages({
|
.messages({
|
||||||
'string.ip': 'IP address must be a valid IPv4 or IPv6 address'
|
'string.ip': 'IP address must be a valid IPv4 or IPv6 address'
|
||||||
})
|
}),
|
||||||
|
listen_channel: Joi.string().max(100).required()
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateDeviceSchema = Joi.object({
|
const updateDeviceSchema = Joi.object({
|
||||||
@@ -28,11 +29,11 @@ const updateDeviceSchema = Joi.object({
|
|||||||
.ip({ version: ['ipv4', 'ipv6'] })
|
.ip({ version: ['ipv4', 'ipv6'] })
|
||||||
.messages({
|
.messages({
|
||||||
'string.ip': 'IP address must be a valid IPv4 or IPv6 address'
|
'string.ip': 'IP address must be a valid IPv4 or IPv6 address'
|
||||||
})
|
}),
|
||||||
|
listen_channel: Joi.string().max(100)
|
||||||
}).min(1);
|
}).min(1);
|
||||||
|
|
||||||
|
|
||||||
// ✅ Export dengan CommonJS
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
insertDeviceSchema, updateDeviceSchema
|
insertDeviceSchema, updateDeviceSchema
|
||||||
};
|
};
|
||||||
73
validate/error_code.schema.js
Normal file
73
validate/error_code.schema.js
Normal 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,
|
||||||
|
};
|
||||||
@@ -13,6 +13,8 @@ const insertNotificationSchema = Joi.object({
|
|||||||
"number.base": "error_code_id must be a number",
|
"number.base": "error_code_id must be a number",
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
message_error_issue: Joi.string().max(255).optional(),
|
||||||
|
|
||||||
is_send: Joi.boolean().required().messages({
|
is_send: Joi.boolean().required().messages({
|
||||||
"any.required": "is_send is required",
|
"any.required": "is_send is required",
|
||||||
"boolean.base": "is_send must be a boolean",
|
"boolean.base": "is_send must be a boolean",
|
||||||
@@ -38,25 +40,11 @@ const insertNotificationSchema = Joi.object({
|
|||||||
// Update Notification Schema
|
// Update Notification Schema
|
||||||
// ========================
|
// ========================
|
||||||
const updateNotificationSchema = Joi.object({
|
const updateNotificationSchema = Joi.object({
|
||||||
error_code_id: Joi.number().optional().messages({
|
|
||||||
"number.base": "error_code_id must be a number",
|
|
||||||
}),
|
|
||||||
|
|
||||||
is_send: Joi.boolean().optional().messages({
|
|
||||||
"boolean.base": "is_send must be a boolean",
|
|
||||||
}),
|
|
||||||
|
|
||||||
is_delivered: Joi.boolean().optional().messages({
|
|
||||||
"boolean.base": "is_delivered must be a boolean",
|
|
||||||
}),
|
|
||||||
|
|
||||||
is_read: Joi.boolean().optional().messages({
|
is_read: Joi.boolean().optional().messages({
|
||||||
"boolean.base": "is_read must be a boolean",
|
"boolean.base": "is_read must be a boolean",
|
||||||
}),
|
}),
|
||||||
|
|
||||||
is_active: Joi.boolean().optional().messages({
|
|
||||||
"boolean.base": "is_active must be a boolean",
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ const Joi = require("joi");
|
|||||||
|
|
||||||
const insertNotificationErrorLogSchema = Joi.object({
|
const insertNotificationErrorLogSchema = Joi.object({
|
||||||
notification_error_id: Joi.number().integer().required(),
|
notification_error_id: Joi.number().integer().required(),
|
||||||
contact_id: Joi.number().integer().required(),
|
contact_phone: Joi.string().optional(),
|
||||||
notification_error_log_description: Joi.string().required()
|
notification_error_log_description: Joi.string().required()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
44
validate/notification_error_user.schema.js
Normal file
44
validate/notification_error_user.schema.js
Normal 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,
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user