Compare commits
128 Commits
00239db472
...
wisdom
| Author | SHA1 | Date | |
|---|---|---|---|
| 436ea1cf89 | |||
| 8e0dc4bb88 | |||
| b680a249d5 | |||
| b1cf4ff624 | |||
| 747a96ac30 | |||
| 026a88a9a9 | |||
| 4d2c18edfb | |||
| a4d8d55dbf | |||
| a6075174f5 | |||
| 3d163f4507 | |||
| bc265ccc33 | |||
| cecdc09719 | |||
| 2a25339478 | |||
| 3faa3656c1 | |||
| aa7cd2fbaa | |||
| f3abaeac39 | |||
| b025c5ea82 | |||
| 6f4d171537 | |||
| 71c5e94f42 | |||
| 0c16b2a3fd | |||
| 402c1c0705 | |||
| adaa9fda9a | |||
| 3eb403c557 | |||
| bedc948a74 | |||
| 889aa04808 | |||
| 25ba80ab7e | |||
| a704eb3235 | |||
| 10b7ac5e68 | |||
| 37185a9fbc | |||
| c9dba276bb | |||
| 706fd401f4 | |||
| 518d6ff427 | |||
| 9f7a73e149 | |||
| bba50177e9 | |||
| 85750b397b | |||
|
|
1496b80fdf | ||
|
|
c112ff165a | ||
| 5e7de6d144 | |||
| dd5e1cc713 | |||
| 1aa7b1bc08 | |||
| f2c8c3818d | |||
| 907f5767c1 | |||
| 2b93baa648 | |||
| fb3061e0d1 | |||
| d063478fc2 | |||
| 555a68e90c | |||
| dc7712a79f | |||
| 20d035a1ca | |||
| 1d3de9ae41 | |||
| 198346ff0b | |||
| a8eb785a5b | |||
| 096fe9461d | |||
| 31daa470b7 | |||
| be80206056 | |||
| 73b4abfd68 | |||
| 8b4cc89be5 | |||
| 6fc21160f5 | |||
| c8b2387e4f | |||
| cecb88b838 | |||
| 1ec69b388d | |||
| 867976030a | |||
| 790b949302 | |||
| f797685a4f | |||
| feff905d8f | |||
| 097030029f | |||
| 28e99c2a0d | |||
| 920b24bfd2 | |||
| 462cf6e94b | |||
| 9926e2b181 | |||
| fdb560985c | |||
| c9713910b3 | |||
| 380864b1ab | |||
| 5a9ef3356d | |||
| 662cf6f5f3 | |||
| 78a813e9ec | |||
| 44107c9753 | |||
| ca973d931f | |||
| 778d6f98e8 | |||
| 9dc165e15d | |||
| 70817df361 | |||
| 6de0d5d149 | |||
| fd07481fb0 | |||
| 8dcdddb42f | |||
| 833b1bee82 | |||
| 8bab066dd0 | |||
| 4253e29889 | |||
| 98a1b15669 | |||
| 5e4a992834 | |||
| 46c69aafa0 | |||
| 919824bb41 | |||
| de5051bfaf | |||
| 8176eb2bdd | |||
| ff4176f8f9 | |||
| ac68a380dd | |||
| b8dd4a61f8 | |||
| c8149c2359 | |||
| 342c06e49c | |||
| d2d6ce2ab1 | |||
| 93b6b1b15e | |||
| d96cbd5e19 | |||
| aa8aad94cf | |||
| a37906470b | |||
| 85fca5613e | |||
| 85ee767451 | |||
| afebb64e47 | |||
| cd77fda212 | |||
| a3b7f79546 | |||
| 409e2d3750 | |||
| 2fa263e9e4 | |||
| 02a2561274 | |||
| 3633590a8f | |||
|
|
3b9f3474a6 | ||
| 26f7420688 | |||
| ea2905d558 | |||
| 893f177abd | |||
| 3a95cdf315 | |||
|
|
23f447188f | ||
|
|
cec23e4777 | ||
|
|
f6b29bb80e | ||
|
|
cf482a293c | ||
| 9211570f2c | |||
| 6fc31fe987 | |||
|
|
519c37e82c | ||
|
|
06582f51be | ||
| 9c08e51d31 | |||
|
|
a9ad9cccc7 | ||
| 0de69aa219 | |||
| 906a624700 |
@@ -23,6 +23,11 @@ SECRET=secret
|
|||||||
# JWT refresh secret
|
# JWT refresh secret
|
||||||
REFRESH_SECRET=refreshsecret
|
REFRESH_SECRET=refreshsecret
|
||||||
|
|
||||||
|
# IMAGEKIT
|
||||||
|
IMAGEKIT_URL_ENDPOINT=https://ik.imagekit.io/j0hxk7x3p
|
||||||
|
IMAGEKIT_PUBLIC_KEY=public_iMPQFBnXmdQy73TTB9w4SMQO4Jk=
|
||||||
|
IMAGEKIT_PRIVATE_KEY=private_vhO/jXHnEoaVYptOHIuZDPMbxIA=
|
||||||
|
|
||||||
# mail server settings
|
# mail server settings
|
||||||
# SMTP_FROM=youremail
|
# SMTP_FROM=youremail
|
||||||
# SMTP_USER=youremail
|
# SMTP_USER=youremail
|
||||||
|
|||||||
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;
|
||||||
|
|||||||
122
config/index.js
122
config/index.js
@@ -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,
|
||||||
@@ -31,11 +34,11 @@ const poolPromise = new sql.ConnectionPool(config)
|
|||||||
async function checkConnection() {
|
async function checkConnection() {
|
||||||
try {
|
try {
|
||||||
const pool = await poolPromise;
|
const pool = await poolPromise;
|
||||||
await pool.request().query('SELECT 1 AS isConnected');
|
await pool.request().query("SELECT 1 AS isConnected");
|
||||||
console.log('🔍 SQL Server terkoneksi dengan baik');
|
console.log("🔍 SQL Server terkoneksi dengan baik");
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('⚠️ Gagal cek koneksi SQL Server:', error);
|
console.error("⚠️ Gagal cek koneksi SQL Server:", error);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,13 +61,16 @@ async function query(text, params = []) {
|
|||||||
return request.query(sqlText);
|
return request.query(sqlText);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validasi tanggal
|
||||||
|
*/
|
||||||
function isValidDate(dateStr) {
|
function isValidDate(dateStr) {
|
||||||
const d = new Date(dateStr);
|
const d = new Date(dateStr);
|
||||||
return !isNaN(d.getTime()); // true kalau valid
|
return !isNaN(d.getTime());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build filter query
|
* Build filter query (AND)
|
||||||
*/
|
*/
|
||||||
function buildFilterQuery(filterQuery = [], fixedParams = []) {
|
function buildFilterQuery(filterQuery = [], fixedParams = []) {
|
||||||
let whereConditions = [];
|
let whereConditions = [];
|
||||||
@@ -76,7 +82,9 @@ function buildFilterQuery(filterQuery = [], fixedParams = []) {
|
|||||||
switch (f.type) {
|
switch (f.type) {
|
||||||
case "string":
|
case "string":
|
||||||
queryParams.push(`%${f.param}%`);
|
queryParams.push(`%${f.param}%`);
|
||||||
whereConditions.push(`${f.column} LIKE $${queryParams.length} COLLATE SQL_Latin1_General_CP1_CI_AS`);
|
whereConditions.push(
|
||||||
|
`${f.column} LIKE $${queryParams.length} COLLATE SQL_Latin1_General_CP1_CI_AS`
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "number":
|
case "number":
|
||||||
@@ -89,15 +97,14 @@ function buildFilterQuery(filterQuery = [], fixedParams = []) {
|
|||||||
whereConditions.push(`${f.column} = $${queryParams.length}`);
|
whereConditions.push(`${f.column} = $${queryParams.length}`);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'between':
|
case "between":
|
||||||
if (Array.isArray(f.param) && f.param.length === 2) {
|
if (Array.isArray(f.param) && f.param.length === 2) {
|
||||||
const from = f.param[0];
|
const [from, to] = f.param;
|
||||||
const to = f.param[1];
|
|
||||||
if (isValidDate(from) && isValidDate(to)) {
|
if (isValidDate(from) && isValidDate(to)) {
|
||||||
queryParams.push(from);
|
queryParams.push(from);
|
||||||
queryParams.push(to);
|
queryParams.push(to);
|
||||||
whereConditions.push(
|
whereConditions.push(
|
||||||
`${f.column} BETWEEN $${queryParams.length - 1} AND $${queryParams.length}`
|
`CAST(${f.column} AS DATE) BETWEEN $${queryParams.length - 1} AND $${queryParams.length}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,7 +119,7 @@ function buildFilterQuery(filterQuery = [], fixedParams = []) {
|
|||||||
* Build OR ILIKE (SQL Server pakai LIKE + COLLATE)
|
* Build OR ILIKE (SQL Server pakai LIKE + COLLATE)
|
||||||
*/
|
*/
|
||||||
function buildStringOrIlike(columnParam, criteria, fixedParams = []) {
|
function buildStringOrIlike(columnParam, criteria, fixedParams = []) {
|
||||||
if (!criteria) return { whereClause: "", whereParam: fixedParams };
|
if (!criteria) return { whereOrConditions: "", whereParamOr: fixedParams };
|
||||||
|
|
||||||
let orStringConditions = [];
|
let orStringConditions = [];
|
||||||
let queryParams = [...fixedParams];
|
let queryParams = [...fixedParams];
|
||||||
@@ -120,7 +127,9 @@ function buildStringOrIlike(columnParam, criteria, fixedParams = []) {
|
|||||||
columnParam.forEach((column) => {
|
columnParam.forEach((column) => {
|
||||||
if (!column) return;
|
if (!column) return;
|
||||||
queryParams.push(`%${criteria}%`);
|
queryParams.push(`%${criteria}%`);
|
||||||
orStringConditions.push(`${column} LIKE $${queryParams.length} COLLATE SQL_Latin1_General_CP1_CI_AS`);
|
orStringConditions.push(
|
||||||
|
`${column} LIKE $${queryParams.length} COLLATE SQL_Latin1_General_CP1_CI_AS`
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const whereClause = orStringConditions.length
|
const whereClause = orStringConditions.length
|
||||||
@@ -130,12 +139,59 @@ function buildStringOrIlike(columnParam, criteria, fixedParams = []) {
|
|||||||
return { whereOrConditions: whereClause, whereParamOr: queryParams };
|
return { whereOrConditions: whereClause, whereParamOr: queryParams };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build Date Filter (harian / mingguan / bulanan)
|
||||||
|
*/
|
||||||
|
function buildDateFilter(column, type, dateValue, fixedParams = []) {
|
||||||
|
let whereCondition = "";
|
||||||
|
let queryParams = [...fixedParams];
|
||||||
|
|
||||||
|
if (!dateValue && type !== "monthly") {
|
||||||
|
return { whereDateCondition: "", whereDateParams: queryParams };
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case "daily": {
|
||||||
|
queryParams.push(dateValue);
|
||||||
|
whereCondition = `CAST(${column} AS DATE) = $${queryParams.length}`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "weekly": {
|
||||||
|
const startDate = new Date(dateValue);
|
||||||
|
if (!isNaN(startDate.getTime())) {
|
||||||
|
const endDate = new Date(startDate);
|
||||||
|
endDate.setDate(startDate.getDate() + 6);
|
||||||
|
|
||||||
|
queryParams.push(startDate.toISOString().split("T")[0]);
|
||||||
|
queryParams.push(endDate.toISOString().split("T")[0]);
|
||||||
|
|
||||||
|
whereCondition = `CAST(${column} AS DATE) BETWEEN $${queryParams.length - 1} AND $${queryParams.length}`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "monthly": {
|
||||||
|
const [year, month] = dateValue.split("-");
|
||||||
|
if (year && month) {
|
||||||
|
queryParams.push(parseInt(year), parseInt(month));
|
||||||
|
whereCondition = `YEAR(${column}) = $${queryParams.length - 1} AND MONTH(${column}) = $${queryParams.length}`;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
whereCondition = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
return { whereDateCondition: whereCondition, whereDateParams: queryParams };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build dynamic UPDATE
|
* Build dynamic UPDATE
|
||||||
*/
|
*/
|
||||||
function buildDynamicUpdate(table, data, where) {
|
function buildDynamicUpdate(table, data, where) {
|
||||||
|
data.updated_by = data.userId;
|
||||||
data.updated_by = data.userId
|
|
||||||
delete data.userId;
|
delete data.userId;
|
||||||
|
|
||||||
const setParts = [];
|
const setParts = [];
|
||||||
@@ -153,7 +209,6 @@ function buildDynamicUpdate(table, data, where) {
|
|||||||
throw new Error("Tidak ada kolom untuk diupdate");
|
throw new Error("Tidak ada kolom untuk diupdate");
|
||||||
}
|
}
|
||||||
|
|
||||||
// updated_at otomatis pakai CURRENT_TIMESTAMP
|
|
||||||
setParts.push(`updated_at = CURRENT_TIMESTAMP`);
|
setParts.push(`updated_at = CURRENT_TIMESTAMP`);
|
||||||
|
|
||||||
const whereParts = [];
|
const whereParts = [];
|
||||||
@@ -175,9 +230,8 @@ function buildDynamicUpdate(table, data, where) {
|
|||||||
* Build dynamic INSERT
|
* Build dynamic INSERT
|
||||||
*/
|
*/
|
||||||
function buildDynamicInsert(table, data) {
|
function buildDynamicInsert(table, data) {
|
||||||
|
data.created_by = data.userId;
|
||||||
data.created_by = data.userId
|
data.updated_by = data.userId;
|
||||||
data.updated_by = data.userId
|
|
||||||
delete data.userId;
|
delete data.userId;
|
||||||
|
|
||||||
const columns = [];
|
const columns = [];
|
||||||
@@ -197,7 +251,6 @@ function buildDynamicInsert(table, data) {
|
|||||||
throw new Error("Tidak ada kolom untuk diinsert");
|
throw new Error("Tidak ada kolom untuk diinsert");
|
||||||
}
|
}
|
||||||
|
|
||||||
// created_at & updated_at otomatis
|
|
||||||
columns.push("created_at", "updated_at");
|
columns.push("created_at", "updated_at");
|
||||||
placeholders.push("CURRENT_TIMESTAMP", "CURRENT_TIMESTAMP");
|
placeholders.push("CURRENT_TIMESTAMP", "CURRENT_TIMESTAMP");
|
||||||
|
|
||||||
@@ -234,12 +287,43 @@ 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,
|
||||||
buildFilterQuery,
|
buildFilterQuery,
|
||||||
|
buildDateFilter,
|
||||||
buildStringOrIlike,
|
buildStringOrIlike,
|
||||||
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,44 @@ 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));
|
||||||
|
|
||||||
|
console.log("decrypted: ", decrypted);
|
||||||
|
|
||||||
|
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;
|
||||||
|
|||||||
77
controllers/brand.controller.js
Normal file
77
controllers/brand.controller.js
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
const BrandService = require('../services/brand.service');
|
||||||
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const {
|
||||||
|
insertBrandSchema,
|
||||||
|
updateBrandSchema,
|
||||||
|
} = require('../validate/brand.schema');
|
||||||
|
|
||||||
|
class BrandController {
|
||||||
|
// Get all brands
|
||||||
|
static async getAll(req, res) {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await BrandService.getAllBrands(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Brand found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get brand by ID
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await BrandService.getBrandById(id);
|
||||||
|
|
||||||
|
// console.log('Brand response structure:', JSON.stringify(results, null, 2));
|
||||||
|
|
||||||
|
const response = await setResponse(results, 'Brand found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create brand
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertBrandSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.created_by = req.user?.user_id || null;
|
||||||
|
|
||||||
|
const results = await BrandService.createBrand(value);
|
||||||
|
const response = await setResponse(results, 'Brand created successfully');
|
||||||
|
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update brand
|
||||||
|
static async update(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const { error, value } = await checkValidate(updateBrandSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.updated_by = req.user?.user_id || null;
|
||||||
|
|
||||||
|
const results = await BrandService.updateBrand(id, value);
|
||||||
|
const response = await setResponse(results, 'Brand updated successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete brand by ID
|
||||||
|
static async delete(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await BrandService.deleteBrand(id, req.user.user_id);
|
||||||
|
const response = await setResponse(results, 'Brand deleted successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = BrandController;
|
||||||
71
controllers/contact.controller.js
Normal file
71
controllers/contact.controller.js
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
const ContactService = require('../services/contact.service');
|
||||||
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const { insertContactSchema, updateContactSchema } = require('../validate/contact.schema');
|
||||||
|
|
||||||
|
class ContactController {
|
||||||
|
// Get all contact
|
||||||
|
static async getAll(req, res) {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await ContactService.getAllContact(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Contact found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get contact by ID
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await ContactService.getContactById(id);
|
||||||
|
const response = await setResponse(results, 'Contact found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create contact
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertContactSchema, req)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id
|
||||||
|
|
||||||
|
const results = await ContactService.createContact(value);
|
||||||
|
const response = await setResponse(results, 'Contact created successfully')
|
||||||
|
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update contact
|
||||||
|
static async update(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const { error, value } = checkValidate(updateContactSchema, req)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id
|
||||||
|
|
||||||
|
const results = await ContactService.updateContact(id, value);
|
||||||
|
const response = await setResponse(results, 'Contact updated successfully')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete contact
|
||||||
|
static async delete(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await ContactService.deleteContact(id, req.user.user_id);
|
||||||
|
const response = await setResponse(results, 'Contact deleted successfully')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ContactController;
|
||||||
74
controllers/error_code.controller.js
Normal file
74
controllers/error_code.controller.js
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
const ErrorCodeService = require('../services/error_code.service');
|
||||||
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const {
|
||||||
|
insertErrorCodeSchema,
|
||||||
|
updateErrorCodeSchema,
|
||||||
|
} = require('../validate/error_code.schema');
|
||||||
|
|
||||||
|
class ErrorCodeController {
|
||||||
|
static async getByBrandId(req, res) {
|
||||||
|
const { brandId } = req.params;
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await ErrorCodeService.getErrorCodesByBrandId(brandId, queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Error codes found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get error code by ID
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const result = await ErrorCodeService.getErrorCodeById(id);
|
||||||
|
const response = setResponse(result, 'Error code found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create error code with solutions and spareparts
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertErrorCodeSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
const { brandId } = req.params;
|
||||||
|
value.created_by = req.user?.user_id || null;
|
||||||
|
|
||||||
|
const result = await ErrorCodeService.createErrorCodeWithFullData(brandId, value);
|
||||||
|
const response = setResponse(result, 'Error code created successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update error code with solutions and spareparts
|
||||||
|
static async update(req, res) {
|
||||||
|
const { error, value } = await checkValidate(updateErrorCodeSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
const { brandId, errorCodeId } = req.params;
|
||||||
|
value.updated_by = req.user?.user_id || null;
|
||||||
|
|
||||||
|
const result = await ErrorCodeService.updateErrorCodeWithFullData(brandId, errorCodeId, value);
|
||||||
|
const response = setResponse(result, 'Error code updated successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete error code
|
||||||
|
static async delete(req, res) {
|
||||||
|
const { brandId, errorCodeId } = req.params;
|
||||||
|
const deletedBy = req.user?.user_id || null;
|
||||||
|
|
||||||
|
const result = await ErrorCodeService.deleteErrorCode(brandId, errorCodeId, deletedBy);
|
||||||
|
const response = setResponse(result, 'Error code deleted successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ErrorCodeController;
|
||||||
117
controllers/file_uploads.controller.js
Normal file
117
controllers/file_uploads.controller.js
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
const path = require("path");
|
||||||
|
const fs = require("fs");
|
||||||
|
const { setResponse } = require("../helpers/utils");
|
||||||
|
const {
|
||||||
|
createFileUploadDb,
|
||||||
|
deleteFileUploadByPathDb,
|
||||||
|
} = require("../db/file_uploads.db");
|
||||||
|
|
||||||
|
const uploadFile = async (req, res) => {
|
||||||
|
try {
|
||||||
|
if (!req.file) {
|
||||||
|
const response = await setResponse([], "Tidak ada file yang diunggah", 400);
|
||||||
|
return res.status(400).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = req.file;
|
||||||
|
const ext = path.extname(file.originalname).toLowerCase();
|
||||||
|
const typeDoc = ext === ".pdf" ? "PDF" : "IMAGE";
|
||||||
|
const folder = typeDoc === "PDF" ? "pdf" : "images";
|
||||||
|
|
||||||
|
const pathDocument = `${folder}/${file.filename}`;
|
||||||
|
|
||||||
|
const fileData = {
|
||||||
|
file_upload_name: file.originalname,
|
||||||
|
path_document: pathDocument,
|
||||||
|
type_document: typeDoc,
|
||||||
|
createdBy: req.user?.user_id || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await createFileUploadDb(fileData);
|
||||||
|
|
||||||
|
const response = await setResponse(
|
||||||
|
{
|
||||||
|
file_upload_name: file.originalname,
|
||||||
|
path_document: pathDocument
|
||||||
|
},
|
||||||
|
"File berhasil diunggah"
|
||||||
|
);
|
||||||
|
res.status(200).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const response = await setResponse([], error.message, 500);
|
||||||
|
res.status(500).json(response);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const getFileByPath = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { folder, filename } = req.params;
|
||||||
|
|
||||||
|
// Decode filename from URL encoding
|
||||||
|
const decodedFilename = decodeURIComponent(filename);
|
||||||
|
const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);
|
||||||
|
|
||||||
|
console.log('getFileByPath Debug:', {
|
||||||
|
folder,
|
||||||
|
originalFilename: filename,
|
||||||
|
decodedFilename,
|
||||||
|
filePath
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fs.existsSync(filePath)) {
|
||||||
|
console.log('File not found at path:', filePath);
|
||||||
|
|
||||||
|
// try {
|
||||||
|
// const folderPath = path.join(__dirname, "../uploads", folder);
|
||||||
|
// const availableFiles = fs.readdirSync(folderPath);
|
||||||
|
// console.log('Available files in', folderPath, ':', availableFiles);
|
||||||
|
// } catch (listError) {
|
||||||
|
// console.log('Could not list files in folder:', listError.message);
|
||||||
|
// }
|
||||||
|
|
||||||
|
const response = await setResponse([], "File tidak ditemukan", 404);
|
||||||
|
return res.status(404).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.sendFile(filePath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('getFileByPath Error:', error);
|
||||||
|
const response = await setResponse([], error.message, 500);
|
||||||
|
res.status(500).json(response);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteFileByPath = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { folder, filename } = req.params;
|
||||||
|
|
||||||
|
// Decode filename from URL encoding
|
||||||
|
const decodedFilename = decodeURIComponent(filename);
|
||||||
|
const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);
|
||||||
|
|
||||||
|
if (!fs.existsSync(filePath)) {
|
||||||
|
const response = await setResponse([], "File tidak ditemukan", 404);
|
||||||
|
return res.status(404).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete physical file
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
|
||||||
|
const pathDocument = `${folder}/${decodedFilename}`;
|
||||||
|
const deletedBy = req.user?.user_id || null;
|
||||||
|
await deleteFileUploadByPathDb(pathDocument, deletedBy);
|
||||||
|
|
||||||
|
const response = await setResponse([], "File berhasil dihapus");
|
||||||
|
res.status(200).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const response = await setResponse([], error.message, 500);
|
||||||
|
res.status(500).json(response);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
uploadFile,
|
||||||
|
getFileByPath,
|
||||||
|
deleteFileByPath,
|
||||||
|
};
|
||||||
105
controllers/history_value.controller.js
Normal file
105
controllers/history_value.controller.js
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
const HistoryValue = require('../services/history_value.service');
|
||||||
|
const { setResponsePaging } = require('../helpers/utils');
|
||||||
|
|
||||||
|
class HistoryValueController {
|
||||||
|
|
||||||
|
static async getAllHistoryAlarm(req, res) {
|
||||||
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await HistoryValue.getAllHistoryAlarm(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
res.status(statusCode).json({
|
||||||
|
success: false,
|
||||||
|
statusCode,
|
||||||
|
message: error.message || 'Internal server error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getAllHistoryEvent(req, res) {
|
||||||
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await HistoryValue.getAllHistoryEvent(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
res.status(statusCode).json({
|
||||||
|
success: false,
|
||||||
|
statusCode,
|
||||||
|
message: error.message || 'Internal server error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getHistoryValueReport(req, res) {
|
||||||
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await HistoryValue.getHistoryValueReport(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
res.status(statusCode).json({
|
||||||
|
success: false,
|
||||||
|
statusCode,
|
||||||
|
message: error.message || 'Internal server error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getHistoryValueReportPivot(req, res) {
|
||||||
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await HistoryValue.getHistoryValueReportPivot(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
|
if (results.column) {
|
||||||
|
response.columns = results.column;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
res.status(statusCode).json({
|
||||||
|
success: false,
|
||||||
|
statusCode,
|
||||||
|
message: error.message || 'Internal server error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getHistoryValueTrendingPivot(req, res) {
|
||||||
|
try {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await HistoryValue.getHistoryValueTrendingPivot(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Data found');
|
||||||
|
|
||||||
|
if (results.column) {
|
||||||
|
response.columns = results.column;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
res.status(statusCode).json({
|
||||||
|
success: false,
|
||||||
|
statusCode,
|
||||||
|
message: error.message || 'Internal server error'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = HistoryValueController;
|
||||||
88
controllers/notification_error.controller.js
Normal file
88
controllers/notification_error.controller.js
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
const NotificationErrorService = require("../services/notification_error.service");
|
||||||
|
const {
|
||||||
|
setResponse,
|
||||||
|
setResponsePaging,
|
||||||
|
checkValidate,
|
||||||
|
} = require("../helpers/utils");
|
||||||
|
const {
|
||||||
|
insertNotificationSchema,
|
||||||
|
updateNotificationSchema,
|
||||||
|
} = require("../validate/notification.schema");
|
||||||
|
|
||||||
|
class NotificationErrorController {
|
||||||
|
static async getAll(req, res) {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await NotificationErrorService.getAllNotification(
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
const response = await setResponsePaging(
|
||||||
|
queryParams,
|
||||||
|
results,
|
||||||
|
"Notification found"
|
||||||
|
);
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await NotificationErrorService.getNotificationById(id);
|
||||||
|
const response = await setResponse(
|
||||||
|
results,
|
||||||
|
"Notification retrieved successfully"
|
||||||
|
);
|
||||||
|
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertNotificationSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, "Validation failed", 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id;
|
||||||
|
|
||||||
|
const results = await NotificationErrorService.createNotificationError(
|
||||||
|
value
|
||||||
|
);
|
||||||
|
const response = await setResponse(
|
||||||
|
results,
|
||||||
|
"Notification created successfully"
|
||||||
|
);
|
||||||
|
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async update(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const userId = req.user.user_id;
|
||||||
|
|
||||||
|
const results = await NotificationErrorService.updateNotificationError(
|
||||||
|
id,
|
||||||
|
userId
|
||||||
|
);
|
||||||
|
const response = await setResponse(
|
||||||
|
results,
|
||||||
|
"Notification Error updated successfully"
|
||||||
|
);
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async resend(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const results = await NotificationErrorService.resendNotification(id);
|
||||||
|
const response = await setResponse(
|
||||||
|
results,
|
||||||
|
"Notification Error resend successfully"
|
||||||
|
);
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationErrorController;
|
||||||
69
controllers/notification_error_log.controller.js
Normal file
69
controllers/notification_error_log.controller.js
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
const NotificationErrorLogService = require('../services/notification_error_log.service');
|
||||||
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const { insertNotificationErrorLogSchema } = require('../validate/notification_error_log.schema');
|
||||||
|
|
||||||
|
class NotificationErrorLogController {
|
||||||
|
// Get all notification error logs
|
||||||
|
static async getAll(req, res) {
|
||||||
|
try {
|
||||||
|
const results = await NotificationErrorLogService.getAllNotificationErrorLog();
|
||||||
|
const response = await setResponse(results, 'Notification Error Logs found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const response = await setResponse(error, error.message, error.statusCode || 500);
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get notification error log by ID
|
||||||
|
static async getById(req, res) {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await NotificationErrorLogService.getNotificationErrorLogById(id);
|
||||||
|
const response = await setResponse(results, 'Notification Error Log found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const response = await setResponse(error, error.message, error.statusCode || 500);
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get notification error logs by notification_error_id
|
||||||
|
static async getByNotificationErrorId(req, res) {
|
||||||
|
try {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await NotificationErrorLogService.getNotificationErrorLogByNotificationErrorId(id);
|
||||||
|
const response = await setResponse(results, 'Notification Error Logs found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const response = await setResponse(error, error.message, error.statusCode || 500);
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create notification error log
|
||||||
|
static async create(req, res) {
|
||||||
|
try {
|
||||||
|
const { error, value } = await checkValidate(insertNotificationErrorLogSchema, req)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await NotificationErrorLogService.createNotificationErrorLog(value, req.user.user_id);
|
||||||
|
const response = await setResponse(results, 'Notification Error Log created successfully')
|
||||||
|
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
} catch (error) {
|
||||||
|
const response = await setResponse(error, error.message, error.statusCode || 500);
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationErrorLogController;
|
||||||
62
controllers/notification_error_sparepart.controller.js
Normal file
62
controllers/notification_error_sparepart.controller.js
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
const NotificationErrorSparepart = require('../services/notification_error_sparepart.service');
|
||||||
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const { updateNotificationErrorSparepartSchema, insertNotificationErrorSparepartSchema } = require('../validate/notification_error_sparepart.schema');
|
||||||
|
|
||||||
|
class NotificationErrorSparepartController {
|
||||||
|
|
||||||
|
static async getAll(req, res) {
|
||||||
|
const { contact_id } = req.body;
|
||||||
|
const queryParams = req.query;
|
||||||
|
const results = await NotificationErrorSparepart.getAll(queryParams, contact_id);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'Notification Error Sparepart found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const results = await NotificationErrorSparepart.getById(id);
|
||||||
|
const response = await setResponse(results, 'Notification Error Sparepart found');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertNotificationErrorSparepartSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await NotificationErrorSparepart.create(value);
|
||||||
|
const response = await setResponse(results, 'Notification Error Sparepart created successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async update(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const { error, value } = await checkValidate(updateNotificationErrorSparepartSchema, req);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await NotificationErrorSparepart.update(id, value);
|
||||||
|
const response = await setResponse(results, 'Notification Error Sparepart updated successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async delete(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const { contact_id } = req.body;
|
||||||
|
|
||||||
|
const results = await NotificationErrorSparepart.delete(id, contact_id);
|
||||||
|
const response = await setResponse(results, 'Notification Error Sparepart deleted successfully');
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationErrorSparepartController;
|
||||||
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,6 +1,6 @@
|
|||||||
const SubSectionService = require('../services/sub_section.service');
|
const SubSectionService = require('../services/plant_sub_section.service');
|
||||||
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
const { insertSubSectionSchema, updateSubSectionSchema } = require('../validate/sub_section.schema');
|
const { insertSubSectionSchema, updateSubSectionSchema } = require('../validate/plant_sub_section.schema');
|
||||||
|
|
||||||
class SubSectionController {
|
class SubSectionController {
|
||||||
// Get all sub sections
|
// Get all sub sections
|
||||||
327
controllers/sparepart.controller.js
Normal file
327
controllers/sparepart.controller.js
Normal file
@@ -0,0 +1,327 @@
|
|||||||
|
const ExcelJS = require("exceljs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const ImageKit = require("imagekit");
|
||||||
|
const imagekit = new ImageKit({
|
||||||
|
publicKey: process.env.IMAGEKIT_PUBLIC_KEY,
|
||||||
|
privateKey: process.env.IMAGEKIT_PRIVATE_KEY,
|
||||||
|
urlEndpoint: process.env.IMAGEKIT_URL_ENDPOINT,
|
||||||
|
});
|
||||||
|
|
||||||
|
const SparepartService = require("../services/sparepart.service");
|
||||||
|
|
||||||
|
const {
|
||||||
|
setResponse,
|
||||||
|
setResponsePaging,
|
||||||
|
checkValidate,
|
||||||
|
} = require("../helpers/utils");
|
||||||
|
|
||||||
|
const {
|
||||||
|
insertSparepartSchema,
|
||||||
|
updateSparepartSchema,
|
||||||
|
} = require("../validate/sparepart.schema");
|
||||||
|
|
||||||
|
class SparepartController {
|
||||||
|
static async getAll(req, res) {
|
||||||
|
const queryParams = req.query;
|
||||||
|
const results = await SparepartService.getAllSparepart(queryParams);
|
||||||
|
const response = await setResponsePaging(
|
||||||
|
queryParams,
|
||||||
|
results,
|
||||||
|
"Sparepart found"
|
||||||
|
);
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const results = await SparepartService.getSparepartById(id);
|
||||||
|
const response = await setResponse(results, "Sparepart found");
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertSparepartSchema, req);
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, "Validation failed", 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (req.file) {
|
||||||
|
const upload = await imagekit.upload({
|
||||||
|
file: req.file.buffer,
|
||||||
|
fileName: req.file.originalname,
|
||||||
|
folder: "/sparepart",
|
||||||
|
});
|
||||||
|
|
||||||
|
value.sparepart_foto = upload.url;
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id;
|
||||||
|
|
||||||
|
const results = await SparepartService.createSparepart(value);
|
||||||
|
return res
|
||||||
|
.status(201)
|
||||||
|
.json(setResponse(results, "Sparepart created successfully"));
|
||||||
|
} catch (err) {
|
||||||
|
return res
|
||||||
|
.status(err.statusCode || 500)
|
||||||
|
.json(setResponse([], err.message, err.statusCode || 500));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async update(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const { error, value } = await checkValidate(updateSparepartSchema, req);
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, "Validation failed", 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (req.file) {
|
||||||
|
const upload = await imagekit.upload({
|
||||||
|
file: req.file.buffer,
|
||||||
|
fileName: req.file.originalname,
|
||||||
|
folder: "/sparepart",
|
||||||
|
});
|
||||||
|
|
||||||
|
value.sparepart_foto = upload.url;
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id;
|
||||||
|
|
||||||
|
const results = await SparepartService.updateSparepart(id, value);
|
||||||
|
return res
|
||||||
|
.status(200)
|
||||||
|
.json(setResponse(results, "Sparepart updated successfully"));
|
||||||
|
} catch (err) {
|
||||||
|
return res
|
||||||
|
.status(err.statusCode || 500)
|
||||||
|
.json(setResponse([], err.message, err.statusCode || 500));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async exportExcel(req, res) {
|
||||||
|
try {
|
||||||
|
const queryParams = req.query || {};
|
||||||
|
queryParams.limit = null;
|
||||||
|
|
||||||
|
const results = await SparepartService.getAllSparepart(queryParams);
|
||||||
|
|
||||||
|
const workbook = new ExcelJS.Workbook();
|
||||||
|
const worksheet = workbook.addWorksheet("Sparepart Data");
|
||||||
|
|
||||||
|
worksheet.columns = [
|
||||||
|
{ header: "Name Sparepart", key: "sparepart_name", width: 30 },
|
||||||
|
{ header: "Code Sparepart", key: "sparepart_code", width: 20 },
|
||||||
|
{ header: "QTY Sparepart", key: "sparepart_qty", width: 15 },
|
||||||
|
{ header: "Merk", key: "sparepart_merk", width: 20 },
|
||||||
|
{ header: "Model", key: "sparepart_model", width: 20 },
|
||||||
|
{ header: "Unit", key: "sparepart_unit", width: 10 },
|
||||||
|
{ header: "Stock", key: "sparepart_stok", width: 10 },
|
||||||
|
{ header: "Foto", key: "sparepart_foto", width: 25 },
|
||||||
|
{ header: "Item Type", key: "sparepart_item_type", width: 25 },
|
||||||
|
{ header: "Dibuat Pada", key: "created_at", width: 20 },
|
||||||
|
];
|
||||||
|
|
||||||
|
worksheet.addRows(
|
||||||
|
results.data.map((item) => ({
|
||||||
|
...item,
|
||||||
|
sparepart_foto: "",
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
|
||||||
|
for (let i = 0; i < results.data.length; i++) {
|
||||||
|
const item = results.data[i];
|
||||||
|
const rowNumber = i + 2;
|
||||||
|
|
||||||
|
if (!item.sparepart_foto) continue;
|
||||||
|
|
||||||
|
let imageUrl = item.sparepart_foto;
|
||||||
|
|
||||||
|
if (!imageUrl.startsWith("https")) continue;
|
||||||
|
|
||||||
|
let ext = path.extname(imageUrl).toLowerCase().replace(".", "");
|
||||||
|
|
||||||
|
if (!ext) ext = "jpg";
|
||||||
|
|
||||||
|
const supported = ["jpg", "jpeg", "png"];
|
||||||
|
if (!supported.includes(ext)) {
|
||||||
|
ext = "png";
|
||||||
|
}
|
||||||
|
|
||||||
|
let buffer;
|
||||||
|
try {
|
||||||
|
const resp = await fetch(imageUrl);
|
||||||
|
buffer = Buffer.from(await resp.arrayBuffer());
|
||||||
|
} catch (e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageId = workbook.addImage({
|
||||||
|
buffer,
|
||||||
|
extension: ext === "jpg" ? "jpeg" : ext,
|
||||||
|
});
|
||||||
|
|
||||||
|
worksheet.addImage(imageId, {
|
||||||
|
tl: { col: 7, row: rowNumber - 1 },
|
||||||
|
ext: { width: 80, height: 80 },
|
||||||
|
});
|
||||||
|
|
||||||
|
worksheet.getRow(rowNumber).height = 70;
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet.getRow(1).eachCell((cell) => {
|
||||||
|
cell.font = { bold: true };
|
||||||
|
cell.alignment = { horizontal: "center" };
|
||||||
|
});
|
||||||
|
|
||||||
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
|
|
||||||
|
res.setHeader(
|
||||||
|
"Content-Type",
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
);
|
||||||
|
res.setHeader(
|
||||||
|
"Content-Disposition",
|
||||||
|
"attachment; filename=sparepart_data.xlsx"
|
||||||
|
);
|
||||||
|
|
||||||
|
return res.send(buffer);
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(500).json({ message: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async importExcel(req, res) {
|
||||||
|
try {
|
||||||
|
|
||||||
|
const workbook = new ExcelJS.Workbook();
|
||||||
|
await workbook.xlsx.load(req.file.buffer);
|
||||||
|
|
||||||
|
const worksheet = workbook.getWorksheet(1);
|
||||||
|
|
||||||
|
const images = worksheet.getImages();
|
||||||
|
const imageMap = {};
|
||||||
|
images.forEach((imgObj) => {
|
||||||
|
const imageId = imgObj.imageId;
|
||||||
|
const range = imgObj.range;
|
||||||
|
const row = range.tl.nativeRow + 1;
|
||||||
|
const image = workbook.getImage(imageId);
|
||||||
|
imageMap[row] = image;
|
||||||
|
});
|
||||||
|
|
||||||
|
const spareparts = [];
|
||||||
|
|
||||||
|
worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
|
||||||
|
if (rowNumber === 1) return;
|
||||||
|
|
||||||
|
const [
|
||||||
|
sparepart_name,
|
||||||
|
sparepart_code,
|
||||||
|
sparepart_description,
|
||||||
|
sparepart_qty_excel,
|
||||||
|
sparepart_merk,
|
||||||
|
sparepart_model,
|
||||||
|
sparepart_unit,
|
||||||
|
sparepart_stok_excel,
|
||||||
|
sparepart_foto_excel,
|
||||||
|
sparepart_item_type,
|
||||||
|
] = row.values.slice(1);
|
||||||
|
|
||||||
|
if (!sparepart_name) return;
|
||||||
|
|
||||||
|
if (!sparepart_code) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
spareparts.push({
|
||||||
|
sparepart_name: sparepart_name || "",
|
||||||
|
sparepart_code: sparepart_code || "",
|
||||||
|
sparepart_description: sparepart_description || "",
|
||||||
|
sparepart_qty: Number(sparepart_qty_excel) || 0,
|
||||||
|
sparepart_merk: sparepart_merk || "",
|
||||||
|
sparepart_model: sparepart_model || "",
|
||||||
|
sparepart_unit: sparepart_unit || "",
|
||||||
|
sparepart_stok: sparepart_stok_excel || "",
|
||||||
|
sparepart_foto: sparepart_foto_excel || "",
|
||||||
|
sparepart_item_type: sparepart_item_type || "",
|
||||||
|
rowNumber,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if (spareparts.length === 0) {
|
||||||
|
return res
|
||||||
|
.status(400)
|
||||||
|
.json(setResponse([], "Tidak ada data valid untuk diimport", 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
for (const data of spareparts) {
|
||||||
|
let uploadedUrl = "";
|
||||||
|
|
||||||
|
try {
|
||||||
|
const image = imageMap[data.rowNumber];
|
||||||
|
if (image) {
|
||||||
|
const fileName = `sparepart_${Date.now()}_${
|
||||||
|
data.sparepart_code
|
||||||
|
}.jpg`;
|
||||||
|
const uploadResult = await imagekit.upload({
|
||||||
|
file: image.buffer,
|
||||||
|
fileName: fileName,
|
||||||
|
folder: "/sparepart",
|
||||||
|
});
|
||||||
|
|
||||||
|
uploadedUrl = uploadResult.url;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
err;
|
||||||
|
}
|
||||||
|
|
||||||
|
data.sparepart_foto = uploadedUrl || "";
|
||||||
|
|
||||||
|
const { rowNumber, ...dbData } = data;
|
||||||
|
|
||||||
|
const created = await SparepartService.createSparepart(dbData);
|
||||||
|
|
||||||
|
if (created && created[0]) {
|
||||||
|
results.push({
|
||||||
|
sparepart_id: created[0].sparepart_id,
|
||||||
|
sparepart_name: created[0].sparepart_name,
|
||||||
|
sparepart_code: created[0].sparepart_code,
|
||||||
|
sparepart_description: created[0].sparepart_description,
|
||||||
|
sparepart_qty: created[0].sparepart_qty,
|
||||||
|
sparepart_merk: created[0].sparepart_merk,
|
||||||
|
sparepart_model: created[0].sparepart_model,
|
||||||
|
sparepart_unit: created[0].sparepart_unit,
|
||||||
|
sparepart_stok: created[0].sparepart_stok,
|
||||||
|
sparepart_foto: created[0].sparepart_foto,
|
||||||
|
sparepart_item_type: created[0].sparepart_item_type,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.json(
|
||||||
|
setResponse(results, `${results.length} Sparepart berhasil diimport`)
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(500).json({ message: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async delete(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
const results = await SparepartService.deleteSparepart(
|
||||||
|
id,
|
||||||
|
req.user.user_id
|
||||||
|
);
|
||||||
|
const response = await setResponse(
|
||||||
|
results,
|
||||||
|
"Sparepart deleted successfully"
|
||||||
|
);
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = SparepartController;
|
||||||
71
controllers/user_schedule.controller.js
Normal file
71
controllers/user_schedule.controller.js
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
const UserScheduleService = require('../services/user_schedule.service');
|
||||||
|
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||||
|
const { insertUserScheduleSchema, updateUserScheduleSchema } = require('../validate/user_schedule.schema');
|
||||||
|
|
||||||
|
class UserScheduleController {
|
||||||
|
// Get all User Schedule
|
||||||
|
static async getAll(req, res) {
|
||||||
|
const queryParams = req.query;
|
||||||
|
|
||||||
|
const results = await UserScheduleService.getAllUserScheduleDb(queryParams);
|
||||||
|
const response = await setResponsePaging(queryParams, results, 'User Schedule found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get User Schedule by ID
|
||||||
|
static async getById(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await UserScheduleService.getUserScheduleByID(id);
|
||||||
|
const response = await setResponse(results, 'User Schedule found')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create User Schedule
|
||||||
|
static async create(req, res) {
|
||||||
|
const { error, value } = await checkValidate(insertUserScheduleSchema, req)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id
|
||||||
|
|
||||||
|
const results = await UserScheduleService.createUserSchedules(value);
|
||||||
|
const response = await setResponse(results, 'User Schedule created successfully')
|
||||||
|
|
||||||
|
return res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update User Schedule
|
||||||
|
static async update(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const { error, value } = checkValidate(updateUserScheduleSchema, req)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||||
|
}
|
||||||
|
|
||||||
|
value.userId = req.user.user_id
|
||||||
|
|
||||||
|
const results = await UserScheduleService.updateUserSchedules(id, value);
|
||||||
|
const response = await setResponse(results, 'User Schedule updated successfully')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete User Schedule
|
||||||
|
static async delete(req, res) {
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const results = await UserScheduleService.deleteUserSchedules(id, req.user.user_id);
|
||||||
|
const response = await setResponse(results, 'User Schedule deleted successfully')
|
||||||
|
|
||||||
|
res.status(response.statusCode).json(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = UserScheduleController;
|
||||||
107
db/brand.db.js
107
db/brand.db.js
@@ -4,23 +4,28 @@ const pool = require("../config");
|
|||||||
const getAllBrandsDb = async (searchParams = {}) => {
|
const getAllBrandsDb = async (searchParams = {}) => {
|
||||||
let queryParams = [];
|
let queryParams = [];
|
||||||
|
|
||||||
|
// Pagination
|
||||||
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];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Search
|
||||||
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
["b.brand_name"],
|
["a.brand_name", "a.brand_type", "a.brand_manufacture", "a.brand_model", "a.brand_code"],
|
||||||
searchParams.criteria,
|
searchParams.criteria,
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
|
|
||||||
queryParams = whereParamOr ? whereParamOr : queryParams;
|
queryParams = whereParamOr ? whereParamOr : queryParams;
|
||||||
|
|
||||||
|
// Filter
|
||||||
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
[
|
[
|
||||||
{ column: "b.brand_name", param: searchParams.name, type: "string" },
|
{ column: "a.brand_type", param: searchParams.type, type: "string" },
|
||||||
{ column: "b.created_by", param: searchParams.created_by, type: "number" },
|
{ column: "a.brand_manufacture", param: searchParams.manufacture, type: "string" },
|
||||||
|
{ column: "a.brand_model", param: searchParams.model, type: "string" },
|
||||||
|
{ column: "a.is_active", param: searchParams.status, type: "string" },
|
||||||
],
|
],
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
@@ -28,49 +33,57 @@ const getAllBrandsDb = async (searchParams = {}) => {
|
|||||||
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
||||||
|
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT COUNT(*) OVER() AS total_data, b.*
|
SELECT
|
||||||
FROM m_brands b
|
COUNT(*) OVER() AS total_data,
|
||||||
WHERE b.deleted_at IS NULL
|
a.*
|
||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
FROM m_brands a
|
||||||
${whereOrConditions ? whereOrConditions : ""}
|
WHERE a.deleted_at IS NULL
|
||||||
ORDER BY b.brand_id ASC
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
||||||
${searchParams.limit ? `OFFSET $2 ROWS FETCH NEXT $1 ROWS ONLY` : ""};
|
${whereOrConditions ? whereOrConditions : ''}
|
||||||
|
ORDER BY a.brand_id ASC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await pool.query(queryText, queryParams);
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
const total =
|
||||||
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
|
result?.recordset.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
return { data: result.recordset, total };
|
return { data: result.recordset, total };
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get brand by ID
|
// Get brand by name (path-based)
|
||||||
const getBrandByIdDb = async (id) => {
|
const getBrandByNameDb = async (brandName) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT b.*
|
SELECT
|
||||||
FROM m_brands b
|
a.*
|
||||||
WHERE b.brand_id = $1 AND b.deleted_at IS NULL
|
FROM m_brands a
|
||||||
|
WHERE a.brand_name = $1 AND a.deleted_at IS NULL
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [id]);
|
const result = await pool.query(queryText, [brandName]);
|
||||||
return result.recordset;
|
return result.recordset[0];
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get brand by name
|
// Get brand by ID (for internal use)
|
||||||
const getBrandByNameDb = async (name) => {
|
const getBrandByIdDb = async (id) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT b.*
|
SELECT
|
||||||
FROM m_brands b
|
a.*
|
||||||
WHERE b.brand_name = $1 AND b.deleted_at IS NULL
|
FROM m_brands a
|
||||||
|
WHERE a.brand_id = $1 AND a.deleted_at IS NULL
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [name]);
|
const result = await pool.query(queryText, [id]);
|
||||||
return result.recordset[0];
|
return result.recordset[0];
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create brand
|
// Create brand
|
||||||
const createBrandDb = async (data) => {
|
const createBrandDb = async (data) => {
|
||||||
|
const newCode = await pool.generateKode("BRD", "m_brands", "brand_code");
|
||||||
|
|
||||||
const store = {
|
const store = {
|
||||||
...data,
|
...data,
|
||||||
created_at: new Date(),
|
brand_code: newCode,
|
||||||
};
|
};
|
||||||
|
|
||||||
const { query: queryText, values } = pool.buildDynamicInsert("m_brands", store);
|
const { query: queryText, values } = pool.buildDynamicInsert("m_brands", store);
|
||||||
@@ -79,23 +92,17 @@ const createBrandDb = async (data) => {
|
|||||||
return insertedId ? await getBrandByIdDb(insertedId) : null;
|
return insertedId ? await getBrandByIdDb(insertedId) : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Update brand
|
// Update brand by name
|
||||||
const updateBrandDb = async (id, data) => {
|
const updateBrandDb = async (brandName, data) => {
|
||||||
const store = {
|
const store = { ...data };
|
||||||
...data,
|
const whereData = { brand_name: brandName };
|
||||||
updated_at: new Date(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const whereData = {
|
|
||||||
brand_id: id,
|
|
||||||
};
|
|
||||||
|
|
||||||
const { query: queryText, values } = pool.buildDynamicUpdate("m_brands", store, whereData);
|
const { query: queryText, values } = pool.buildDynamicUpdate("m_brands", store, whereData);
|
||||||
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
return getBrandByIdDb(id);
|
return getBrandByNameDb(brandName);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Soft delete brand
|
// Soft delete brand
|
||||||
const deleteBrandDb = async (id, deletedBy) => {
|
const deleteBrandDb = async (id, deletedBy) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
UPDATE m_brands
|
UPDATE m_brands
|
||||||
@@ -106,11 +113,31 @@ const deleteBrandDb = async (id, deletedBy) => {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Check if brand name exists (for validation)
|
||||||
|
const checkBrandNameExistsDb = async (brandName, excludeId = null) => {
|
||||||
|
let queryText = `
|
||||||
|
SELECT brand_id
|
||||||
|
FROM m_brands
|
||||||
|
WHERE brand_name = $1 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
let values = [brandName];
|
||||||
|
|
||||||
|
if (excludeId) {
|
||||||
|
queryText += ` AND brand_id != $2`;
|
||||||
|
values.push(excludeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
return result.recordset.length > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getAllBrandsDb,
|
getAllBrandsDb,
|
||||||
getBrandByIdDb,
|
|
||||||
getBrandByNameDb,
|
getBrandByNameDb,
|
||||||
|
getBrandByIdDb,
|
||||||
createBrandDb,
|
createBrandDb,
|
||||||
updateBrandDb,
|
updateBrandDb,
|
||||||
deleteBrandDb,
|
deleteBrandDb,
|
||||||
};
|
checkBrandNameExistsDb,
|
||||||
|
};
|
||||||
174
db/brand_code.db.js
Normal file
174
db/brand_code.db.js
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get error codes by brand ID
|
||||||
|
const getErrorCodesByBrandIdDb = async (brandId, searchParams = {}) => {
|
||||||
|
let queryParams = [brandId];
|
||||||
|
|
||||||
|
// Pagination
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [brandId, Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search across multiple columns
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
["a.error_code", "a.error_code_name", "a.error_code_description"],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamOr ? whereParamOr : queryParams;
|
||||||
|
|
||||||
|
// Filter conditions
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.is_active", param: searchParams.status, type: "string" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*
|
||||||
|
FROM brand_code a
|
||||||
|
WHERE a.brand_id = $1 AND a.deleted_at IS NULL
|
||||||
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
||||||
|
${whereOrConditions ? whereOrConditions : ''}
|
||||||
|
ORDER BY a.error_code_id DESC
|
||||||
|
${searchParams.limit ? `OFFSET $3 * $2 ROWS FETCH NEXT $2 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
// Return paginated format if limit is provided
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return simple array for backward compatibility
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createErrorCodeDb = async (brandId, data) => {
|
||||||
|
const store = {
|
||||||
|
brand_id: brandId,
|
||||||
|
error_code: data.error_code,
|
||||||
|
error_code_name: data.error_code_name,
|
||||||
|
error_code_description: data.error_code_description,
|
||||||
|
error_code_color: data.error_code_color,
|
||||||
|
path_icon: data.path_icon,
|
||||||
|
is_active: data.is_active,
|
||||||
|
created_by: data.created_by
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert("brand_code", store);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset[0]?.inserted_id;
|
||||||
|
return insertedId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateErrorCodeDb = async (brandId, errorCode, data) => {
|
||||||
|
const store = { ...data };
|
||||||
|
const whereData = {
|
||||||
|
brand_id: brandId,
|
||||||
|
error_code: errorCode
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate("brand_code", store, whereData);
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE brand_code
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE brand_id = $2 AND error_code = $3 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, brandId, errorCode]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getErrorCodeByIdDb = async (error_code_id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*
|
||||||
|
FROM brand_code a
|
||||||
|
WHERE a.error_code_id = $1 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [error_code_id]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getErrorCodeByBrandAndCodeDb = async (brandId, errorCode) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*
|
||||||
|
FROM brand_code a
|
||||||
|
WHERE a.brand_id = $1 AND a.error_code = $2 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [brandId, errorCode]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get all error codes with pagination and search
|
||||||
|
const getAllErrorCodesDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
// Pagination
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search across multiple columns
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
["a.error_code", "a.error_code_name", "a.error_code_description"],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamOr ? whereParamOr : queryParams;
|
||||||
|
|
||||||
|
// Filter conditions
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.is_active", param: searchParams.status, type: "string" },
|
||||||
|
{ column: "a.brand_id", param: searchParams.brand_id, type: "number" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*
|
||||||
|
FROM brand_code a
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
||||||
|
${whereOrConditions ? whereOrConditions : ''}
|
||||||
|
ORDER BY a.error_code_id DESC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getErrorCodesByBrandIdDb,
|
||||||
|
getErrorCodeByIdDb,
|
||||||
|
getErrorCodeByBrandAndCodeDb,
|
||||||
|
createErrorCodeDb,
|
||||||
|
updateErrorCodeDb,
|
||||||
|
deleteErrorCodeDb,
|
||||||
|
getAllErrorCodesDb,
|
||||||
|
};
|
||||||
60
db/brand_code_solution.db.js
Normal file
60
db/brand_code_solution.db.js
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get solutions by error code ID
|
||||||
|
const getSolutionsByErrorCodeIdDb = async (errorCodeId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*
|
||||||
|
FROM brand_code_solution a
|
||||||
|
WHERE a.error_code_id = $1 AND a.deleted_at IS NULL
|
||||||
|
ORDER BY a.brand_code_solution_id
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [errorCodeId]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create solution for error code
|
||||||
|
const createSolutionDb = async (errorCodeId, data) => {
|
||||||
|
const store = {
|
||||||
|
error_code_id: errorCodeId,
|
||||||
|
solution_name: data.solution_name,
|
||||||
|
type_solution: data.type_solution,
|
||||||
|
text_solution: data.text_solution,
|
||||||
|
path_solution: data.path_solution,
|
||||||
|
is_active: data.is_active,
|
||||||
|
created_by: data.created_by
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert("brand_code_solution", store);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset[0]?.inserted_id;
|
||||||
|
return insertedId;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update solution
|
||||||
|
const updateSolutionDb = async (solutionId, data) => {
|
||||||
|
const store = { ...data };
|
||||||
|
const whereData = { brand_code_solution_id: solutionId };
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate("brand_code_solution", store, whereData);
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Soft delete solution
|
||||||
|
const deleteSolutionDb = async (solutionId, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE brand_code_solution
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE brand_code_solution_id = $2 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, solutionId]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getSolutionsByErrorCodeIdDb,
|
||||||
|
createSolutionDb,
|
||||||
|
updateSolutionDb,
|
||||||
|
deleteSolutionDb,
|
||||||
|
};
|
||||||
187
db/brand_sparepart.db.js
Normal file
187
db/brand_sparepart.db.js
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get spareparts by error_code_id
|
||||||
|
const getSparepartsByErrorCodeIdDb = async (errorCodeId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
s.sparepart_id,
|
||||||
|
s.sparepart_name,
|
||||||
|
s.sparepart_code,
|
||||||
|
s.sparepart_description,
|
||||||
|
s.sparepart_model,
|
||||||
|
s.sparepart_foto,
|
||||||
|
s.sparepart_item_type,
|
||||||
|
s.sparepart_qty,
|
||||||
|
s.sparepart_unit,
|
||||||
|
s.sparepart_merk,
|
||||||
|
s.sparepart_stok,
|
||||||
|
bs.created_at,
|
||||||
|
bs.created_by
|
||||||
|
FROM brand_sparepart bs
|
||||||
|
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
||||||
|
WHERE bs.error_code_id = $1
|
||||||
|
AND s.deleted_at IS NULL
|
||||||
|
ORDER BY s.sparepart_name
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [errorCodeId]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get error codes by sparepart_id
|
||||||
|
const getErrorCodesBySparepartIdDb = async (sparepartId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
ec.error_code_id,
|
||||||
|
ec.error_code,
|
||||||
|
ec.error_code_name,
|
||||||
|
ec.error_code_description,
|
||||||
|
ec.error_code_color,
|
||||||
|
ec.path_icon,
|
||||||
|
ec.is_active,
|
||||||
|
ec.created_at,
|
||||||
|
ec.updated_at
|
||||||
|
FROM brand_sparepart bs
|
||||||
|
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
|
||||||
|
WHERE bs.sparepart_id = $1
|
||||||
|
AND ec.deleted_at IS NULL
|
||||||
|
ORDER BY ec.error_code
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [sparepartId]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Insert error_code-spareparts relationship
|
||||||
|
const insertErrorCodeSparepartDb = async (errorCodeId, sparepartId, createdBy) => {
|
||||||
|
const queryText = `
|
||||||
|
INSERT INTO brand_sparepart (error_code_id, sparepart_id, created_by, created_at)
|
||||||
|
VALUES ($1, $2, $3, CURRENT_TIMESTAMP)
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [errorCodeId, sparepartId, createdBy]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Insert multiple error_code-spareparts relationships
|
||||||
|
const insertMultipleErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, createdBy) => {
|
||||||
|
if (!sparepartIds || sparepartIds.length === 0) return [];
|
||||||
|
|
||||||
|
const values = sparepartIds.map((_, index) => `($1, $${index + 2}, $${sparepartIds.length + 2}, CURRENT_TIMESTAMP)`).join(', ');
|
||||||
|
const queryText = `
|
||||||
|
INSERT INTO brand_sparepart (error_code_id, sparepart_id, created_by, created_at)
|
||||||
|
VALUES ${values}
|
||||||
|
`;
|
||||||
|
const params = [errorCodeId, ...sparepartIds, createdBy];
|
||||||
|
const result = await pool.query(queryText, params);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Delete specific error_code-sparepart relationship
|
||||||
|
const deleteErrorCodeSparepartDb = async (errorCodeId, sparepartId) => {
|
||||||
|
const queryText = `
|
||||||
|
DELETE FROM brand_sparepart
|
||||||
|
WHERE error_code_id = $1 AND sparepart_id = $2
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [errorCodeId, sparepartId]);
|
||||||
|
return result.rowsAffected > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Delete all spareparts for an error_code
|
||||||
|
const deleteAllErrorCodeSparepartsDb = async (errorCodeId) => {
|
||||||
|
const queryText = `
|
||||||
|
DELETE FROM brand_sparepart
|
||||||
|
WHERE error_code_id = $1
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [errorCodeId]);
|
||||||
|
return result.rowsAffected > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update error_code-spareparts (replace all)
|
||||||
|
const updateErrorCodeSparepartsDb = async (errorCodeId, sparepartIds, updatedBy) => {
|
||||||
|
// Delete existing relationships
|
||||||
|
await deleteAllErrorCodeSparepartsDb(errorCodeId);
|
||||||
|
|
||||||
|
// Insert new relationships
|
||||||
|
if (sparepartIds && sparepartIds.length > 0) {
|
||||||
|
return await insertMultipleErrorCodeSparepartsDb(errorCodeId, sparepartIds, updatedBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkErrorCodeSparepartExistsDb = async (errorCodeId, sparepartId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT 1
|
||||||
|
FROM brand_spareparts
|
||||||
|
WHERE error_code_id = $1 AND sparepart_id = $2
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [errorCodeId, sparepartId]);
|
||||||
|
return result.recordset.length > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getSparepartsByBrandIdDb = async (brandId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT DISTINCT
|
||||||
|
s.sparepart_id,
|
||||||
|
s.sparepart_name,
|
||||||
|
s.sparepart_code,
|
||||||
|
s.sparepart_description,
|
||||||
|
s.sparepart_model,
|
||||||
|
s.sparepart_foto,
|
||||||
|
s.sparepart_item_type,
|
||||||
|
s.sparepart_qty,
|
||||||
|
s.sparepart_unit,
|
||||||
|
s.sparepart_merk,
|
||||||
|
s.sparepart_stok,
|
||||||
|
s.created_at,
|
||||||
|
s.updated_at
|
||||||
|
FROM brand_sparepart bs
|
||||||
|
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
||||||
|
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
|
||||||
|
WHERE ec.brand_id = $1
|
||||||
|
AND s.deleted_at IS NULL
|
||||||
|
AND ec.deleted_at IS NULL
|
||||||
|
ORDER BY s.sparepart_name
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [brandId]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get brands by sparepart_id (now using error_code_id mapping)
|
||||||
|
const getBrandsBySparepartIdDb = async (sparepartId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT DISTINCT
|
||||||
|
b.brand_id,
|
||||||
|
b.brand_name,
|
||||||
|
b.brand_type,
|
||||||
|
b.brand_manufacture,
|
||||||
|
b.brand_model,
|
||||||
|
b.brand_code,
|
||||||
|
b.is_active,
|
||||||
|
b.created_at,
|
||||||
|
b.updated_at
|
||||||
|
FROM brand_sparepart bs
|
||||||
|
JOIN m_sparepart s ON bs.sparepart_id = s.sparepart_id
|
||||||
|
JOIN m_error_codes ec ON bs.error_code_id = ec.error_code_id
|
||||||
|
JOIN m_brands b ON ec.brand_id = b.brand_id
|
||||||
|
WHERE bs.sparepart_id = $1
|
||||||
|
AND s.deleted_at IS NULL
|
||||||
|
AND ec.deleted_at IS NULL
|
||||||
|
AND b.deleted_at IS NULL
|
||||||
|
ORDER BY b.brand_name
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [sparepartId]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Deprecated functions removed - table structure changed to use error_code_id instead of brand_id
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
// New functions using error_code_id
|
||||||
|
getSparepartsByErrorCodeIdDb,
|
||||||
|
getErrorCodesBySparepartIdDb,
|
||||||
|
insertErrorCodeSparepartDb,
|
||||||
|
insertMultipleErrorCodeSparepartsDb,
|
||||||
|
deleteErrorCodeSparepartDb,
|
||||||
|
deleteAllErrorCodeSparepartsDb,
|
||||||
|
updateErrorCodeSparepartsDb,
|
||||||
|
checkErrorCodeSparepartExistsDb,
|
||||||
|
};
|
||||||
106
db/contact.db.js
Normal file
106
db/contact.db.js
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get all Contact
|
||||||
|
const getAllContactDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
[
|
||||||
|
"a.contact_name",
|
||||||
|
"a.contact_type",
|
||||||
|
],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.contact_name", param: searchParams.name, type: "string" },
|
||||||
|
{ column: "a.contact_type", param: searchParams.code, type: "string" },
|
||||||
|
{ column: "a.is_active", param: searchParams.active, type: "boolean" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*
|
||||||
|
FROM contact a
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
ORDER BY a.contact_id ASC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total =
|
||||||
|
result?.recordset?.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const getContactByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*
|
||||||
|
FROM contact a
|
||||||
|
WHERE a.contact_id = $1 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createContactDb = async (store) => {
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert("contact", store);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset?.[0]?.inserted_id;
|
||||||
|
|
||||||
|
return insertedId ? await getContactByIdDb(insertedId) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateContactDb = async (id, data) => {
|
||||||
|
const store = { ...data };
|
||||||
|
const whereData = { contact_id: id };
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||||
|
"contact",
|
||||||
|
store,
|
||||||
|
whereData
|
||||||
|
);
|
||||||
|
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return getContactByIdDb(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Soft delete tag
|
||||||
|
const deleteContactDb = async (id, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE contact
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE contact_id = $2 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getAllContactDb,
|
||||||
|
getContactByIdDb,
|
||||||
|
createContactDb,
|
||||||
|
updateContactDb,
|
||||||
|
deleteContactDb,
|
||||||
|
};
|
||||||
@@ -50,7 +50,7 @@ const getAllDevicesDb = async (searchParams = {}) => {
|
|||||||
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
||||||
${whereOrConditions ? whereOrConditions : ''}
|
${whereOrConditions ? whereOrConditions : ''}
|
||||||
ORDER BY a.device_id ASC
|
ORDER BY a.device_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
|
|||||||
92
db/file_uploads.db.js
Normal file
92
db/file_uploads.db.js
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get file upload by path
|
||||||
|
const getFileUploadByPathDb = async (path) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
file_upload_id,
|
||||||
|
file_upload_name,
|
||||||
|
type_document,
|
||||||
|
path_document,
|
||||||
|
created_by,
|
||||||
|
updated_by,
|
||||||
|
deleted_by,
|
||||||
|
created_at,
|
||||||
|
updated_at,
|
||||||
|
deleted_at
|
||||||
|
FROM file_upload
|
||||||
|
WHERE path_document = $1 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [path]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create file upload
|
||||||
|
const createFileUploadDb = async (data) => {
|
||||||
|
const store = {
|
||||||
|
file_upload_name: data.file_upload_name,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add path_document if exists
|
||||||
|
if (data.path_document) {
|
||||||
|
store.path_document = data.path_document;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add type_document if exists
|
||||||
|
if (data.type_document) {
|
||||||
|
store.type_document = data.type_document;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.createdBy) {
|
||||||
|
store.created_by = data.createdBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Data to insert:', store);
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
INSERT INTO file_upload (file_upload_name, path_document, type_document, created_by, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
|
||||||
|
SELECT SCOPE_IDENTITY() as inserted_id;
|
||||||
|
`;
|
||||||
|
const values = [
|
||||||
|
store.file_upload_name,
|
||||||
|
store.path_document,
|
||||||
|
store.type_document,
|
||||||
|
store.created_by || null
|
||||||
|
];
|
||||||
|
|
||||||
|
// console.log('Manual Query:', queryText);
|
||||||
|
// console.log('Manual Values:', values);
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Soft delete file upload by path
|
||||||
|
const deleteFileUploadByPathDb = async (path, deletedBy = null) => {
|
||||||
|
const store = {
|
||||||
|
deleted_at: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (deletedBy) {
|
||||||
|
store.deleted_by = deletedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
const whereData = {
|
||||||
|
path_document: path,
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||||
|
"file_upload",
|
||||||
|
store,
|
||||||
|
whereData
|
||||||
|
);
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getFileUploadByPathDb,
|
||||||
|
createFileUploadDb,
|
||||||
|
deleteFileUploadByPathDb,
|
||||||
|
};
|
||||||
568
db/history_value.db.js
Normal file
568
db/history_value.db.js
Normal file
@@ -0,0 +1,568 @@
|
|||||||
|
const { columns } = require("mssql");
|
||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
const getHistoryAlarmDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
[
|
||||||
|
"b.tag_name",
|
||||||
|
"a.tagnum"
|
||||||
|
],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "b.tag_name", param: searchParams.name, type: "string" },
|
||||||
|
{ column: "b.tag_number", param: searchParams.name, type: "number" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*,
|
||||||
|
b.tag_name,
|
||||||
|
b.tag_number,
|
||||||
|
b.lim_low_crash,
|
||||||
|
b.lim_low,
|
||||||
|
b.lim_high,
|
||||||
|
b.lim_high_crash,
|
||||||
|
c.status_color
|
||||||
|
FROM alarm_history a
|
||||||
|
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
|
||||||
|
LEFT JOIN m_status c ON a.status = c.status_number AND c.deleted_at IS NULL
|
||||||
|
WHERE a.datetime IS NOT NULL
|
||||||
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
ORDER BY a.datetime DESC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total =
|
||||||
|
result?.recordset?.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const getHistoryEventDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
[
|
||||||
|
"b.tag_name",
|
||||||
|
"a.tagnum"
|
||||||
|
],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "b.tag_name", param: searchParams.name, type: "string" },
|
||||||
|
{ column: "b.tag_number", param: searchParams.name, type: "number" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*,
|
||||||
|
c.status_color
|
||||||
|
FROM event_alarm a
|
||||||
|
LEFT JOIN m_status c ON a.status = c.status_number AND c.deleted_at IS NULL
|
||||||
|
WHERE a.datetime IS NOT NULL
|
||||||
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
ORDER BY a.datetime DESC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total =
|
||||||
|
result?.recordset?.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkTableNamedDb = async (tableName) => {
|
||||||
|
try {
|
||||||
|
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||||
|
throw new Error('Invalid table name format');
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT TABLE_NAME, TABLE_SCHEMA, TABLE_TYPE
|
||||||
|
FROM INFORMATION_SCHEMA.TABLES
|
||||||
|
WHERE TABLE_NAME = $1
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, [tableName]);
|
||||||
|
return result.recordset;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in checkTableNamedDb:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getHistoryValueReportDb = async (tableName, searchParams = {}) => {
|
||||||
|
try {
|
||||||
|
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||||
|
throw new Error('Invalid table name format');
|
||||||
|
}
|
||||||
|
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
["b.tag_name", "CAST(a.tagnum AS VARCHAR)"],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "b.tag_name", param: searchParams.name, type: "string" },
|
||||||
|
{ column: "b.tag_number", param: searchParams.name, type: "number" },
|
||||||
|
{ column: "a.datetime", param: [searchParams.from, searchParams.to], type: "between" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*,
|
||||||
|
b.tag_name,
|
||||||
|
b.tag_number,
|
||||||
|
b.lim_low_crash,
|
||||||
|
b.lim_low,
|
||||||
|
b.lim_high,
|
||||||
|
b.lim_high_crash,
|
||||||
|
c.status_color
|
||||||
|
FROM ${tableName} a
|
||||||
|
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
|
||||||
|
LEFT JOIN m_status c ON a.status = c.status_number AND c.deleted_at IS NULL
|
||||||
|
WHERE a.datetime IS NOT NULL AND b.is_report = 1
|
||||||
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
ORDER BY a.datetime DESC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total = result.recordset?.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getHistoryValueReportDb:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getHistoryValueReportPivotDb = async (tableName, searchParams = {}) => {
|
||||||
|
try {
|
||||||
|
if (!tableName || !/^[a-zA-Z0-9_]+$/.test(tableName)) {
|
||||||
|
throw new Error('Invalid table name format');
|
||||||
|
}
|
||||||
|
|
||||||
|
let from = searchParams.from || '';
|
||||||
|
let to = searchParams.to || '';
|
||||||
|
const interval = Math.max(1, Math.min(1440, Number(searchParams.interval ?? 10)));
|
||||||
|
|
||||||
|
if (from.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(from)) {
|
||||||
|
from += ' 00:00:00';
|
||||||
|
}
|
||||||
|
if (to.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(to)) {
|
||||||
|
to += ' 23:59:59';
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Table:', tableName);
|
||||||
|
console.log('From:', from, '| To:', to, '| Interval:', interval);
|
||||||
|
console.log('Filters:', searchParams);
|
||||||
|
|
||||||
|
const dateRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
||||||
|
if (!dateRegex.test(from) || !dateRegex.test(to)) {
|
||||||
|
throw new Error('Invalid date format. Expected: YYYY-MM-DD or YYYY-MM-DD HH:MM:SS');
|
||||||
|
}
|
||||||
|
|
||||||
|
const fromDate = new Date(from);
|
||||||
|
const toDate = new Date(to);
|
||||||
|
const daysDiff = (toDate - fromDate) / (1000 * 60 * 60 * 24);
|
||||||
|
|
||||||
|
if (daysDiff > 365) {
|
||||||
|
throw new Error('Date range cannot exceed 1 year');
|
||||||
|
}
|
||||||
|
if (daysDiff < 0) {
|
||||||
|
throw new Error('From date must be before to date');
|
||||||
|
}
|
||||||
|
|
||||||
|
let tagQueryParams = [];
|
||||||
|
let tagWhereConditions = [];
|
||||||
|
|
||||||
|
if (searchParams.plant_sub_section_id) {
|
||||||
|
tagWhereConditions.push(`plant_sub_section_id = $${tagQueryParams.length + 1}`);
|
||||||
|
tagQueryParams.push(searchParams.plant_sub_section_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchParams.plant_section_id) {
|
||||||
|
tagWhereConditions.push(`plant_section_id = $${tagQueryParams.length + 1}`);
|
||||||
|
tagQueryParams.push(searchParams.plant_section_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchParams.name) {
|
||||||
|
const nameFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
|
||||||
|
tagWhereConditions.push(nameFilter);
|
||||||
|
tagQueryParams.push(`%${searchParams.name}%`, `%${searchParams.name}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchParams.criteria) {
|
||||||
|
const criteriaFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
|
||||||
|
tagWhereConditions.push(criteriaFilter);
|
||||||
|
tagQueryParams.push(`%${searchParams.criteria}%`, `%${searchParams.criteria}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tagWhereClause = tagWhereConditions.length > 0
|
||||||
|
? ` AND ${tagWhereConditions.join(" AND ")}`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const tagsQuery = `
|
||||||
|
SELECT tag_name, tag_number
|
||||||
|
FROM m_tags
|
||||||
|
WHERE is_report = 1 AND deleted_at IS NULL
|
||||||
|
${tagWhereClause}
|
||||||
|
ORDER BY tag_name
|
||||||
|
`;
|
||||||
|
|
||||||
|
console.log('Tags Query:', tagsQuery);
|
||||||
|
console.log('Tags Query Params:', tagQueryParams);
|
||||||
|
|
||||||
|
const tagsResult = await pool.query(tagsQuery, tagQueryParams);
|
||||||
|
|
||||||
|
console.log('Tags found:', tagsResult.recordset.length);
|
||||||
|
|
||||||
|
if (tagsResult.recordset.length === 0) {
|
||||||
|
return { data: [], column: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const tagNames = tagsResult.recordset.map(r => `[${r.tag_name}]`).join(', ');
|
||||||
|
const tagNamesColumn = tagsResult.recordset.map(r => r.tag_name).join(', ');
|
||||||
|
const tagNumbers = tagsResult.recordset.map(r => r.tag_number);
|
||||||
|
|
||||||
|
console.log('Filtered tag numbers:', tagNumbers);
|
||||||
|
console.log('Filtered tag names:', tagNamesColumn);
|
||||||
|
|
||||||
|
const tagNumbersFilter = tagNumbers.length > 0
|
||||||
|
? ` AND a.tagnum IN (${tagNumbers.join(',')})`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
DECLARE
|
||||||
|
@fromParam DATETIME = $1,
|
||||||
|
@toParam DATETIME = $2,
|
||||||
|
@intervalParam INT = $3;
|
||||||
|
|
||||||
|
SELECT TOP 10
|
||||||
|
'DEBUG_AVERAGING' as info,
|
||||||
|
b.tag_name,
|
||||||
|
DATEADD(MINUTE,
|
||||||
|
(DATEDIFF(MINUTE, @fromParam, CAST(a.datetime AS DATETIME)) / @intervalParam) * @intervalParam,
|
||||||
|
@fromParam
|
||||||
|
) AS waktu_group,
|
||||||
|
COUNT(*) as data_points,
|
||||||
|
AVG(CAST(a.val AS FLOAT)) as avg_val,
|
||||||
|
MIN(CAST(a.val AS FLOAT)) as min_val,
|
||||||
|
MAX(CAST(a.val AS FLOAT)) as max_val
|
||||||
|
FROM ${tableName} a
|
||||||
|
INNER JOIN m_tags b ON a.tagnum = b.tag_number
|
||||||
|
AND b.deleted_at IS NULL
|
||||||
|
AND b.is_report = 1
|
||||||
|
WHERE CAST(a.datetime AS DATETIME) BETWEEN @fromParam AND @toParam
|
||||||
|
AND a.val IS NOT NULL
|
||||||
|
${tagNumbersFilter}
|
||||||
|
GROUP BY
|
||||||
|
b.tag_name,
|
||||||
|
DATEADD(MINUTE,
|
||||||
|
(DATEDIFF(MINUTE, @fromParam, CAST(a.datetime AS DATETIME)) / @intervalParam) * @intervalParam,
|
||||||
|
@fromParam
|
||||||
|
)
|
||||||
|
ORDER BY b.tag_name, waktu_group;
|
||||||
|
|
||||||
|
;WITH TimeSeries AS (
|
||||||
|
SELECT @fromParam AS waktu
|
||||||
|
UNION ALL
|
||||||
|
SELECT DATEADD(MINUTE, @intervalParam, waktu)
|
||||||
|
FROM TimeSeries
|
||||||
|
WHERE DATEADD(MINUTE, @intervalParam, waktu) <= @toParam
|
||||||
|
),
|
||||||
|
CleanData AS (
|
||||||
|
SELECT
|
||||||
|
CAST(a.datetime AS DATETIME) as datetime_clean,
|
||||||
|
a.tagnum,
|
||||||
|
CAST(a.val AS FLOAT) as val,
|
||||||
|
b.tag_name
|
||||||
|
FROM ${tableName} a
|
||||||
|
INNER JOIN m_tags b ON a.tagnum = b.tag_number
|
||||||
|
AND b.deleted_at IS NULL
|
||||||
|
AND b.is_report = 1
|
||||||
|
WHERE ISDATE(a.datetime) = 1
|
||||||
|
AND a.val IS NOT NULL
|
||||||
|
AND CAST(a.datetime AS DATETIME) BETWEEN @fromParam AND @toParam
|
||||||
|
${tagNumbersFilter}
|
||||||
|
),
|
||||||
|
Averaged AS (
|
||||||
|
SELECT
|
||||||
|
DATEADD(MINUTE,
|
||||||
|
(DATEDIFF(MINUTE, @fromParam, datetime_clean) / @intervalParam) * @intervalParam,
|
||||||
|
@fromParam
|
||||||
|
) AS waktu_group,
|
||||||
|
tag_name,
|
||||||
|
AVG(val) AS avg_val
|
||||||
|
FROM CleanData
|
||||||
|
GROUP BY
|
||||||
|
DATEADD(MINUTE,
|
||||||
|
(DATEDIFF(MINUTE, @fromParam, datetime_clean) / @intervalParam) * @intervalParam,
|
||||||
|
@fromParam
|
||||||
|
),
|
||||||
|
tag_name
|
||||||
|
),
|
||||||
|
Pivoted AS (
|
||||||
|
SELECT
|
||||||
|
waktu_group,
|
||||||
|
${tagNames}
|
||||||
|
FROM Averaged
|
||||||
|
PIVOT (
|
||||||
|
MAX(avg_val)
|
||||||
|
FOR tag_name IN (${tagNames})
|
||||||
|
) AS p
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
CONVERT(VARCHAR(19), ts.waktu, 120) AS waktu,
|
||||||
|
${tagNames}
|
||||||
|
FROM TimeSeries ts
|
||||||
|
LEFT JOIN Pivoted p ON ts.waktu = p.waktu_group
|
||||||
|
ORDER BY ts.waktu
|
||||||
|
OPTION (MAXRECURSION 0);
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, [from, to, interval]);
|
||||||
|
|
||||||
|
if (result.recordsets && result.recordsets.length >= 2) {
|
||||||
|
console.log('Sample averaging data:');
|
||||||
|
result.recordsets[0].slice(0, 10).forEach(row => {
|
||||||
|
console.log(`${row.tag_name} @ ${row.waktu_group}: avg=${row.avg_val}, min=${row.min_val}, max=${row.max_val}, points=${row.data_points}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('\nPivot result sample:');
|
||||||
|
if (result.recordsets[1] && result.recordsets[1].length > 0) {
|
||||||
|
result.recordsets[1].slice(0, 5).forEach(row => {
|
||||||
|
console.log(JSON.stringify(row, null, 2));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = result.recordsets?.[1] || result.recordset;
|
||||||
|
|
||||||
|
if (!rows || rows.length === 0) {
|
||||||
|
console.log('No pivot data');
|
||||||
|
return { data: [], column: tagNamesColumn };
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeKey = 'waktu';
|
||||||
|
const tagList = Object.keys(rows[0]).filter(k => k !== timeKey);
|
||||||
|
|
||||||
|
const nivoData = tagList.map(tag => ({
|
||||||
|
id: tag,
|
||||||
|
data: rows.map(row => ({
|
||||||
|
x: row[timeKey],
|
||||||
|
y: row[tag] !== null && row[tag] !== undefined ? Number(row[tag]) : null
|
||||||
|
}))
|
||||||
|
}));
|
||||||
|
|
||||||
|
nivoData.forEach(series => {
|
||||||
|
const nonNull = series.data.filter(d => d.y !== null && d.y !== 0);
|
||||||
|
const sampleVals = nonNull.slice(0, 3).map(d => d.y);
|
||||||
|
console.log(`${series.id}: ${nonNull.length} non-zero values, sample: [${sampleVals.join(', ')}]`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data: nivoData, column: tagNamesColumn };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in getHistoryValueReportPivotDb:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getHistoryValueTrendingPivotDb = async (tableName, searchParams = {}) => {
|
||||||
|
let from = searchParams.from;
|
||||||
|
let to = searchParams.to;
|
||||||
|
|
||||||
|
// pastikan interval berupa number dan ada nilai default
|
||||||
|
const interval = Number(searchParams.interval) > 0 ? Number(searchParams.interval) : 10;
|
||||||
|
|
||||||
|
// --- Normalisasi tanggal (kalau cuma tanggal tanpa jam)
|
||||||
|
if (from.length === 10) from += ' 00:00:00';
|
||||||
|
if (to.length === 10) to += ' 23:59:59';
|
||||||
|
|
||||||
|
let tagQueryParams = [];
|
||||||
|
let tagWhereConditions = [];
|
||||||
|
|
||||||
|
if (searchParams.plant_sub_section_id) {
|
||||||
|
tagWhereConditions.push(`plant_sub_section_id = $${tagQueryParams.length + 1}`);
|
||||||
|
tagQueryParams.push(searchParams.plant_sub_section_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchParams.plant_section_id) {
|
||||||
|
tagWhereConditions.push(`plant_section_id = $${tagQueryParams.length + 1}`);
|
||||||
|
tagQueryParams.push(searchParams.plant_section_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchParams.name) {
|
||||||
|
const nameFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
|
||||||
|
tagWhereConditions.push(nameFilter);
|
||||||
|
tagQueryParams.push(`%${searchParams.name}%`, `%${searchParams.name}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchParams.criteria) {
|
||||||
|
const criteriaFilter = `(tag_name LIKE $${tagQueryParams.length + 1} OR CAST(tag_number AS VARCHAR) LIKE $${tagQueryParams.length + 2})`;
|
||||||
|
tagWhereConditions.push(criteriaFilter);
|
||||||
|
tagQueryParams.push(`%${searchParams.criteria}%`, `%${searchParams.criteria}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tagWhereClause = tagWhereConditions.length > 0
|
||||||
|
? ` AND ${tagWhereConditions.join(" AND ")}`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const tagsQuery = `
|
||||||
|
SELECT tag_name, tag_number
|
||||||
|
FROM m_tags
|
||||||
|
WHERE is_report = 1 AND deleted_at IS NULL
|
||||||
|
${tagWhereClause}
|
||||||
|
ORDER BY tag_name
|
||||||
|
`;
|
||||||
|
|
||||||
|
const tags = await pool.query(tagsQuery, tagQueryParams);
|
||||||
|
|
||||||
|
if (tags.recordset.length === 0) {
|
||||||
|
return { data: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const tagNames = tags.recordset.map(r => `[${r.tag_name}]`).join(', ');
|
||||||
|
const tagNumbers = tags.recordset.map(r => r.tag_number);
|
||||||
|
|
||||||
|
const tagNumbersFilter = tagNumbers.length > 0
|
||||||
|
? ` AND a.tagnum IN (${tagNumbers.join(',')})`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
DECLARE
|
||||||
|
@fromParam DATETIME = '${from}',
|
||||||
|
@toParam DATETIME = '${to}',
|
||||||
|
@intervalParam INT = ${interval};
|
||||||
|
|
||||||
|
;WITH TimeSeries AS (
|
||||||
|
SELECT @fromParam AS waktu
|
||||||
|
UNION ALL
|
||||||
|
SELECT DATEADD(MINUTE, @intervalParam, waktu)
|
||||||
|
FROM TimeSeries
|
||||||
|
WHERE DATEADD(MINUTE, @intervalParam, waktu) <= @toParam
|
||||||
|
),
|
||||||
|
Averaged AS (
|
||||||
|
SELECT
|
||||||
|
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, CAST(a.datetime AS DATETIME)) / @intervalParam * @intervalParam, 0) AS waktu_group,
|
||||||
|
b.tag_name,
|
||||||
|
ROUND(AVG(a.val), 4) AS avg_val
|
||||||
|
FROM ${tableName} a
|
||||||
|
LEFT JOIN m_tags b ON a.tagnum = b.tag_number AND b.deleted_at IS NULL
|
||||||
|
WHERE a.datetime BETWEEN @fromParam AND @toParam
|
||||||
|
${tagNumbersFilter}
|
||||||
|
GROUP BY
|
||||||
|
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, CAST(a.datetime AS DATETIME)) / @intervalParam * @intervalParam, 0),
|
||||||
|
b.tag_name
|
||||||
|
),
|
||||||
|
Pivoted AS (
|
||||||
|
SELECT
|
||||||
|
waktu_group,
|
||||||
|
${tagNames}
|
||||||
|
FROM Averaged
|
||||||
|
PIVOT (
|
||||||
|
MAX(avg_val)
|
||||||
|
FOR tag_name IN (${tagNames})
|
||||||
|
) AS p
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
CONVERT(VARCHAR(16), ts.waktu, 120) AS waktu,
|
||||||
|
${tagNames}
|
||||||
|
FROM TimeSeries ts
|
||||||
|
LEFT JOIN Pivoted p ON ts.waktu = p.waktu_group
|
||||||
|
ORDER BY ts.waktu
|
||||||
|
OPTION (MAXRECURSION 0);
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText);
|
||||||
|
const rows = result.recordset;
|
||||||
|
|
||||||
|
if (!rows || rows.length === 0) return { data: [] };
|
||||||
|
|
||||||
|
// --- Bentuk data untuk Nivo Chart
|
||||||
|
const timeKey = 'waktu';
|
||||||
|
const tagList = Object.keys(rows[0]).filter(k => k !== timeKey);
|
||||||
|
|
||||||
|
const nivoData = tagList.map(tag => ({
|
||||||
|
id: tag,
|
||||||
|
data: rows.map(row => ({
|
||||||
|
x: row[timeKey],
|
||||||
|
y: row[tag] !== null ? Number(row[tag]) : null
|
||||||
|
}))
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { data: nivoData };
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getHistoryAlarmDb,
|
||||||
|
getHistoryEventDb,
|
||||||
|
checkTableNamedDb,
|
||||||
|
getHistoryValueReportDb,
|
||||||
|
getHistoryValueReportPivotDb,
|
||||||
|
getHistoryValueTrendingPivotDb
|
||||||
|
};
|
||||||
211
db/notification_error.db.js
Normal file
211
db/notification_error.db.js
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
const InsertNotificationErrorDb = async (store) => {
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert(
|
||||||
|
"notification_error",
|
||||||
|
store
|
||||||
|
);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset?.[0]?.inserted_id;
|
||||||
|
|
||||||
|
return insertedId ? await getNotificationByIdDb(insertedId) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getNotificationByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
b.plant_sub_section_id,
|
||||||
|
c.plant_sub_section_name,
|
||||||
|
d.device_code,
|
||||||
|
d.device_name,
|
||||||
|
d.device_location,
|
||||||
|
d.listen_channel,
|
||||||
|
e.brand_name
|
||||||
|
|
||||||
|
FROM notification_error a
|
||||||
|
|
||||||
|
LEFT JOIN m_tags b
|
||||||
|
ON a.error_chanel = b.tag_number
|
||||||
|
|
||||||
|
LEFT JOIN m_plant_sub_section c
|
||||||
|
ON b.plant_sub_section_id = c.plant_sub_section_id
|
||||||
|
|
||||||
|
LEFT JOIN m_device d
|
||||||
|
ON a.error_chanel = d.listen_channel AND d.deleted_at IS NULL
|
||||||
|
|
||||||
|
LEFT JOIN m_brands e
|
||||||
|
ON d.brand_id = e.brand_id AND d.deleted_at IS NULL
|
||||||
|
|
||||||
|
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getDeviceNotificationByIdDb = async (chanel_id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
device_code,
|
||||||
|
device_name,
|
||||||
|
device_location,
|
||||||
|
listen_channel
|
||||||
|
|
||||||
|
FROM m_device
|
||||||
|
WHERE listen_channel = $1
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [chanel_id]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const getAllNotificationDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
[
|
||||||
|
"a.message_error_issue",
|
||||||
|
"a.is_send",
|
||||||
|
"a.is_delivered",
|
||||||
|
"a.is_read",
|
||||||
|
"a.is_active",
|
||||||
|
"b.error_code",
|
||||||
|
"b.error_code_name",
|
||||||
|
],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.message_error_issue", param: searchParams.message_error_issue, type: "string" },
|
||||||
|
{ column: "a.is_send", param: searchParams.is_send, type: "number" },
|
||||||
|
{ column: "a.is_delivered", param: searchParams.is_delivered, type: "number" },
|
||||||
|
{ column: "a.is_read", param: searchParams.is_read, type: "number" },
|
||||||
|
{ column: "a.is_active", param: searchParams.is_active, type: "number" },
|
||||||
|
{ column: "b.error_code", param: searchParams.error_code, type: "string" },
|
||||||
|
{ column: "b.error_code_name", param: searchParams.error_code_name, type: "string" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
|
||||||
|
a.notification_error_id,
|
||||||
|
a.error_code_id,
|
||||||
|
a.message_error_issue,
|
||||||
|
a.is_send,
|
||||||
|
a.is_delivered,
|
||||||
|
a.is_read,
|
||||||
|
a.is_active,
|
||||||
|
a.created_at,
|
||||||
|
|
||||||
|
b.error_code,
|
||||||
|
b.error_code_name,
|
||||||
|
b.error_code_color,
|
||||||
|
b.path_icon,
|
||||||
|
|
||||||
|
c.solution_name,
|
||||||
|
c.type_solution,
|
||||||
|
c.path_solution,
|
||||||
|
|
||||||
|
d.device_code,
|
||||||
|
d.device_name,
|
||||||
|
d.device_location,
|
||||||
|
d.listen_channel,
|
||||||
|
e.brand_name,
|
||||||
|
|
||||||
|
COALESCE(d.device_name, '') + ' - ' + COALESCE(b.error_code_name, '') AS device_name_error
|
||||||
|
|
||||||
|
FROM notification_error a
|
||||||
|
|
||||||
|
LEFT JOIN brand_code b
|
||||||
|
ON a.error_code_id = b.error_code_id AND b.deleted_at IS NULL
|
||||||
|
|
||||||
|
LEFT JOIN brand_code_solution c
|
||||||
|
ON b.error_code_id = c.error_code_id AND c.deleted_at IS NULL
|
||||||
|
|
||||||
|
LEFT JOIN m_device d
|
||||||
|
ON a.error_chanel = d.listen_channel AND d.deleted_at IS NULL
|
||||||
|
|
||||||
|
LEFT JOIN m_brands e
|
||||||
|
ON d.brand_id = e.brand_id AND d.deleted_at IS NULL
|
||||||
|
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
|
||||||
|
ORDER BY a.notification_error_id DESC
|
||||||
|
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total =
|
||||||
|
result?.recordset?.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateNotificationErrorDb = async (id, data) => {
|
||||||
|
const store = { ...data };
|
||||||
|
const whereData = { notification_error_id: id };
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||||
|
"notification_error",
|
||||||
|
store,
|
||||||
|
whereData
|
||||||
|
);
|
||||||
|
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return getNotificationByIdDb(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getUsersNotificationErrorDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
b.notification_error_id,
|
||||||
|
a.notification_error_user_id,
|
||||||
|
a.contact_phone,
|
||||||
|
a.contact_name,
|
||||||
|
a.is_send,
|
||||||
|
a.updated_at,
|
||||||
|
c.is_active
|
||||||
|
|
||||||
|
FROM notification_error_user a
|
||||||
|
|
||||||
|
LEFT JOIN notification_error b ON a.notification_error_id = b.notification_error_id
|
||||||
|
|
||||||
|
LEFT JOIN contact c ON a.contact_phone = c.contact_phone
|
||||||
|
|
||||||
|
WHERE a.notification_error_id = $1
|
||||||
|
AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getNotificationByIdDb,
|
||||||
|
getDeviceNotificationByIdDb,
|
||||||
|
getAllNotificationDb,
|
||||||
|
InsertNotificationErrorDb,
|
||||||
|
updateNotificationErrorDb,
|
||||||
|
getUsersNotificationErrorDb
|
||||||
|
|
||||||
|
};
|
||||||
94
db/notification_error_log.db.js
Normal file
94
db/notification_error_log.db.js
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
const getAllNotificationErrorLogDb = async () => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
b.contact_name,
|
||||||
|
b.contact_type
|
||||||
|
FROM notification_error_log a
|
||||||
|
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
ORDER BY a.notification_error_log_id DESC
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getNotificationErrorLogByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
b.contact_name,
|
||||||
|
b.contact_type
|
||||||
|
FROM notification_error_log a
|
||||||
|
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
|
||||||
|
WHERE a.notification_error_log_id = $1 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getNotificationErrorLogByNotificationErrorIdDb = async (notificationErrorId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.notification_error_log_description,
|
||||||
|
a.created_at,
|
||||||
|
b.contact_type,
|
||||||
|
c.user_fullname as created_by_name,
|
||||||
|
case when a.created_by is not null then c.user_fullname else b.contact_name end as contact_name,
|
||||||
|
case when a.created_by is not null then c.user_phone else a.contact_phone end as contact_phone
|
||||||
|
FROM notification_error_log a
|
||||||
|
LEFT JOIN contact b ON a.contact_phone = b.contact_phone
|
||||||
|
LEFT JOIN m_users c ON a.created_by = c.user_id
|
||||||
|
WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
|
||||||
|
ORDER BY a.created_at DESC
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [notificationErrorId]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createNotificationErrorLogDb = async (store) => {
|
||||||
|
const queryText = `
|
||||||
|
INSERT INTO notification_error_log (
|
||||||
|
notification_error_id,
|
||||||
|
contact_phone,
|
||||||
|
notification_error_log_description,
|
||||||
|
created_by,
|
||||||
|
updated_by,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
)
|
||||||
|
VALUES ($1, $2, $3, $4, $4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
|
||||||
|
SELECT SCOPE_IDENTITY() as inserted_id;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const values = [
|
||||||
|
store.notification_error_id,
|
||||||
|
store.contact_phone,
|
||||||
|
store.notification_error_log_description,
|
||||||
|
store.created_by
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset[0]?.inserted_id;
|
||||||
|
return insertedId ? await getNotificationErrorLogByIdDb(insertedId) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteNotificationErrorLogDb = async (id, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE notification_error_log
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE notification_error_log_id = $2 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getAllNotificationErrorLogDb,
|
||||||
|
getNotificationErrorLogByIdDb,
|
||||||
|
getNotificationErrorLogByNotificationErrorIdDb,
|
||||||
|
createNotificationErrorLogDb,
|
||||||
|
deleteNotificationErrorLogDb,
|
||||||
|
};
|
||||||
176
db/notification_error_sparepart.db.js
Normal file
176
db/notification_error_sparepart.db.js
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
const insertNotificationErrorSparepartDb = async () => {
|
||||||
|
const insertQuery = `
|
||||||
|
INSERT INTO notification_error_sparepart (
|
||||||
|
notification_error_id,
|
||||||
|
brand_sparepart_id
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
ne.notification_error_id,
|
||||||
|
bs.brand_sparepart_id
|
||||||
|
|
||||||
|
FROM notification_error ne
|
||||||
|
|
||||||
|
INNER JOIN brand_sparepart bs
|
||||||
|
ON ne.error_code_id = bs.error_code_id
|
||||||
|
|
||||||
|
LEFT JOIN notification_error_sparepart nes
|
||||||
|
ON nes.notification_error_id = ne.notification_error_id
|
||||||
|
AND nes.brand_sparepart_id = bs.brand_sparepart_id
|
||||||
|
AND nes.deleted_at IS NULL
|
||||||
|
|
||||||
|
WHERE ne.deleted_at IS NULL
|
||||||
|
AND nes.notification_error_sparepart_id IS NULL;
|
||||||
|
`;
|
||||||
|
|
||||||
|
await pool.query(insertQuery);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getAllNotificationErrorSparepartDb = async (searchParams = {}) => {
|
||||||
|
await insertNotificationErrorSparepartDb();
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
[
|
||||||
|
"a.brand_sparepart_id",
|
||||||
|
"a.device_id",
|
||||||
|
"a.sparepart_id",
|
||||||
|
"b.sparepart_name",
|
||||||
|
"d.device_name",
|
||||||
|
],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.brand_sparepart_id", param: searchParams.name, type: "int" },
|
||||||
|
{ column: "a.device_id", param: searchParams.code, type: "int" },
|
||||||
|
{ column: "a.unit", param: searchParams.unit, type: "string" },
|
||||||
|
{ column: "b.sparepart_name", param: searchParams.device, type: "string" },
|
||||||
|
{ column: "d.device_name", param: searchParams.device, type: "string" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*,
|
||||||
|
b.sparepart_name,
|
||||||
|
b.sparepart_foto,
|
||||||
|
b.sparepart_stok,
|
||||||
|
b.sparepart_qty,
|
||||||
|
b.sparepart_description,
|
||||||
|
b.sparepart_model,
|
||||||
|
b.sparepart_merk,
|
||||||
|
b.sparepart_unit,
|
||||||
|
b.sparepart_item_type,
|
||||||
|
d.device_name
|
||||||
|
|
||||||
|
FROM notification_error_sparepart a
|
||||||
|
|
||||||
|
LEFT JOIN brand_sparepart c ON a.brand_sparepart_id = c.brand_sparepart_id
|
||||||
|
|
||||||
|
LEFT JOIN m_sparepart b ON c.sparepart_id = b.sparepart_id
|
||||||
|
|
||||||
|
LEFT JOIN m_device d on c.device_id = d.device_id
|
||||||
|
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
ORDER BY a.notification_error_sparepart_id ASC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total =
|
||||||
|
result?.recordset?.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const getNotificationErrorSparepartByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
b.sparepart_name,
|
||||||
|
b.sparepart_foto,
|
||||||
|
b.sparepart_stok,
|
||||||
|
b.sparepart_qty,
|
||||||
|
b.sparepart_description,
|
||||||
|
b.sparepart_model,
|
||||||
|
b.sparepart_merk,
|
||||||
|
b.sparepart_unit,
|
||||||
|
b.sparepart_item_type,
|
||||||
|
d.device_name
|
||||||
|
|
||||||
|
FROM notification_error_sparepart a
|
||||||
|
|
||||||
|
LEFT JOIN brand_sparepart c ON a.brand_sparepart_id = c.brand_sparepart_id
|
||||||
|
|
||||||
|
LEFT JOIN m_sparepart b ON c.sparepart_id = b.sparepart_id
|
||||||
|
|
||||||
|
LEFT JOIN m_device d on c.device_id = d.device_id
|
||||||
|
|
||||||
|
WHERE a.notification_error_sparepart_id = $1
|
||||||
|
AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset?.[0] || null;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const createNotificationErrorSparepartDb = async (store) => {
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert("notification_error_sparepart", store);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset?.[0]?.inserted_id;
|
||||||
|
|
||||||
|
return insertedId ? await getNotificationErrorSparepartByIdDb(insertedId) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateNotificationErrorSparepartDb = async (id, data) => {
|
||||||
|
const store = { ...data };
|
||||||
|
const whereData = { notification_error_sparepart_id: id };
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||||
|
"notification_error_sparepart",
|
||||||
|
store,
|
||||||
|
whereData
|
||||||
|
);
|
||||||
|
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return getNotificationErrorSparepartByIdDb(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Soft delete tag
|
||||||
|
const deleteNotificationErrorSparepartDb = async (id, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE notification_error_sparepart
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE notification_error_sparepart_id = $2 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getAllNotificationErrorSparepartDb,
|
||||||
|
getNotificationErrorSparepartByIdDb,
|
||||||
|
createNotificationErrorSparepartDb,
|
||||||
|
updateNotificationErrorSparepartDb,
|
||||||
|
deleteNotificationErrorSparepartDb,
|
||||||
|
};
|
||||||
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,
|
||||||
|
};
|
||||||
@@ -11,7 +11,7 @@ const getAllSubSectionsDb = async (searchParams = {}) => {
|
|||||||
|
|
||||||
// OR condition (pencarian bebas)
|
// OR condition (pencarian bebas)
|
||||||
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
["a.sub_section_code", "a.sub_section_name"],
|
["a.plant_sub_section_code", "a.plant_sub_section_name"],
|
||||||
searchParams.criteria,
|
searchParams.criteria,
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
@@ -21,8 +21,8 @@ const getAllSubSectionsDb = async (searchParams = {}) => {
|
|||||||
// AND condition (filter spesifik)
|
// AND condition (filter spesifik)
|
||||||
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
[
|
[
|
||||||
{ column: "a.sub_section_code", param: searchParams.code, type: "string" },
|
{ column: "a.plant_sub_section_code", param: searchParams.code, type: "string" },
|
||||||
{ column: "a.sub_section_name", param: searchParams.name, type: "string" },
|
{ column: "a.plant_sub_section_name", param: searchParams.name, type: "string" },
|
||||||
],
|
],
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
@@ -36,8 +36,8 @@ const getAllSubSectionsDb = async (searchParams = {}) => {
|
|||||||
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 ")}` : ""}
|
||||||
${whereOrConditions ? whereOrConditions : ""}
|
${whereOrConditions ? whereOrConditions : ""}
|
||||||
ORDER BY a.sub_section_id ASC
|
ORDER BY a.plant_sub_section_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
@@ -54,7 +54,7 @@ const getSubSectionByIdDb = async (id) => {
|
|||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT a.*
|
SELECT a.*
|
||||||
FROM m_plant_sub_section a
|
FROM m_plant_sub_section a
|
||||||
WHERE a.sub_section_id = $1 AND a.deleted_at IS NULL
|
WHERE a.plant_sub_section_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;
|
return result.recordset;
|
||||||
@@ -63,11 +63,11 @@ const getSubSectionByIdDb = async (id) => {
|
|||||||
// Create new sub section
|
// Create new sub section
|
||||||
const createSubSectionDb = async (data) => {
|
const createSubSectionDb = async (data) => {
|
||||||
// Generate kode otomatis
|
// Generate kode otomatis
|
||||||
const newCode = await pool.generateKode("SUB", "m_plant_sub_section", "sub_section_code");
|
const newCode = await pool.generateKode("SUB", "m_plant_sub_section", "plant_sub_section_code");
|
||||||
|
|
||||||
const store = {
|
const store = {
|
||||||
...data,
|
...data,
|
||||||
sub_section_code: newCode
|
plant_sub_section_code: newCode
|
||||||
};
|
};
|
||||||
|
|
||||||
const { query: queryText, values } = pool.buildDynamicInsert("m_plant_sub_section", store);
|
const { query: queryText, values } = pool.buildDynamicInsert("m_plant_sub_section", store);
|
||||||
@@ -80,7 +80,7 @@ const createSubSectionDb = async (data) => {
|
|||||||
// Update sub section
|
// Update sub section
|
||||||
const updateSubSectionDb = async (id, data) => {
|
const updateSubSectionDb = async (id, data) => {
|
||||||
const store = { ...data };
|
const store = { ...data };
|
||||||
const whereData = { sub_section_id: id };
|
const whereData = { plant_sub_section_id: id };
|
||||||
|
|
||||||
const { query: queryText, values } = pool.buildDynamicUpdate("m_plant_sub_section", store, whereData);
|
const { query: queryText, values } = pool.buildDynamicUpdate("m_plant_sub_section", store, whereData);
|
||||||
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
@@ -93,7 +93,7 @@ const deleteSubSectionDb = async (id, deletedBy) => {
|
|||||||
const queryText = `
|
const queryText = `
|
||||||
UPDATE m_plant_sub_section
|
UPDATE m_plant_sub_section
|
||||||
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
WHERE sub_section_id = $2 AND deleted_at IS NULL
|
WHERE plant_sub_section_id = $2 AND deleted_at IS NULL
|
||||||
`;
|
`;
|
||||||
await pool.query(queryText, [deletedBy, id]);
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
return true;
|
return true;
|
||||||
@@ -35,7 +35,7 @@ const getAllRolesDb = async (searchParams = {}) => {
|
|||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
ORDER BY a.role_id ASC
|
ORDER BY a.role_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
const pool = require("../config");
|
const pool = require("../config");
|
||||||
const { formattedDate } = require("../utils/date");
|
const { formattedDate } = require("../utils/date");
|
||||||
|
|
||||||
// Get all schedules
|
const normalizeClause = (clause) => {
|
||||||
|
if (!clause) return "";
|
||||||
|
return clause.replace(/^\s*(?:AND|WHERE)\s*/i, "").trim();
|
||||||
|
};
|
||||||
|
|
||||||
const getAllScheduleDb = async (searchParams = {}) => {
|
const getAllScheduleDb = async (searchParams = {}) => {
|
||||||
let queryParams = [];
|
let queryParams = [];
|
||||||
|
|
||||||
@@ -18,11 +22,51 @@ const getAllScheduleDb = async (searchParams = {}) => {
|
|||||||
if (whereParamOr) queryParams = whereParamOr;
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
[{ column: "a.schedule_date", param: searchParams.name, type: "date" }],
|
[
|
||||||
|
{
|
||||||
|
column: "a.schedule_date",
|
||||||
|
param: searchParams.name,
|
||||||
|
type: "date",
|
||||||
|
},
|
||||||
|
],
|
||||||
queryParams
|
queryParams
|
||||||
);
|
);
|
||||||
if (whereParamAnd) queryParams = whereParamAnd;
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const { whereDateCondition, whereDateParams } = pool.buildDateFilter(
|
||||||
|
"a.schedule_date",
|
||||||
|
searchParams.dateType,
|
||||||
|
searchParams.dateValue,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
if (whereDateParams) queryParams = whereDateParams;
|
||||||
|
|
||||||
|
const whereParts = [];
|
||||||
|
|
||||||
|
whereParts.push("a.deleted_at IS NULL");
|
||||||
|
|
||||||
|
if (Array.isArray(whereConditions) && whereConditions.length > 0) {
|
||||||
|
const joined = whereConditions.join(" AND ");
|
||||||
|
const norm = normalizeClause(joined);
|
||||||
|
if (norm) whereParts.push(norm);
|
||||||
|
} else if (typeof whereConditions === "string" && whereConditions.trim()) {
|
||||||
|
const norm = normalizeClause(whereConditions);
|
||||||
|
if (norm) whereParts.push(norm);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (whereOrConditions && String(whereOrConditions).trim()) {
|
||||||
|
const norm = normalizeClause(whereOrConditions);
|
||||||
|
if (norm) whereParts.push(norm);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (whereDateCondition && String(whereDateCondition).trim()) {
|
||||||
|
const norm = normalizeClause(whereDateCondition);
|
||||||
|
if (norm) whereParts.push(norm);
|
||||||
|
}
|
||||||
|
|
||||||
|
const whereClause =
|
||||||
|
whereParts.length > 0 ? `WHERE ${whereParts.join(" AND ")}` : "";
|
||||||
|
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT
|
SELECT
|
||||||
COUNT(*) OVER() AS total_data,
|
COUNT(*) OVER() AS total_data,
|
||||||
@@ -32,14 +76,13 @@ const getAllScheduleDb = async (searchParams = {}) => {
|
|||||||
b.end_time
|
b.end_time
|
||||||
FROM schedule a
|
FROM schedule a
|
||||||
LEFT JOIN m_shift b ON a.shift_id = b.shift_id
|
LEFT JOIN m_shift b ON a.shift_id = b.shift_id
|
||||||
WHERE a.deleted_at IS NULL
|
${whereClause}
|
||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
|
||||||
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
|
||||||
ORDER BY a.schedule_id ASC
|
ORDER BY a.schedule_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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)
|
||||||
@@ -48,6 +91,7 @@ const getAllScheduleDb = async (searchParams = {}) => {
|
|||||||
return { data: result.recordset, total };
|
return { data: result.recordset, total };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Get by ID
|
||||||
const getScheduleByIdDb = async (id) => {
|
const getScheduleByIdDb = async (id) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
SELECT
|
SELECT
|
||||||
@@ -63,8 +107,9 @@ const getScheduleByIdDb = async (id) => {
|
|||||||
return result.recordset?.[0] || null;
|
return result.recordset?.[0] || null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Insert (bisa multi hari)
|
||||||
const insertScheduleDb = async (store) => {
|
const insertScheduleDb = async (store) => {
|
||||||
const nextDays = Number(store.next_day ?? 0); // default 0 kalau tidak diisi
|
const nextDays = Number(store.next_day ?? 0);
|
||||||
const insertedRecords = [];
|
const insertedRecords = [];
|
||||||
|
|
||||||
for (let i = 0; i <= nextDays; i++) {
|
for (let i = 0; i <= nextDays; i++) {
|
||||||
@@ -72,11 +117,7 @@ const insertScheduleDb = async (store) => {
|
|||||||
nextDate.setDate(nextDate.getDate() + i);
|
nextDate.setDate(nextDate.getDate() + i);
|
||||||
|
|
||||||
const formatted = formattedDate(nextDate);
|
const formatted = formattedDate(nextDate);
|
||||||
|
const newStore = { ...store, schedule_date: formatted };
|
||||||
const newStore = {
|
|
||||||
...store,
|
|
||||||
schedule_date: formatted,
|
|
||||||
};
|
|
||||||
delete newStore.next_day;
|
delete newStore.next_day;
|
||||||
|
|
||||||
const { query: queryText, values } = pool.buildDynamicInsert("schedule", newStore);
|
const { query: queryText, values } = pool.buildDynamicInsert("schedule", newStore);
|
||||||
@@ -92,6 +133,7 @@ const insertScheduleDb = async (store) => {
|
|||||||
return insertedRecords;
|
return insertedRecords;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Update
|
||||||
const updateScheduleDb = async (id, data) => {
|
const updateScheduleDb = async (id, data) => {
|
||||||
const store = { ...data };
|
const store = { ...data };
|
||||||
const whereData = { schedule_id: id };
|
const whereData = { schedule_id: id };
|
||||||
@@ -106,7 +148,7 @@ const updateScheduleDb = async (id, data) => {
|
|||||||
return getScheduleByIdDb(id);
|
return getScheduleByIdDb(id);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Soft delete schedule
|
// Soft delete
|
||||||
const deleteScheduleDb = async (id, deletedBy) => {
|
const deleteScheduleDb = async (id, deletedBy) => {
|
||||||
const queryText = `
|
const queryText = `
|
||||||
UPDATE schedule
|
UPDATE schedule
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ const getAllShiftDb = async (searchParams = {}) => {
|
|||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
ORDER BY a.shift_id ASC
|
ORDER BY a.shift_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
|
|||||||
187
db/sparepart.db.js
Normal file
187
db/sparepart.db.js
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get all devices
|
||||||
|
const getAllSparepartDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
// Pagination
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
[
|
||||||
|
"a.sparepart_name",
|
||||||
|
"a.sparepart_code",
|
||||||
|
"a.sparepart_model",
|
||||||
|
"a.updated_at",
|
||||||
|
],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamOr ? whereParamOr : queryParams;
|
||||||
|
|
||||||
|
// Filter
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.sparepart_name", param: searchParams.code, type: "string" },
|
||||||
|
{
|
||||||
|
column: "a.sparepart_code",
|
||||||
|
param: searchParams.location,
|
||||||
|
type: "string",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
column: "b.sparepart_model",
|
||||||
|
param: searchParams.brand,
|
||||||
|
type: "string",
|
||||||
|
},
|
||||||
|
{ column: "a.updated_at", param: searchParams.status, type: "string" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
|
||||||
|
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*,
|
||||||
|
COALESCE(a.sparepart_code, '') + ' - ' + COALESCE(a.sparepart_name, '') AS sparepart_code_name
|
||||||
|
FROM m_sparepart a
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
${
|
||||||
|
whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""
|
||||||
|
}
|
||||||
|
${whereOrConditions ? whereOrConditions : ""}
|
||||||
|
ORDER BY a.sparepart_id ASC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
|
||||||
|
const total =
|
||||||
|
result?.recordset.length > 0
|
||||||
|
? parseInt(result.recordset[0].total_data, 10)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return { data: result.recordset, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const getSparepartByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
COALESCE(a.sparepart_code, '') + ' - ' + COALESCE(a.sparepart_name, '') AS sparepart_code_name
|
||||||
|
FROM m_sparepart a
|
||||||
|
WHERE a.sparepart_id = $1 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkSparepartNameExistsDb = async (sparePartName, excludeId = null) => {
|
||||||
|
let queryText = `
|
||||||
|
SELECT sparepart_id
|
||||||
|
FROM m_sparepart
|
||||||
|
WHERE sparepart_name = $1 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
let values = [sparePartName];
|
||||||
|
if (excludeId) {
|
||||||
|
queryText += ` AND sparepart_id != $2`;
|
||||||
|
values.push(excludeId);
|
||||||
|
}
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
return result.recordset.length > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createSparepartDb = async (data) => {
|
||||||
|
const newCode = await pool.generateKode(
|
||||||
|
"SPAREPART",
|
||||||
|
"m_sparepart",
|
||||||
|
"sparepart_code"
|
||||||
|
);
|
||||||
|
|
||||||
|
const store = {
|
||||||
|
...data,
|
||||||
|
sparepart_code: newCode,
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert(
|
||||||
|
"m_sparepart",
|
||||||
|
store
|
||||||
|
);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset[0]?.inserted_id;
|
||||||
|
return insertedId ? await getSparepartByIdDb(insertedId) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateSparepartDb = async (id, data) => {
|
||||||
|
const store = {
|
||||||
|
...data,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Kondisi WHERE
|
||||||
|
const whereData = {
|
||||||
|
sparepart_id: id,
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||||
|
"m_sparepart",
|
||||||
|
store,
|
||||||
|
whereData
|
||||||
|
);
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return getSparepartByIdDb(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteSparepartDb = async (id, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE m_sparepart
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE sparepart_id = $2 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get multiple spareparts by IDs
|
||||||
|
const getSparepartsByIdsDb = async (sparepartIds) => {
|
||||||
|
if (!sparepartIds || sparepartIds.length === 0) return [];
|
||||||
|
|
||||||
|
const placeholders = sparepartIds.map((_, index) => `$${index + 1}`).join(', ');
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
sparepart_id,
|
||||||
|
sparepart_name,
|
||||||
|
sparepart_code,
|
||||||
|
sparepart_description,
|
||||||
|
sparepart_model,
|
||||||
|
sparepart_foto,
|
||||||
|
sparepart_item_type,
|
||||||
|
sparepart_qty,
|
||||||
|
sparepart_unit,
|
||||||
|
sparepart_merk,
|
||||||
|
sparepart_stok,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
FROM m_sparepart
|
||||||
|
WHERE sparepart_id IN (${placeholders})
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, sparepartIds);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getAllSparepartDb,
|
||||||
|
getSparepartByIdDb,
|
||||||
|
getSparepartsByIdsDb,
|
||||||
|
checkSparepartNameExistsDb,
|
||||||
|
createSparepartDb,
|
||||||
|
updateSparepartDb,
|
||||||
|
deleteSparepartDb,
|
||||||
|
};
|
||||||
@@ -39,7 +39,7 @@ const getAllStatusDb = async (searchParams = {}) => {
|
|||||||
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
|
||||||
${whereOrConditions ? whereOrConditions : ''}
|
${whereOrConditions ? whereOrConditions : ''}
|
||||||
ORDER BY a.status_id ASC
|
ORDER BY a.status_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const getAllTagsDb = async (searchParams = {}) => {
|
|||||||
"a.data_type",
|
"a.data_type",
|
||||||
"a.unit",
|
"a.unit",
|
||||||
"b.device_name",
|
"b.device_name",
|
||||||
"c.sub_section_name",
|
"c.plant_sub_section_name",
|
||||||
],
|
],
|
||||||
searchParams.criteria,
|
searchParams.criteria,
|
||||||
queryParams
|
queryParams
|
||||||
@@ -38,7 +38,7 @@ const getAllTagsDb = async (searchParams = {}) => {
|
|||||||
type: "string",
|
type: "string",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
column: "c.sub_section_name",
|
column: "c.plant_sub_section_name",
|
||||||
param: searchParams.subsection,
|
param: searchParams.subsection,
|
||||||
type: "string",
|
type: "string",
|
||||||
},
|
},
|
||||||
@@ -54,15 +54,15 @@ const getAllTagsDb = async (searchParams = {}) => {
|
|||||||
a.*,
|
a.*,
|
||||||
b.device_name,
|
b.device_name,
|
||||||
b.device_code,
|
b.device_code,
|
||||||
c.sub_section_name
|
c.plant_sub_section_name
|
||||||
FROM m_tags a
|
FROM m_tags a
|
||||||
LEFT JOIN m_device b ON a.device_id = b.device_id
|
LEFT JOIN m_device b ON a.device_id = b.device_id
|
||||||
LEFT JOIN m_plant_sub_section c ON a.sub_section_id = c.sub_section_id
|
LEFT JOIN m_plant_sub_section c ON a.plant_sub_section_id = c.plant_sub_section_id
|
||||||
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 ")}` : ""}
|
||||||
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
ORDER BY a.tag_id ASC
|
ORDER BY a.tag_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
@@ -81,10 +81,10 @@ const getTagsByIdDb = async (id) => {
|
|||||||
a.*,
|
a.*,
|
||||||
b.device_name,
|
b.device_name,
|
||||||
b.device_code,
|
b.device_code,
|
||||||
c.sub_section_name
|
c.plant_sub_section_name
|
||||||
FROM m_tags a
|
FROM m_tags a
|
||||||
LEFT JOIN m_device b ON a.device_id = b.device_id
|
LEFT JOIN m_device b ON a.device_id = b.device_id
|
||||||
LEFT JOIN m_plant_sub_section c ON a.sub_section_id = c.sub_section_id
|
LEFT JOIN m_plant_sub_section c ON a.plant_sub_section_id = c.plant_sub_section_id
|
||||||
WHERE a.tag_id = $1 AND a.deleted_at IS NULL
|
WHERE a.tag_id = $1 AND a.deleted_at IS NULL
|
||||||
`;
|
`;
|
||||||
const result = await pool.query(queryText, [id]);
|
const result = await pool.query(queryText, [id]);
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ const getAllUnitsDb = async (searchParams = {}) => {
|
|||||||
${whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""}
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""}
|
||||||
${whereOrConditions ? whereOrConditions : ""}
|
${whereOrConditions ? whereOrConditions : ""}
|
||||||
ORDER BY a.unit_id ASC
|
ORDER BY a.unit_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ const getAllUsersDb = async (searchParams = {}) => {
|
|||||||
${whereConditions.length > 0 ? ` AND ${whereConditions.join(' AND ')}` : ''}
|
${whereConditions.length > 0 ? ` AND ${whereConditions.join(' AND ')}` : ''}
|
||||||
${whereOrConditions ? whereOrConditions : ''}
|
${whereOrConditions ? whereOrConditions : ''}
|
||||||
ORDER BY u.user_id ASC
|
ORDER BY u.user_id ASC
|
||||||
${searchParams.limit ? `OFFSET $2 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);
|
||||||
|
|||||||
170
db/user_schedule.db.js
Normal file
170
db/user_schedule.db.js
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
const getAllUserScheduleDb = async (searchParams = {}) => {
|
||||||
|
let queryParams = [];
|
||||||
|
|
||||||
|
// Handle pagination
|
||||||
|
if (searchParams.limit) {
|
||||||
|
const page = Number(searchParams.page ?? 1) - 1;
|
||||||
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
||||||
|
}
|
||||||
|
|
||||||
|
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
|
||||||
|
["a.user_id", "a.user_schedule_id", "a.schedule_id", "a.user_schedule_id", "a.shift_id"],
|
||||||
|
searchParams.criteria,
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
if (whereParamOr) queryParams = whereParamOr;
|
||||||
|
|
||||||
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||||
|
[
|
||||||
|
{ column: "a.user_id", param: searchParams.user_id, type: "int" },
|
||||||
|
{
|
||||||
|
column: "a.user_schedule_id",
|
||||||
|
param: searchParams.user_schedule_id,
|
||||||
|
type: "int",
|
||||||
|
},
|
||||||
|
{ column: "a.schedule_id", param: searchParams.schedule_id, type: "int" },
|
||||||
|
{ column: "a.shift_id", param: searchParams.shift_id, type: "int" },
|
||||||
|
],
|
||||||
|
queryParams
|
||||||
|
);
|
||||||
|
if (whereParamAnd) queryParams = whereParamAnd;
|
||||||
|
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
COUNT(*) OVER() AS total_data,
|
||||||
|
a.*,
|
||||||
|
c.shift_name,
|
||||||
|
c.start_time,
|
||||||
|
c.end_time,
|
||||||
|
d.user_fullname,
|
||||||
|
d.user_name,
|
||||||
|
d.user_phone
|
||||||
|
FROM user_schedule a
|
||||||
|
LEFT JOIN schedule b ON a.schedule_id = b.schedule_id
|
||||||
|
LEFT JOIN m_shift c ON a.shift_id = c.shift_id
|
||||||
|
LEFT JOIN m_users d ON a.user_id = d.user_id
|
||||||
|
WHERE a.deleted_at IS NULL
|
||||||
|
${
|
||||||
|
whereConditions.length > 0
|
||||||
|
? ` AND ${whereConditions.join(" AND ")}`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
${whereOrConditions ? ` ${whereOrConditions}` : ""}
|
||||||
|
ORDER BY c.shift_id ASC
|
||||||
|
${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.query(queryText, queryParams);
|
||||||
|
const records = result.recordset || [];
|
||||||
|
|
||||||
|
const total = records.length > 0 ? parseInt(records[0].total_data, 10) : 0;
|
||||||
|
|
||||||
|
const groupedShift = {};
|
||||||
|
records.forEach((row) => {
|
||||||
|
if (!groupedShift[row.shift_id]) {
|
||||||
|
groupedShift[row.shift_id] = {
|
||||||
|
shift: {
|
||||||
|
shift_id: row.shift_id,
|
||||||
|
shift_name: row.shift_name,
|
||||||
|
start_time: row.start_time,
|
||||||
|
end_time: row.end_time,
|
||||||
|
users: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
groupedShift[row.shift_id].shift.users.push({
|
||||||
|
user_schedule_id: row.user_schedule_id,
|
||||||
|
user_id: row.user_id,
|
||||||
|
user_fullname: row.user_fullname,
|
||||||
|
user_name: row.user_name,
|
||||||
|
user_phone: row.user_phone,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = Object.values(groupedShift);
|
||||||
|
|
||||||
|
return { data, total };
|
||||||
|
};
|
||||||
|
|
||||||
|
const getUserScheduleById = async (userId, shiftId) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.user_schedule_id,
|
||||||
|
a.user_id,
|
||||||
|
a.shift_id
|
||||||
|
FROM user_schedule a
|
||||||
|
WHERE a.user_id = $1
|
||||||
|
AND a.shift_id = $2
|
||||||
|
AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [userId, shiftId]);
|
||||||
|
return result.recordset || [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getUserScheduleByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT
|
||||||
|
a.*,
|
||||||
|
b.schedule_date,
|
||||||
|
c.shift_name,
|
||||||
|
c.start_time,
|
||||||
|
c.end_time,
|
||||||
|
d.user_fullname,
|
||||||
|
d.user_name,
|
||||||
|
d.user_phone
|
||||||
|
FROM user_schedule a
|
||||||
|
LEFT JOIN schedule b ON a.schedule_id = b.schedule_id
|
||||||
|
LEFT JOIN m_shift c ON a.shift_id = c.shift_id
|
||||||
|
LEFT JOIN m_users d ON a.user_id = d.user_id
|
||||||
|
WHERE a.user_schedule_id = $1 AND a.deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset?.[0] || null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const insertUserScheduleDb = async (store) => {
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert(
|
||||||
|
"user_schedule",
|
||||||
|
store
|
||||||
|
);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset?.[0]?.inserted_id;
|
||||||
|
|
||||||
|
return insertedId ? await getUserScheduleByIdDb(insertedId) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateUserScheduleDb = async (id, data) => {
|
||||||
|
const store = { ...data };
|
||||||
|
const whereData = { user_schedule_id: id };
|
||||||
|
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||||
|
"user_schedule",
|
||||||
|
store,
|
||||||
|
whereData
|
||||||
|
);
|
||||||
|
|
||||||
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||||
|
return getUserScheduleByIdDb(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteUserScheduleDb = async (id, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE user_schedule
|
||||||
|
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||||
|
WHERE user_schedule_id = $2 AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getAllUserScheduleDb,
|
||||||
|
getUserScheduleByIdDb,
|
||||||
|
insertUserScheduleDb,
|
||||||
|
updateUserScheduleDb,
|
||||||
|
deleteUserScheduleDb,
|
||||||
|
getUserScheduleById,
|
||||||
|
};
|
||||||
8
middleware/imagekit.js
Normal file
8
middleware/imagekit.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
const Imagekit = require("imagekit");
|
||||||
|
const { IMAGEKIT_URL_ENDPOINT, IMAGEKIT_PUBLIC_KEY, IMAGEKIT_PRIVATE_KEY } = process.env;
|
||||||
|
|
||||||
|
module.exports = new Imagekit({
|
||||||
|
publicKey: IMAGEKIT_PUBLIC_KEY,
|
||||||
|
privateKey: IMAGEKIT_PRIVATE_KEY,
|
||||||
|
urlEndpoint: IMAGEKIT_URL_ENDPOINT,
|
||||||
|
});
|
||||||
5
middleware/upload.js
Normal file
5
middleware/upload.js
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
const multer = require("multer");
|
||||||
|
|
||||||
|
const storage = multer.memoryStorage();
|
||||||
|
|
||||||
|
module.exports = multer({ storage });
|
||||||
69
middleware/uploads.js
Normal file
69
middleware/uploads.js
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
const multer = require("multer");
|
||||||
|
const path = require("path");
|
||||||
|
const { randomUUID } = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
|
||||||
|
// Fungsi untuk tentuin folder berdasarkan file type
|
||||||
|
function getFolderByType(mimetype) {
|
||||||
|
if (mimetype === "application/pdf") {
|
||||||
|
return "pdf";
|
||||||
|
} else if (mimetype.startsWith("image/")) {
|
||||||
|
return "images";
|
||||||
|
}
|
||||||
|
return "file";
|
||||||
|
}
|
||||||
|
|
||||||
|
const storage = multer.diskStorage({
|
||||||
|
destination: (req, file, cb) => {
|
||||||
|
const folderName = getFolderByType(file.mimetype);
|
||||||
|
const folderPath = path.join(__dirname, "../uploads", folderName);
|
||||||
|
|
||||||
|
fs.mkdirSync(folderPath, { recursive: true });
|
||||||
|
|
||||||
|
cb(null, folderPath);
|
||||||
|
},
|
||||||
|
filename: (req, file, cb) => {
|
||||||
|
const ext = path.extname(file.originalname);
|
||||||
|
const timestamp = Date.now();
|
||||||
|
|
||||||
|
const date = new Date(timestamp);
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||||
|
const day = String(date.getDate()).padStart(2, "0");
|
||||||
|
const hours = String(date.getHours()).padStart(2, "0");
|
||||||
|
const minutes = String(date.getMinutes()).padStart(2, "0");
|
||||||
|
const seconds = String(date.getSeconds()).padStart(2, "0");
|
||||||
|
|
||||||
|
const formattedDate = `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;
|
||||||
|
|
||||||
|
// Prefix berdasarkan tipe file
|
||||||
|
const prefix = file.mimetype === "application/pdf" ? "pdf" : "img";
|
||||||
|
const uniqueId = randomUUID().slice(0, 8);
|
||||||
|
|
||||||
|
cb(null, `${prefix}-${uniqueId}-${formattedDate}${ext}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const upload = multer({
|
||||||
|
storage,
|
||||||
|
fileFilter: (req, file, cb) => {
|
||||||
|
const allowedTypes = /jpeg|jpg|png|pdf/;
|
||||||
|
const allowedMimeTypes = /image\/(jpeg|jpg|png)|application\/pdf/;
|
||||||
|
|
||||||
|
const extname = allowedTypes.test(
|
||||||
|
path.extname(file.originalname).toLowerCase()
|
||||||
|
);
|
||||||
|
const mimetype = allowedMimeTypes.test(file.mimetype);
|
||||||
|
|
||||||
|
if (extname && mimetype) {
|
||||||
|
return cb(null, true);
|
||||||
|
} else {
|
||||||
|
cb(new Error("File type not allowed. Only PDF and Images (JPEG, JPG, PNG) are accepted."));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
limits: {
|
||||||
|
fileSize: 10 * 1024 * 1024, // 10MB max file size
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = upload;
|
||||||
@@ -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();
|
||||||
|
|||||||
@@ -19,10 +19,15 @@ function verifyAccessToken(req, res, next) {
|
|||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
const authHeader = req.headers.authorization;
|
const authHeader = req.headers.authorization;
|
||||||
if (!authHeader || !authHeader.startsWith('Bearer')) {
|
if (authHeader && authHeader.startsWith('Bearer')) {
|
||||||
throw new ErrorHandler(401, 'Access Token is required');
|
token = authHeader.split(' ')[1];
|
||||||
|
} else {
|
||||||
|
token = req.query.token;
|
||||||
}
|
}
|
||||||
token = authHeader.split(' ')[1];
|
}
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new ErrorHandler(401, 'Access Token is required');
|
||||||
}
|
}
|
||||||
|
|
||||||
const decoded = JWTService.verifyToken(token);
|
const decoded = JWTService.verifyToken(token);
|
||||||
|
|||||||
@@ -30,11 +30,13 @@
|
|||||||
"crypto": "^1.0.1",
|
"crypto": "^1.0.1",
|
||||||
"crypto-js": "^4.2.0",
|
"crypto-js": "^4.2.0",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
|
"exceljs": "^4.4.0",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"express-async-errors": "^3.1.1",
|
"express-async-errors": "^3.1.1",
|
||||||
"google-auth-library": "^8.7.0",
|
"google-auth-library": "^8.7.0",
|
||||||
"googleapis": "^112.0.0",
|
"googleapis": "^112.0.0",
|
||||||
"helmet": "^4.4.1",
|
"helmet": "^4.4.1",
|
||||||
|
"imagekit": "^6.0.0",
|
||||||
"joi": "^17.13.3",
|
"joi": "^17.13.3",
|
||||||
"jsonwebtoken": "^8.5.1",
|
"jsonwebtoken": "^8.5.1",
|
||||||
"moment": "^2.29.4",
|
"moment": "^2.29.4",
|
||||||
|
|||||||
@@ -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;
|
||||||
17
routes/brand.route.js
Normal file
17
routes/brand.route.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const BrandController = require('../controllers/brand.controller');
|
||||||
|
const verifyToken = require('../middleware/verifyToken');
|
||||||
|
const verifyAccess = require('../middleware/verifyAccess');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.route('/')
|
||||||
|
.get(verifyToken.verifyAccessToken, BrandController.getAll)
|
||||||
|
.post(verifyToken.verifyAccessToken, verifyAccess(), BrandController.create);
|
||||||
|
|
||||||
|
router.route('/:id')
|
||||||
|
.get(verifyToken.verifyAccessToken, BrandController.getById)
|
||||||
|
.put(verifyToken.verifyAccessToken, verifyAccess(), BrandController.update)
|
||||||
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), BrandController.delete);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
17
routes/contact.route.js
Normal file
17
routes/contact.route.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const ContactController = require('../controllers/contact.controller');
|
||||||
|
const verifyToken = require("../middleware/verifyToken")
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess")
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.route("/")
|
||||||
|
.get(verifyToken.verifyAccessToken, ContactController.getAll)
|
||||||
|
.post(verifyToken.verifyAccessToken, verifyAccess(), ContactController.create);
|
||||||
|
|
||||||
|
router.route("/:id")
|
||||||
|
.get(verifyToken.verifyAccessToken, ContactController.getById)
|
||||||
|
.put(verifyToken.verifyAccessToken, verifyAccess(), ContactController.update)
|
||||||
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), ContactController.delete);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
19
routes/error_code.route.js
Normal file
19
routes/error_code.route.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const ErrorCodeController = require('../controllers/error_code.controller');
|
||||||
|
const verifyToken = require('../middleware/verifyToken');
|
||||||
|
const verifyAccess = require('../middleware/verifyAccess');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.route('/brand/:brandId')
|
||||||
|
.get(verifyToken.verifyAccessToken, ErrorCodeController.getByBrandId)
|
||||||
|
.post(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.create);
|
||||||
|
|
||||||
|
router.route('/brand/:brandId/:errorCodeId')
|
||||||
|
.put(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.update)
|
||||||
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), ErrorCodeController.delete);
|
||||||
|
|
||||||
|
router.route('/:id')
|
||||||
|
.get(verifyToken.verifyAccessToken, ErrorCodeController.getById);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
17
routes/file_uploads.route.js
Normal file
17
routes/file_uploads.route.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
const router = require("express").Router();
|
||||||
|
const upload = require("../middleware/uploads");
|
||||||
|
const verifyToken = require("../middleware/verifyToken");
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess");
|
||||||
|
const {
|
||||||
|
uploadFile,
|
||||||
|
getFileByPath,
|
||||||
|
deleteFileByPath,
|
||||||
|
} = require("../controllers/file_uploads.controller");
|
||||||
|
|
||||||
|
router.post("/", verifyToken.verifyAccessToken, verifyAccess(), upload.single("file"), uploadFile);
|
||||||
|
|
||||||
|
router.route("/:folder/:filename")
|
||||||
|
.get(verifyToken.verifyAccessToken, getFileByPath)
|
||||||
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), deleteFileByPath);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
19
routes/history_value.route.js
Normal file
19
routes/history_value.route.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const HistoryValueController = require('../controllers/history_value.controller');
|
||||||
|
const verifyToken = require('../middleware/verifyToken');
|
||||||
|
const verifyAccess = require('../middleware/verifyAccess');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.route('/alarm')
|
||||||
|
.get(verifyToken.verifyAccessToken, HistoryValueController.getAllHistoryAlarm)
|
||||||
|
router.route('/event')
|
||||||
|
.get(verifyToken.verifyAccessToken, HistoryValueController.getAllHistoryEvent)
|
||||||
|
router.route('/value-report')
|
||||||
|
.get(verifyToken.verifyAccessToken, HistoryValueController.getHistoryValueReport)
|
||||||
|
router.route('/value-report-pivot')
|
||||||
|
.get(verifyToken.verifyAccessToken, HistoryValueController.getHistoryValueReportPivot)
|
||||||
|
router.route('/value-trending')
|
||||||
|
.get(verifyToken.verifyAccessToken, HistoryValueController.getHistoryValueTrendingPivot)
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -4,22 +4,43 @@ const users = require("./users.route");
|
|||||||
const device = require('./device.route');
|
const device = require('./device.route');
|
||||||
const roles = require('./roles.route');
|
const roles = require('./roles.route');
|
||||||
const tags = require("./tags.route");
|
const tags = require("./tags.route");
|
||||||
const subSection = require("./sub_section.route");
|
const brand = require("./brand.route");
|
||||||
|
const subSection = require("./plant_sub_section.route");
|
||||||
|
const fileUploads = require("./file_uploads.route");
|
||||||
const shift = require("./shift.route");
|
const shift = require("./shift.route");
|
||||||
const schedule = require("./schedule.route");
|
const schedule = require("./schedule.route");
|
||||||
const status = require("./status.route");
|
const status = require("./status.route");
|
||||||
const unit = require("./unit.route")
|
const unit = require("./unit.route")
|
||||||
|
const UserSchedule = require("./user_schedule.route")
|
||||||
|
const historyValue = require("./history_value.route")
|
||||||
|
const contact = require("./contact.route")
|
||||||
|
const notificationError = require("./notification_error.route")
|
||||||
|
const notificationErrorSparepart = require("./notification_error_sparepart.route")
|
||||||
|
const sparepart = require("./sparepart.route")
|
||||||
|
const notificationErrorLog = require("./notification_error_log.route")
|
||||||
|
const notificationErrorUser = require("./notification_error_user.route")
|
||||||
|
const errorCode = require("./error_code.route")
|
||||||
|
|
||||||
router.use("/auth", auth);
|
router.use("/auth", auth);
|
||||||
router.use("/user", users);
|
router.use("/user", users);
|
||||||
router.use("/device", device);
|
router.use("/device", device);
|
||||||
router.use("/roles", roles);
|
router.use("/roles", roles);
|
||||||
router.use("/tags", tags);
|
router.use("/tags", tags);
|
||||||
|
router.use("/brand", brand);
|
||||||
router.use("/plant-sub-section", subSection);
|
router.use("/plant-sub-section", subSection);
|
||||||
|
router.use("/file-uploads", fileUploads);
|
||||||
router.use("/shift", shift);
|
router.use("/shift", shift);
|
||||||
router.use("/schedule", schedule);
|
router.use("/schedule", schedule);
|
||||||
router.use("/status", status);
|
router.use("/status", status);
|
||||||
router.use("/unit", unit);
|
router.use("/unit", unit);
|
||||||
|
router.use("/user-schedule", UserSchedule)
|
||||||
|
router.use("/history", historyValue)
|
||||||
|
router.use("/contact", contact)
|
||||||
|
router.use("/notification", notificationError)
|
||||||
|
router.use("/notification-sparepart", notificationErrorSparepart)
|
||||||
|
router.use("/sparepart", sparepart)
|
||||||
|
router.use("/notification-log", notificationErrorLog)
|
||||||
|
router.use("/notification-user", notificationErrorUser)
|
||||||
|
router.use("/error-code", errorCode)
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
40
routes/notification_error.route.js
Normal file
40
routes/notification_error.route.js
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const NotificationErrorController = require("../controllers/notification_error.controller");
|
||||||
|
const verifyToken = require("../middleware/verifyToken");
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess");
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router
|
||||||
|
.route("/")
|
||||||
|
.get(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.getAll
|
||||||
|
);
|
||||||
|
|
||||||
|
router
|
||||||
|
.route("/")
|
||||||
|
.post(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.create
|
||||||
|
);
|
||||||
|
|
||||||
|
router
|
||||||
|
.route("/:id")
|
||||||
|
.get(verifyToken.verifyAccessToken, NotificationErrorController.getById)
|
||||||
|
.put(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.update
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
"/resend/:id",
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorController.resend
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
21
routes/notification_error_log.route.js
Normal file
21
routes/notification_error_log.route.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const NotificationErrorLogController = require('../controllers/notification_error_log.controller');
|
||||||
|
const verifyToken = require("../middleware/verifyToken")
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess")
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.route("/")
|
||||||
|
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getAll)
|
||||||
|
.post(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
NotificationErrorLogController.create);
|
||||||
|
|
||||||
|
router.route("/:id")
|
||||||
|
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getById);
|
||||||
|
|
||||||
|
router.route("/notification_error/:id")
|
||||||
|
.get(verifyToken.verifyAccessToken, NotificationErrorLogController.getByNotificationErrorId);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
23
routes/notification_error_sparepart.route.js
Normal file
23
routes/notification_error_sparepart.route.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const NotificationErrorSparepartController = require('../controllers/notification_error_sparepart.controller');
|
||||||
|
const verifyToken = require('../middleware/verifyToken');
|
||||||
|
const verifyAccess = require('../middleware/verifyAccess');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// ===========================
|
||||||
|
// Notification Erro rSparepart Routes
|
||||||
|
// ===========================
|
||||||
|
|
||||||
|
router
|
||||||
|
.route('/')
|
||||||
|
.get(verifyToken.verifyAccessToken, NotificationErrorSparepartController.getAll)
|
||||||
|
.post(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorSparepartController.create);
|
||||||
|
|
||||||
|
router
|
||||||
|
.route('/:id')
|
||||||
|
.get(verifyToken.verifyAccessToken, NotificationErrorSparepartController.getById)
|
||||||
|
.put(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorSparepartController.update)
|
||||||
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), NotificationErrorSparepartController.delete);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
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;
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const PlantSubSectionController = require('../controllers/sub_section.controller');
|
const PlantSubSectionController = require('../controllers/plant_sub_section.controller');
|
||||||
const verifyToken = require('../middleware/verifyToken');
|
const verifyToken = require('../middleware/verifyToken');
|
||||||
const verifyAccess = require('../middleware/verifyAccess');
|
const verifyAccess = require('../middleware/verifyAccess');
|
||||||
|
|
||||||
48
routes/sparepart.route.js
Normal file
48
routes/sparepart.route.js
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const SparepartController = require("../controllers/sparepart.controller");
|
||||||
|
const verifyToken = require("../middleware/verifyToken");
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess");
|
||||||
|
const upload = require("../middleware/upload");
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
"/export",
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
SparepartController.exportExcel
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
"/import",
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
upload.single("file"),
|
||||||
|
SparepartController.importExcel
|
||||||
|
);
|
||||||
|
|
||||||
|
router
|
||||||
|
.route("/")
|
||||||
|
.get(verifyToken.verifyAccessToken, SparepartController.getAll)
|
||||||
|
.post(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
upload.single("sparepart_foto"),
|
||||||
|
SparepartController.create
|
||||||
|
);
|
||||||
|
|
||||||
|
router
|
||||||
|
.route("/:id")
|
||||||
|
.get(verifyToken.verifyAccessToken, SparepartController.getById)
|
||||||
|
.put(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
upload.single("sparepart_foto"),
|
||||||
|
SparepartController.update
|
||||||
|
)
|
||||||
|
.delete(
|
||||||
|
verifyToken.verifyAccessToken,
|
||||||
|
verifyAccess(),
|
||||||
|
SparepartController.delete
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
17
routes/user_schedule.route.js
Normal file
17
routes/user_schedule.route.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const UserSchedulesController = require('../controllers/user_schedule.controller');
|
||||||
|
const verifyToken = require("../middleware/verifyToken")
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess")
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.route("/")
|
||||||
|
.get(verifyToken.verifyAccessToken, UserSchedulesController.getAll)
|
||||||
|
.post(verifyToken.verifyAccessToken, verifyAccess(), UserSchedulesController.create);
|
||||||
|
|
||||||
|
router.route("/:id")
|
||||||
|
.get(verifyToken.verifyAccessToken, UserSchedulesController.getById)
|
||||||
|
.put(verifyToken.verifyAccessToken, verifyAccess(), UserSchedulesController.update)
|
||||||
|
.delete(verifyToken.verifyAccessToken, verifyAccess(), UserSchedulesController.delete);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
122
services/brand.service.js
Normal file
122
services/brand.service.js
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
// Brand operations
|
||||||
|
const {
|
||||||
|
getAllBrandsDb,
|
||||||
|
getBrandByIdDb,
|
||||||
|
createBrandDb,
|
||||||
|
updateBrandDb,
|
||||||
|
deleteBrandDb,
|
||||||
|
checkBrandNameExistsDb,
|
||||||
|
} = require("../db/brand.db");
|
||||||
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
|
||||||
|
class BrandService {
|
||||||
|
// Get all brands
|
||||||
|
static async getAllBrands(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllBrandsDb(param);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...results,
|
||||||
|
data: results.data
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get brand by ID (without error codes)
|
||||||
|
static async getBrandById(id) {
|
||||||
|
try {
|
||||||
|
const brand = await getBrandByIdDb(id);
|
||||||
|
if (!brand) throw new ErrorHandler(404, "Brand not found");
|
||||||
|
|
||||||
|
return brand;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Create brand
|
||||||
|
static async createBrand(data) {
|
||||||
|
try {
|
||||||
|
if (data.brand_name) {
|
||||||
|
const brandExists = await checkBrandNameExistsDb(data.brand_name);
|
||||||
|
if (brandExists) {
|
||||||
|
throw new ErrorHandler(400, "Brand name already exists");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const brandData = {
|
||||||
|
brand_name: data.brand_name,
|
||||||
|
brand_type: data.brand_type,
|
||||||
|
brand_manufacture: data.brand_manufacture,
|
||||||
|
brand_model: data.brand_model,
|
||||||
|
is_active: data.is_active !== undefined ? data.is_active : true,
|
||||||
|
created_by: data.created_by,
|
||||||
|
};
|
||||||
|
|
||||||
|
const createdBrand = await createBrandDb(brandData);
|
||||||
|
if (!createdBrand) {
|
||||||
|
throw new ErrorHandler(500, "Failed to create brand");
|
||||||
|
}
|
||||||
|
|
||||||
|
return createdBrand;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete brand by ID
|
||||||
|
static async deleteBrand(id, userId) {
|
||||||
|
try {
|
||||||
|
const brandExist = await getBrandByIdDb(id);
|
||||||
|
|
||||||
|
if (!brandExist) {
|
||||||
|
throw new ErrorHandler(404, "Brand not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deleteBrandDb(id, userId);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Update brand
|
||||||
|
static async updateBrand(id, data) {
|
||||||
|
try {
|
||||||
|
const existingBrand = await getBrandByIdDb(id);
|
||||||
|
if (!existingBrand) throw new ErrorHandler(404, "Brand not found");
|
||||||
|
|
||||||
|
if (data.brand_name && data.brand_name !== existingBrand.brand_name) {
|
||||||
|
const brandExists = await checkBrandNameExistsDb(data.brand_name, id);
|
||||||
|
if (brandExists) {
|
||||||
|
throw new ErrorHandler(400, "Brand name already exists");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const brandData = {
|
||||||
|
brand_name: data.brand_name || existingBrand.brand_name,
|
||||||
|
brand_type: data.brand_type !== undefined ? data.brand_type : existingBrand.brand_type,
|
||||||
|
brand_manufacture: data.brand_manufacture !== undefined ? data.brand_manufacture : existingBrand.brand_manufacture,
|
||||||
|
brand_model: data.brand_model !== undefined ? data.brand_model : existingBrand.brand_model,
|
||||||
|
is_active: data.is_active !== undefined ? data.is_active : existingBrand.is_active,
|
||||||
|
updated_by: data.updated_by,
|
||||||
|
};
|
||||||
|
|
||||||
|
const updatedBrand = await updateBrandDb(existingBrand.brand_name, brandData);
|
||||||
|
if (!updatedBrand) {
|
||||||
|
throw new ErrorHandler(500, "Failed to update brand");
|
||||||
|
}
|
||||||
|
|
||||||
|
return updatedBrand;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = BrandService;
|
||||||
88
services/contact.service.js
Normal file
88
services/contact.service.js
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
const {
|
||||||
|
getAllContactDb,
|
||||||
|
getContactByIdDb,
|
||||||
|
createContactDb,
|
||||||
|
updateContactDb,
|
||||||
|
deleteContactDb
|
||||||
|
} = require('../db/contact.db');
|
||||||
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
|
class ContactService {
|
||||||
|
// Get all Contact
|
||||||
|
static async getAllContact(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllContactDb(param);
|
||||||
|
|
||||||
|
results.data.map(element => {
|
||||||
|
});
|
||||||
|
|
||||||
|
return results
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get Contact by ID
|
||||||
|
static async getContactById(id) {
|
||||||
|
try {
|
||||||
|
const result = await getContactByIdDb(id);
|
||||||
|
|
||||||
|
if (result.length < 1) throw new ErrorHandler(404, 'Contact not found');
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create Contact
|
||||||
|
static async createContact(data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
const result = await createContactDb(data);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update Contact
|
||||||
|
static async updateContact(id, data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
const dataExist = await getContactByIdDb(id);
|
||||||
|
|
||||||
|
if (dataExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Contact not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await updateContactDb(id, data);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete Contact
|
||||||
|
static async deleteContact(id, userId) {
|
||||||
|
try {
|
||||||
|
const dataExist = await getContactByIdDb(id);
|
||||||
|
|
||||||
|
if (dataExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Contact not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deleteContactDb(id, userId);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ContactService;
|
||||||
265
services/error_code.service.js
Normal file
265
services/error_code.service.js
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
const {
|
||||||
|
getErrorCodesByBrandIdDb,
|
||||||
|
getErrorCodeByIdDb,
|
||||||
|
getErrorCodeByBrandAndCodeDb,
|
||||||
|
createErrorCodeDb,
|
||||||
|
updateErrorCodeDb,
|
||||||
|
deleteErrorCodeDb,
|
||||||
|
getAllErrorCodesDb,
|
||||||
|
} = require("../db/brand_code.db");
|
||||||
|
|
||||||
|
const {
|
||||||
|
getSolutionsByErrorCodeIdDb,
|
||||||
|
createSolutionDb,
|
||||||
|
updateSolutionDb,
|
||||||
|
deleteSolutionDb,
|
||||||
|
} = require("../db/brand_code_solution.db");
|
||||||
|
|
||||||
|
const {
|
||||||
|
getSparepartsByErrorCodeIdDb,
|
||||||
|
insertMultipleErrorCodeSparepartsDb,
|
||||||
|
updateErrorCodeSparepartsDb,
|
||||||
|
} = require("../db/brand_sparepart.db");
|
||||||
|
|
||||||
|
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
|
||||||
|
|
||||||
|
class ErrorCodeService {
|
||||||
|
static async getAllErrorCodes(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllErrorCodesDb(param);
|
||||||
|
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get error code by ID with complete data
|
||||||
|
static async getErrorCodeById(id) {
|
||||||
|
try {
|
||||||
|
const errorCode = await getErrorCodeByIdDb(id);
|
||||||
|
if (!errorCode) throw new ErrorHandler(404, "Error code not found");
|
||||||
|
|
||||||
|
const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);
|
||||||
|
const spareparts = await getSparepartsByErrorCodeIdDb(errorCode.error_code_id);
|
||||||
|
|
||||||
|
const solutionsWithFiles = await Promise.all(
|
||||||
|
solutions.map(async (solution) => {
|
||||||
|
let fileData = null;
|
||||||
|
|
||||||
|
if (solution.path_solution && solution.type_solution !== "text") {
|
||||||
|
fileData = await getFileUploadByPathDb(solution.path_solution);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...solution,
|
||||||
|
file_upload_name: fileData?.file_upload_name || null,
|
||||||
|
path_document: fileData?.path_document || null,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...errorCode,
|
||||||
|
solution: solutionsWithFiles,
|
||||||
|
spareparts: spareparts,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get error codes by brand ID
|
||||||
|
static async getErrorCodesByBrandId(brandId, queryParams = {}) {
|
||||||
|
try {
|
||||||
|
const results = await getErrorCodesByBrandIdDb(brandId, queryParams);
|
||||||
|
|
||||||
|
if (results.data && results.total !== undefined) {
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorCodesWithDetails = await Promise.all(
|
||||||
|
results.map(async (errorCode) => {
|
||||||
|
const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);
|
||||||
|
const spareparts = await getSparepartsByErrorCodeIdDb(errorCode.error_code_id);
|
||||||
|
|
||||||
|
const solutionsWithFiles = await Promise.all(
|
||||||
|
solutions.map(async (solution) => {
|
||||||
|
let fileData = null;
|
||||||
|
|
||||||
|
if (solution.path_solution && solution.type_solution !== "text") {
|
||||||
|
fileData = await getFileUploadByPathDb(solution.path_solution);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...solution,
|
||||||
|
file_upload_name: fileData?.file_upload_name || null,
|
||||||
|
path_document: fileData?.path_document || null,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...errorCode,
|
||||||
|
solution: solutionsWithFiles,
|
||||||
|
spareparts: spareparts,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return errorCodesWithDetails;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create error code with solutions and spareparts
|
||||||
|
static async createErrorCodeWithFullData(brandId, data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== "object") data = {};
|
||||||
|
|
||||||
|
const errorId = await createErrorCodeDb(brandId, {
|
||||||
|
error_code: data.error_code,
|
||||||
|
error_code_name: data.error_code_name,
|
||||||
|
error_code_description: data.error_code_description,
|
||||||
|
error_code_color: data.error_code_color,
|
||||||
|
path_icon: data.path_icon,
|
||||||
|
is_active: data.is_active,
|
||||||
|
created_by: data.created_by,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!errorId) {
|
||||||
|
throw new Error("Failed to create error code");
|
||||||
|
}
|
||||||
|
if (data.spareparts && Array.isArray(data.spareparts)) {
|
||||||
|
await insertMultipleErrorCodeSparepartsDb(errorId, data.spareparts, data.created_by);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.solution && Array.isArray(data.solution)) {
|
||||||
|
for (const solutionData of data.solution) {
|
||||||
|
await createSolutionDb(errorId, {
|
||||||
|
solution_name: solutionData.solution_name,
|
||||||
|
type_solution: solutionData.type_solution,
|
||||||
|
text_solution: solutionData.text_solution || null,
|
||||||
|
path_solution: solutionData.path_solution || null,
|
||||||
|
is_active: solutionData.is_active,
|
||||||
|
created_by: data.created_by,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const createdErrorCode = await this.getErrorCodeById(errorId);
|
||||||
|
return createdErrorCode;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(500, `Create error code failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update error code with solutions and spareparts
|
||||||
|
static async updateErrorCodeWithFullData(brandId, errorCodeId, data) {
|
||||||
|
try {
|
||||||
|
const existingErrorCode = await getErrorCodeByIdDb(errorCodeId);
|
||||||
|
if (!existingErrorCode) throw new ErrorHandler(404, "Error code not found");
|
||||||
|
|
||||||
|
// Verify the error code belongs to the specified brand
|
||||||
|
if (existingErrorCode.brand_id !== parseInt(brandId)) {
|
||||||
|
throw new ErrorHandler(403, "Error code does not belong to specified brand");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there are any error code fields to update
|
||||||
|
const hasMainFieldUpdate =
|
||||||
|
data.error_code !== undefined ||
|
||||||
|
data.error_code_name !== undefined ||
|
||||||
|
data.error_code_description !== undefined ||
|
||||||
|
data.error_code_color !== undefined ||
|
||||||
|
data.path_icon !== undefined ||
|
||||||
|
data.is_active !== undefined;
|
||||||
|
|
||||||
|
if (hasMainFieldUpdate) {
|
||||||
|
await updateErrorCodeDb(brandId, existingErrorCode.error_code, {
|
||||||
|
error_code: data.error_code,
|
||||||
|
error_code_name: data.error_code_name,
|
||||||
|
error_code_description: data.error_code_description,
|
||||||
|
error_code_color: data.error_code_color,
|
||||||
|
path_icon: data.path_icon,
|
||||||
|
is_active: data.is_active,
|
||||||
|
updated_by: data.updated_by,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.spareparts && Array.isArray(data.spareparts)) {
|
||||||
|
await updateErrorCodeSparepartsDb(existingErrorCode.error_code_id, data.spareparts, data.updated_by);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.solution && Array.isArray(data.solution)) {
|
||||||
|
const existingSolutions = await getSolutionsByErrorCodeIdDb(existingErrorCode.error_code_id);
|
||||||
|
const incomingSolutionNames = data.solution.map((s) => s.solution_name);
|
||||||
|
|
||||||
|
for (const solutionData of data.solution) {
|
||||||
|
const existingSolution = existingSolutions.find(
|
||||||
|
(s) => s.solution_name === solutionData.solution_name
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingSolution) {
|
||||||
|
await updateSolutionDb(
|
||||||
|
existingSolution.brand_code_solution_id,
|
||||||
|
{
|
||||||
|
solution_name: solutionData.solution_name,
|
||||||
|
type_solution: solutionData.type_solution,
|
||||||
|
text_solution: solutionData.text_solution || null,
|
||||||
|
path_solution: solutionData.path_solution || null,
|
||||||
|
is_active: solutionData.is_active,
|
||||||
|
updated_by: data.updated_by,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await createSolutionDb(existingErrorCode.error_code_id, {
|
||||||
|
solution_name: solutionData.solution_name,
|
||||||
|
type_solution: solutionData.type_solution,
|
||||||
|
text_solution: solutionData.text_solution || null,
|
||||||
|
path_solution: solutionData.path_solution || null,
|
||||||
|
is_active: solutionData.is_active,
|
||||||
|
created_by: data.updated_by,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const existingSolution of existingSolutions) {
|
||||||
|
if (!incomingSolutionNames.includes(existingSolution.solution_name)) {
|
||||||
|
await deleteSolutionDb(existingSolution.brand_code_solution_id, data.updated_by);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedErrorCode = await this.getErrorCodeById(existingErrorCode.error_code_id);
|
||||||
|
return updatedErrorCode;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(500, `Update error code failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete error code
|
||||||
|
static async deleteErrorCode(brandId, errorCodeId, deletedBy) {
|
||||||
|
try {
|
||||||
|
const errorCodeExist = await getErrorCodeByIdDb(errorCodeId);
|
||||||
|
|
||||||
|
if (!errorCodeExist) {
|
||||||
|
throw new ErrorHandler(404, "Error code not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the error code belongs to the specified brand
|
||||||
|
if (errorCodeExist.brand_id !== parseInt(brandId)) {
|
||||||
|
throw new ErrorHandler(403, "Error code does not belong to specified brand");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deleteErrorCodeDb(brandId, errorCodeExist.error_code, deletedBy);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ErrorCodeService;
|
||||||
141
services/history_value.service.js
Normal file
141
services/history_value.service.js
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
const {
|
||||||
|
getHistoryAlarmDb,
|
||||||
|
getHistoryEventDb,
|
||||||
|
checkTableNamedDb,
|
||||||
|
getHistoryValueReportDb,
|
||||||
|
getHistoryValueReportPivotDb,
|
||||||
|
getHistoryValueTrendingPivotDb
|
||||||
|
} = require('../db/history_value.db');
|
||||||
|
const { getSubSectionByIdDb } = require('../db/plant_sub_section.db');
|
||||||
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
|
class HistoryValue {
|
||||||
|
|
||||||
|
static async getAllHistoryAlarm(param) {
|
||||||
|
try {
|
||||||
|
const results = await getHistoryAlarmDb(param);
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message || 'Error fetching alarm history');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getAllHistoryEvent(param) {
|
||||||
|
try {
|
||||||
|
const results = await getHistoryEventDb(param);
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message || 'Error fetching event history');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getHistoryValueReport(param) {
|
||||||
|
try {
|
||||||
|
if (!param.plant_sub_section_id) {
|
||||||
|
throw new ErrorHandler(400, 'plant_sub_section_id is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
|
||||||
|
|
||||||
|
if (!plantSubSection || plantSubSection.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Plant sub section not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableNameValue = plantSubSection[0]?.table_name_value;
|
||||||
|
|
||||||
|
if (!tableNameValue) {
|
||||||
|
throw new ErrorHandler(404, 'Table name not configured for this sub section');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableExist = await checkTableNamedDb(tableNameValue);
|
||||||
|
|
||||||
|
if (!tableExist || tableExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await getHistoryValueReportDb(tableExist[0].TABLE_NAME, param);
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(
|
||||||
|
error.statusCode || 500,
|
||||||
|
error.message || 'Error fetching history value report'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getHistoryValueReportPivot(param) {
|
||||||
|
try {
|
||||||
|
if (!param.plant_sub_section_id) {
|
||||||
|
throw new ErrorHandler(400, 'plant_sub_section_id is required');
|
||||||
|
}
|
||||||
|
if (!param.from || !param.to) {
|
||||||
|
throw new ErrorHandler(400, 'from and to date parameters are required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
|
||||||
|
|
||||||
|
if (!plantSubSection || plantSubSection.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Plant sub section not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableNameValue = plantSubSection[0]?.table_name_value;
|
||||||
|
|
||||||
|
if (!tableNameValue) {
|
||||||
|
throw new ErrorHandler(404, 'Table name not configured for this sub section');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableExist = await checkTableNamedDb(tableNameValue);
|
||||||
|
|
||||||
|
if (!tableExist || tableExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await getHistoryValueReportPivotDb(tableExist[0].TABLE_NAME, param);
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(
|
||||||
|
error.statusCode || 500,
|
||||||
|
error.message || 'Error fetching history value report pivot'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getHistoryValueTrendingPivot(param) {
|
||||||
|
try {
|
||||||
|
if (!param.plant_sub_section_id) {
|
||||||
|
throw new ErrorHandler(400, 'plant_sub_section_id is required');
|
||||||
|
}
|
||||||
|
if (!param.from || !param.to) {
|
||||||
|
throw new ErrorHandler(400, 'from and to date parameters are required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const plantSubSection = await getSubSectionByIdDb(param.plant_sub_section_id);
|
||||||
|
|
||||||
|
if (!plantSubSection || plantSubSection.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Plant sub section not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableNameValue = plantSubSection[0]?.table_name_value;
|
||||||
|
|
||||||
|
if (!tableNameValue) {
|
||||||
|
throw new ErrorHandler(404, 'Table name not configured for this sub section');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableExist = await checkTableNamedDb(tableNameValue);
|
||||||
|
|
||||||
|
if (!tableExist || tableExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, `Value table '${tableNameValue}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await getHistoryValueTrendingPivotDb(tableExist[0].TABLE_NAME, param);
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(
|
||||||
|
error.statusCode || 500,
|
||||||
|
error.message || 'Error fetching history value trending pivot'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = HistoryValue;
|
||||||
266
services/notification_error.service.js
Normal file
266
services/notification_error.service.js
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
// services/notification_error.service.js
|
||||||
|
const {
|
||||||
|
getAllNotificationDb,
|
||||||
|
getNotificationByIdDb,
|
||||||
|
InsertNotificationErrorDb,
|
||||||
|
getUsersNotificationErrorDb,
|
||||||
|
updateNotificationErrorDb,
|
||||||
|
} = require("../db/notification_error.db");
|
||||||
|
|
||||||
|
const { getErrorCodeByIdDb } = require("../db/brand_code.db");
|
||||||
|
|
||||||
|
const { getSolutionsByErrorCodeIdDb } = require("../db/brand_code_solution.db");
|
||||||
|
|
||||||
|
const {
|
||||||
|
getAllNotificationErrorLogDb,
|
||||||
|
getNotificationErrorLogByNotificationErrorIdDb,
|
||||||
|
} = require("../db/notification_error_log.db");
|
||||||
|
|
||||||
|
const { getSparepartsByErrorCodeIdDb } = require("../db/brand_sparepart.db");
|
||||||
|
|
||||||
|
const {
|
||||||
|
getNotificationErrorByIdDb,
|
||||||
|
} = require("../db/notification_error_user.db");
|
||||||
|
|
||||||
|
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
|
||||||
|
|
||||||
|
const {
|
||||||
|
generateTokenRedirect,
|
||||||
|
shortUrltiny,
|
||||||
|
sendNotifikasi,
|
||||||
|
} = require("../db/notification_wa.db");
|
||||||
|
|
||||||
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
|
||||||
|
class NotificationService {
|
||||||
|
static async getAllNotification(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllNotificationDb(param);
|
||||||
|
|
||||||
|
if (results && Array.isArray(results.data)) {
|
||||||
|
results.data = await Promise.all(
|
||||||
|
results.data.map(async (notification) => {
|
||||||
|
const usersNotification =
|
||||||
|
(await getUsersNotificationErrorDb(
|
||||||
|
notification.notification_error_id
|
||||||
|
)) || [];
|
||||||
|
return {
|
||||||
|
...notification,
|
||||||
|
users: usersNotification,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async createNotificationError(data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== "object") data = {};
|
||||||
|
|
||||||
|
const result = await InsertNotificationErrorDb(data);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getNotificationById(id) {
|
||||||
|
try {
|
||||||
|
const notification = await getNotificationByIdDb(id);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!notification ||
|
||||||
|
(Array.isArray(notification) && notification.length < 1)
|
||||||
|
) {
|
||||||
|
throw new ErrorHandler(404, "Notification not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
const usersNotification = (await getUsersNotificationErrorDb(id)) || [];
|
||||||
|
|
||||||
|
// Get error code details if error_code_id exists
|
||||||
|
if (notification.error_code_id) {
|
||||||
|
const errorCode = await getErrorCodeByIdDb(notification.error_code_id);
|
||||||
|
|
||||||
|
if (errorCode) {
|
||||||
|
// Get solutions for this error code
|
||||||
|
const solutions =
|
||||||
|
(await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || [];
|
||||||
|
|
||||||
|
const spareparts =
|
||||||
|
(await getSparepartsByErrorCodeIdDb(errorCode.error_code_id)) || [];
|
||||||
|
|
||||||
|
const solutionsWithDetails = await Promise.all(
|
||||||
|
solutions.map(async (solution) => {
|
||||||
|
let fileData = null;
|
||||||
|
if (
|
||||||
|
solution.path_solution &&
|
||||||
|
solution.type_solution &&
|
||||||
|
solution.type_solution !== "text"
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
fileData = await getFileUploadByPathDb(
|
||||||
|
solution.path_solution
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
fileData = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...solution,
|
||||||
|
file_upload_name: fileData?.file_upload_name || null,
|
||||||
|
path_document: fileData?.path_document || null,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
notification.error_code = {
|
||||||
|
...errorCode,
|
||||||
|
solution: solutionsWithDetails,
|
||||||
|
spareparts: spareparts,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get activity logs for this notification
|
||||||
|
const notificationLogs =
|
||||||
|
(await getNotificationErrorLogByNotificationErrorIdDb(id)) || [];
|
||||||
|
|
||||||
|
notification.users = usersNotification;
|
||||||
|
|
||||||
|
notification.activity_logs = notificationLogs;
|
||||||
|
|
||||||
|
return notification;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async updateNotificationError(notification_error_id, data) {
|
||||||
|
try {
|
||||||
|
const dataExist = await getNotificationErrorByIdDb(notification_error_id);
|
||||||
|
|
||||||
|
if (!dataExist || (Array.isArray(dataExist) && dataExist.length < 1)) {
|
||||||
|
throw new ErrorHandler(404, "Notification Error User not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
const notification = Array.isArray(dataExist) ? dataExist[0] : dataExist;
|
||||||
|
|
||||||
|
if (notification.is_read === true) {
|
||||||
|
return { success: true, message: "Notification has already been read" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!notification.is_read) {
|
||||||
|
const updateStatus = await updateNotificationErrorDb(
|
||||||
|
notification_error_id,
|
||||||
|
{ is_read: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!updateStatus) {
|
||||||
|
throw new ErrorHandler(500, "Failed to update notification");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, message: "Notification marked as read" };
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async resendNotification(id) {
|
||||||
|
const deviceNotification = await getNotificationByIdDb(id);
|
||||||
|
if (!deviceNotification) throw new ErrorHandler(404, "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;
|
||||||
111
services/notification_error_log.service.js
Normal file
111
services/notification_error_log.service.js
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
const {
|
||||||
|
getAllNotificationErrorLogDb,
|
||||||
|
getNotificationErrorLogByIdDb,
|
||||||
|
getNotificationErrorLogByNotificationErrorIdDb,
|
||||||
|
createNotificationErrorLogDb,
|
||||||
|
updateNotificationErrorLogDb,
|
||||||
|
deleteNotificationErrorLogDb
|
||||||
|
} = require('../db/notification_error_log.db');
|
||||||
|
|
||||||
|
const { getUserByIdDb } = require('../db/user.db');
|
||||||
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
|
class NotificationErrorLogService {
|
||||||
|
// Get all Notification Error Logs
|
||||||
|
static async getAllNotificationErrorLog() {
|
||||||
|
try {
|
||||||
|
const results = await getAllNotificationErrorLogDb();
|
||||||
|
|
||||||
|
results.data.map(element => {
|
||||||
|
});
|
||||||
|
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get Notification Error Log by ID
|
||||||
|
static async getNotificationErrorLogById(id) {
|
||||||
|
try {
|
||||||
|
const result = await getNotificationErrorLogByIdDb(id);
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
throw new ErrorHandler(404, 'Notification Error Log not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create Notification Error Log
|
||||||
|
static async createNotificationErrorLog(data, userId) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
let createdBy = null;
|
||||||
|
let contactPhone = data.contact_phone || null;
|
||||||
|
|
||||||
|
if (userId) {
|
||||||
|
try {
|
||||||
|
const user = await getUserByIdDb(userId);
|
||||||
|
|
||||||
|
if (user && user.user_id) {
|
||||||
|
createdBy = Number(user.user_id);
|
||||||
|
} else {
|
||||||
|
createdBy = null;
|
||||||
|
contactPhone = userId;
|
||||||
|
}
|
||||||
|
} catch (dbError) {
|
||||||
|
createdBy = null;
|
||||||
|
contactPhone = userId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const store = {
|
||||||
|
notification_error_id: data.notification_error_id,
|
||||||
|
contact_phone: contactPhone,
|
||||||
|
notification_error_log_description: data.notification_error_log_description,
|
||||||
|
created_by: createdBy
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await createNotificationErrorLogDb(store);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get Notification Error Log by notification_error_id
|
||||||
|
static async getNotificationErrorLogByNotificationErrorId(notificationErrorId) {
|
||||||
|
try {
|
||||||
|
const results = await getNotificationErrorLogByNotificationErrorIdDb(notificationErrorId);
|
||||||
|
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete Notification Error Log
|
||||||
|
static async deleteNotificationErrorLog(id, userId) {
|
||||||
|
try {
|
||||||
|
const dataExist = await getNotificationErrorLogByIdDb(id);
|
||||||
|
|
||||||
|
if (!dataExist) {
|
||||||
|
throw new ErrorHandler(404, 'Notification Error Log not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deleteNotificationErrorLogDb(id, userId);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationErrorLogService;
|
||||||
76
services/notification_error_sparepart.service.js
Normal file
76
services/notification_error_sparepart.service.js
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
const {
|
||||||
|
getAllNotificationErrorSparepartDb,
|
||||||
|
getNotificationErrorSparepartByIdDb,
|
||||||
|
createNotificationErrorSparepartDb,
|
||||||
|
updateNotificationErrorSparepartDb,
|
||||||
|
deleteNotificationErrorSparepartDb,
|
||||||
|
} = require("../db/notification_error_sparepart.db");
|
||||||
|
|
||||||
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
|
||||||
|
class NotificationErrorSparepartService {
|
||||||
|
|
||||||
|
static async getAll(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllNotificationErrorSparepartDb(param);
|
||||||
|
|
||||||
|
results.data.map(element => {
|
||||||
|
});
|
||||||
|
|
||||||
|
return results
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getById(id) {
|
||||||
|
const result = await getNotificationErrorSparepartByIdDb(id);
|
||||||
|
|
||||||
|
if (result.length < 1)
|
||||||
|
throw new ErrorHandler(404, "Notification Error Sparepart not found");
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async create(data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
const result = await createNotificationErrorSparepartDb(data);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async update(id, data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
const dataExist = await getNotificationErrorSparepartByIdDb(id);
|
||||||
|
|
||||||
|
if (dataExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'Notification Error Sparepart not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await updateNotificationErrorSparepartDb(id, data);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async delete(id) {
|
||||||
|
|
||||||
|
const exist = await getNotificationErrorSparepartByIdDb(id);
|
||||||
|
|
||||||
|
if (exist.length < 1)
|
||||||
|
throw new ErrorHandler(404, "Notification Error Sparepart not found");
|
||||||
|
|
||||||
|
return await deleteNotificationErrorSparepartDb(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationErrorSparepartService;
|
||||||
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;
|
||||||
127
services/notifikasi-wa.service.js
Normal file
127
services/notifikasi-wa.service.js
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
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.contact_phone,
|
||||||
|
dataUser.contact_name,
|
||||||
|
resultNotificationError.notification_error_id
|
||||||
|
);
|
||||||
|
|
||||||
|
const encodedToken = encodeURIComponent(tokenRedirect);
|
||||||
|
|
||||||
|
const shortUrl = await shortUrltiny(encodedToken);
|
||||||
|
|
||||||
|
const bodyMessage =
|
||||||
|
`Hai ${dataUser.contact_name || "-"}\n` +
|
||||||
|
`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
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log("resultSend: ", resultSend);
|
||||||
|
|
||||||
|
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();
|
||||||
@@ -4,7 +4,7 @@ const {
|
|||||||
createSubSectionDb,
|
createSubSectionDb,
|
||||||
updateSubSectionDb,
|
updateSubSectionDb,
|
||||||
deleteSubSectionDb
|
deleteSubSectionDb
|
||||||
} = require('../db/sub_section.db');
|
} = require('../db/plant_sub_section.db');
|
||||||
const { ErrorHandler } = require('../helpers/error');
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
class SubSectionService {
|
class SubSectionService {
|
||||||
88
services/sparepart.service.js
Normal file
88
services/sparepart.service.js
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
const {
|
||||||
|
getAllSparepartDb,
|
||||||
|
getSparepartByIdDb,
|
||||||
|
createSparepartDb,
|
||||||
|
updateSparepartDb,
|
||||||
|
deleteSparepartDb,
|
||||||
|
checkSparepartNameExistsDb,
|
||||||
|
} = require("../db/sparepart.db");
|
||||||
|
|
||||||
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
|
||||||
|
class SparepartService {
|
||||||
|
static async getAllSparepart(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllSparepartDb(param);
|
||||||
|
results.data.map((item) => {});
|
||||||
|
return results;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getSparepartById(id) {
|
||||||
|
try {
|
||||||
|
const sparepart = await getSparepartByIdDb(id);
|
||||||
|
|
||||||
|
if (!sparepart || sparepart.length === 0) {
|
||||||
|
throw new ErrorHandler(404, "Sparepart not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
return sparepart[0];
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async createSparepart(data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== "object") data = {};
|
||||||
|
if (data.sparepart_name) {
|
||||||
|
const exists = await checkSparepartNameExistsDb(data.sparepart_name);
|
||||||
|
if (exists)
|
||||||
|
throw new ErrorHandler(400, "Sparepart name already exists");
|
||||||
|
}
|
||||||
|
const created = await createSparepartDb(data);
|
||||||
|
if (!created) throw new ErrorHandler(500, "Failed to create Sparepart");
|
||||||
|
return created;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async updateSparepart(id, data) {
|
||||||
|
try {
|
||||||
|
const existing = await getSparepartByIdDb(id);
|
||||||
|
if (!existing) throw new ErrorHandler(404, "Sparepart not found");
|
||||||
|
if (
|
||||||
|
data.sparepart_name &&
|
||||||
|
data.sparepart_name !== existing.sparepart_name
|
||||||
|
) {
|
||||||
|
const exists = await checkSparepartNameExistsDb(
|
||||||
|
data.sparepart_name,
|
||||||
|
id
|
||||||
|
);
|
||||||
|
if (exists)
|
||||||
|
throw new ErrorHandler(400, "Sparepart name already exists");
|
||||||
|
}
|
||||||
|
const updated = await updateSparepartDb(id, data);
|
||||||
|
if (!updated) throw new ErrorHandler(500, "Failed to update Sparepart");
|
||||||
|
return await this.getSparepartById(id);
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async deleteSparepart(id, userId) {
|
||||||
|
try {
|
||||||
|
const existing = await getSparepartByIdDb(id);
|
||||||
|
if (!existing) throw new ErrorHandler(404, "Sparepart not found");
|
||||||
|
const deleted = await deleteSparepartDb(id, userId);
|
||||||
|
if (!deleted) throw new ErrorHandler(500, "Failed to delete Sparepart");
|
||||||
|
return deleted;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode || 500, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = SparepartService;
|
||||||
114
services/user_schedule.service.js
Normal file
114
services/user_schedule.service.js
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
const {
|
||||||
|
getAllUserScheduleDb,
|
||||||
|
getUserScheduleByIdDb,
|
||||||
|
getUserScheduleById,
|
||||||
|
insertUserScheduleDb,
|
||||||
|
updateUserScheduleDb,
|
||||||
|
deleteUserScheduleDb
|
||||||
|
} = require('../db/user_schedule.db');
|
||||||
|
const { ErrorHandler } = require('../helpers/error');
|
||||||
|
|
||||||
|
class UserScheduleService {
|
||||||
|
// Get all devices
|
||||||
|
static async getAllUserScheduleDb(param) {
|
||||||
|
try {
|
||||||
|
const results = await getAllUserScheduleDb(param);
|
||||||
|
|
||||||
|
results.data.map(element => {
|
||||||
|
});
|
||||||
|
|
||||||
|
return results
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get device by ID
|
||||||
|
static async getUserScheduleByID(id) {
|
||||||
|
try {
|
||||||
|
const result = await getUserScheduleByIdDb(id);
|
||||||
|
|
||||||
|
if (result.length < 1) throw new ErrorHandler(404, 'User Schedule not found');
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async createUserSchedules(data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
const exist = await getUserScheduleById(
|
||||||
|
data.user_id,
|
||||||
|
data.shift_id
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exist.length > 0) {
|
||||||
|
throw new ErrorHandler(
|
||||||
|
400,
|
||||||
|
`User dengan ID ${data.user_id} sudah terdaftar pada shift ${data.shift_id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await insertUserScheduleDb(data);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update user schedule
|
||||||
|
static async updateUserSchedules(id, data) {
|
||||||
|
try {
|
||||||
|
if (!data || typeof data !== 'object') data = {};
|
||||||
|
|
||||||
|
const dataExist = await getUserScheduleByIdDb(id);
|
||||||
|
|
||||||
|
if (dataExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'UserSchedules not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 🧩 VALIDASI SAAT UPDATE
|
||||||
|
if (data.user_id && data.shift_id) {
|
||||||
|
const exist = await getUserScheduleById(
|
||||||
|
data.user_id,
|
||||||
|
data.shift_id
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exist.length > 0 && exist[0].id !== Number(id)) {
|
||||||
|
throw new ErrorHandler(
|
||||||
|
400,
|
||||||
|
`User dengan ID ${data.user_id} sudah terdaftar pada shift ${data.shift_id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await updateUserScheduleDb(id, data);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete device
|
||||||
|
static async deleteUserSchedules(id, userId) {
|
||||||
|
try {
|
||||||
|
const dataExist = await getUserScheduleByIdDb(id);
|
||||||
|
|
||||||
|
if (dataExist.length < 1) {
|
||||||
|
throw new ErrorHandler(404, 'UserSchedules not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deleteUserScheduleDb(id, userId);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new ErrorHandler(error.statusCode, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = UserScheduleService;
|
||||||
|
|
||||||
BIN
uploads/images/tesimage.jpg
Normal file
BIN
uploads/images/tesimage.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 122 KiB |
BIN
uploads/pdf/pdf-467864af-2025-11-13_13-55-20.pdf
Normal file
BIN
uploads/pdf/pdf-467864af-2025-11-13_13-55-20.pdf
Normal file
Binary file not shown.
BIN
uploads/pdf/pdf-d0ded6ba-2025-10-26_17-11-14.pdf
Normal file
BIN
uploads/pdf/pdf-d0ded6ba-2025-10-26_17-11-14.pdf
Normal file
Binary file not shown.
BIN
uploads/pdf/pdf-ec196bab-2025-11-13_13-40-50.pdf
Normal file
BIN
uploads/pdf/pdf-ec196bab-2025-11-13_13-40-50.pdf
Normal file
Binary file not shown.
@@ -3,7 +3,7 @@ const crypto = require('crypto');
|
|||||||
|
|
||||||
const tokenSettings = {
|
const tokenSettings = {
|
||||||
access: {
|
access: {
|
||||||
expiresIn: '15m',
|
expiresIn: '12h',
|
||||||
type: 'access',
|
type: 'access',
|
||||||
secret: process.env.SECRET
|
secret: process.env.SECRET
|
||||||
},
|
},
|
||||||
|
|||||||
28
validate/brand.schema.js
Normal file
28
validate/brand.schema.js
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Brand Validation
|
||||||
|
// ========================
|
||||||
|
const insertBrandSchema = Joi.object({
|
||||||
|
brand_name: Joi.string().max(100).required(),
|
||||||
|
brand_type: Joi.string().max(50).optional().allow(""),
|
||||||
|
brand_manufacture: Joi.string().max(100).required(),
|
||||||
|
brand_model: Joi.string().max(100).optional().allow(""),
|
||||||
|
is_active: Joi.boolean().optional().default(true),
|
||||||
|
description: Joi.string().max(255).optional().allow(""),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update Brand Validation
|
||||||
|
const updateBrandSchema = Joi.object({
|
||||||
|
brand_name: Joi.string().max(100).optional(),
|
||||||
|
brand_type: Joi.string().max(50).optional().allow(""),
|
||||||
|
brand_manufacture: Joi.string().max(100).optional(),
|
||||||
|
brand_model: Joi.string().max(100).optional().allow(""),
|
||||||
|
is_active: Joi.boolean().optional(),
|
||||||
|
description: Joi.string().max(255).optional().allow(""),
|
||||||
|
}).min(1);
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertBrandSchema,
|
||||||
|
updateBrandSchema,
|
||||||
|
};
|
||||||
35
validate/contact.schema.js
Normal file
35
validate/contact.schema.js
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Contacts Validation
|
||||||
|
// ========================
|
||||||
|
const insertContactSchema = Joi.object({
|
||||||
|
contact_name: Joi.string().min(3).max(100).required(),
|
||||||
|
contact_phone: Joi.string()
|
||||||
|
.pattern(/^(?:\+62|0)8\d{7,10}$/)
|
||||||
|
.required()
|
||||||
|
.messages({
|
||||||
|
"string.pattern.base":
|
||||||
|
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
|
||||||
|
}),
|
||||||
|
is_active: Joi.boolean().required(),
|
||||||
|
contact_type: Joi.string().max(255).optional().allow(null)
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateContactSchema = Joi.object({
|
||||||
|
contact_name: Joi.string().min(3).max(100).optional(),
|
||||||
|
contact_phone: Joi.string()
|
||||||
|
.pattern(/^(?:\+62|0)8\d{7,10}$/)
|
||||||
|
.optional()
|
||||||
|
.messages({
|
||||||
|
"string.pattern.base":
|
||||||
|
"Phone number must be a valid Indonesian number in format +628XXXXXXXXX",
|
||||||
|
}),
|
||||||
|
is_active: Joi.boolean().optional(),
|
||||||
|
contact_type: Joi.string().max(255).optional().allow(null)
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertContactSchema,
|
||||||
|
updateContactSchema,
|
||||||
|
};
|
||||||
@@ -7,30 +7,33 @@ const Joi = require("joi");
|
|||||||
const insertDeviceSchema = Joi.object({
|
const insertDeviceSchema = Joi.object({
|
||||||
device_name: Joi.string().max(100).required(),
|
device_name: Joi.string().max(100).required(),
|
||||||
is_active: Joi.boolean().required(),
|
is_active: Joi.boolean().required(),
|
||||||
|
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({
|
||||||
device_name: Joi.string().max(100),
|
device_name: Joi.string().max(100),
|
||||||
is_active: Joi.boolean(),
|
is_active: Joi.boolean(),
|
||||||
|
brand_id: Joi.number().integer().min(1),
|
||||||
device_location: Joi.string().max(100),
|
device_location: Joi.string().max(100),
|
||||||
device_description: Joi.string(),
|
device_description: Joi.string(),
|
||||||
ip_address: Joi.string()
|
ip_address: Joi.string()
|
||||||
.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,
|
||||||
|
};
|
||||||
53
validate/notification.schema.js
Normal file
53
validate/notification.schema.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
// ========================
|
||||||
|
// Notification Validation
|
||||||
|
// ========================
|
||||||
|
|
||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Insert Notification Schema
|
||||||
|
// ========================
|
||||||
|
const insertNotificationSchema = Joi.object({
|
||||||
|
error_code_id: Joi.number().required().messages({
|
||||||
|
"any.required": "error_code_id is required",
|
||||||
|
"number.base": "error_code_id must be a number",
|
||||||
|
}),
|
||||||
|
|
||||||
|
message_error_issue: Joi.string().max(255).optional(),
|
||||||
|
|
||||||
|
is_send: Joi.boolean().required().messages({
|
||||||
|
"any.required": "is_send is required",
|
||||||
|
"boolean.base": "is_send must be a boolean",
|
||||||
|
}),
|
||||||
|
|
||||||
|
is_delivered: Joi.boolean().required().messages({
|
||||||
|
"any.required": "is_delivered is required",
|
||||||
|
"boolean.base": "is_delivered must be a boolean",
|
||||||
|
}),
|
||||||
|
|
||||||
|
is_read: Joi.boolean().required().messages({
|
||||||
|
"any.required": "is_read is required",
|
||||||
|
"boolean.base": "is_read must be a boolean",
|
||||||
|
}),
|
||||||
|
|
||||||
|
is_active: Joi.boolean().required().messages({
|
||||||
|
"any.required": "is_active is required",
|
||||||
|
"boolean.base": "is_active must be a boolean",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Update Notification Schema
|
||||||
|
// ========================
|
||||||
|
const updateNotificationSchema = Joi.object({
|
||||||
|
|
||||||
|
is_read: Joi.boolean().optional().messages({
|
||||||
|
"boolean.base": "is_read must be a boolean",
|
||||||
|
}),
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertNotificationSchema,
|
||||||
|
updateNotificationSchema,
|
||||||
|
};
|
||||||
11
validate/notification_error_log.schema.js
Normal file
11
validate/notification_error_log.schema.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
const insertNotificationErrorLogSchema = Joi.object({
|
||||||
|
notification_error_id: Joi.number().integer().required(),
|
||||||
|
contact_phone: Joi.string().optional(),
|
||||||
|
notification_error_log_description: Joi.string().required()
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertNotificationErrorLogSchema,
|
||||||
|
};
|
||||||
30
validate/notification_error_sparepart.schema.js
Normal file
30
validate/notification_error_sparepart.schema.js
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
const insertNotificationErrorSparepartSchema = Joi.object({
|
||||||
|
contact_id: Joi.number().required(),
|
||||||
|
|
||||||
|
brand_sparepart_id: Joi.number().required(),
|
||||||
|
|
||||||
|
is_verification: Joi.boolean().required(),
|
||||||
|
|
||||||
|
is_available: Joi.boolean().required(),
|
||||||
|
|
||||||
|
is_active: Joi.boolean().required(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateNotificationErrorSparepartSchema = Joi.object({
|
||||||
|
contact_id: Joi.number().required(),
|
||||||
|
|
||||||
|
brand_sparepart_id: Joi.number().optional(),
|
||||||
|
|
||||||
|
is_verification: Joi.boolean().optional(),
|
||||||
|
|
||||||
|
is_available: Joi.boolean().optional(),
|
||||||
|
|
||||||
|
is_active: Joi.boolean().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertNotificationErrorSparepartSchema,
|
||||||
|
updateNotificationErrorSparepartSchema,
|
||||||
|
};
|
||||||
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,
|
||||||
|
};
|
||||||
65
validate/plant_sub_section.schema.js
Normal file
65
validate/plant_sub_section.schema.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// Plant Sub Section Validation
|
||||||
|
// ========================
|
||||||
|
const insertSubSectionSchema = Joi.object({
|
||||||
|
plant_sub_section_name: Joi.string()
|
||||||
|
.max(200)
|
||||||
|
.required()
|
||||||
|
.messages({
|
||||||
|
"string.base": "Sub section name must be a string",
|
||||||
|
"string.max": "Sub section name cannot exceed 200 characters",
|
||||||
|
"any.required": "Sub section name is required"
|
||||||
|
}),
|
||||||
|
plant_sub_section_description: Joi.string()
|
||||||
|
.max(200)
|
||||||
|
.allow('')
|
||||||
|
.optional()
|
||||||
|
.messages({
|
||||||
|
"string.base": "Description must be a string",
|
||||||
|
"string.max": "Description cannot exceed 200 characters"
|
||||||
|
}),
|
||||||
|
table_name_value: Joi.string()
|
||||||
|
.max(255)
|
||||||
|
.allow('')
|
||||||
|
.optional()
|
||||||
|
.messages({
|
||||||
|
"string.base": "Table name value must be a string",
|
||||||
|
"string.max": "Table name value cannot exceed 255 characters"
|
||||||
|
}),
|
||||||
|
is_active: Joi.boolean()
|
||||||
|
.default(true)
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateSubSectionSchema = Joi.object({
|
||||||
|
plant_sub_section_name: Joi.string()
|
||||||
|
.max(200)
|
||||||
|
.messages({
|
||||||
|
"string.base": "Sub section name must be a string",
|
||||||
|
"string.max": "Sub section name cannot exceed 200 characters",
|
||||||
|
}).optional(),
|
||||||
|
plant_sub_section_description: Joi.string()
|
||||||
|
.max(200)
|
||||||
|
.allow('')
|
||||||
|
.optional()
|
||||||
|
.messages({
|
||||||
|
"string.base": "Description must be a string",
|
||||||
|
"string.max": "Description cannot exceed 200 characters"
|
||||||
|
}),
|
||||||
|
table_name_value: Joi.string()
|
||||||
|
.max(255)
|
||||||
|
.allow('')
|
||||||
|
.optional()
|
||||||
|
.messages({
|
||||||
|
"string.base": "Table name value must be a string",
|
||||||
|
"string.max": "Table name value cannot exceed 255 characters"
|
||||||
|
}),
|
||||||
|
is_active: Joi.boolean().optional()
|
||||||
|
}).min(1);
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertSubSectionSchema,
|
||||||
|
updateSubSectionSchema
|
||||||
|
};
|
||||||
32
validate/sparepart.schema.js
Normal file
32
validate/sparepart.schema.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
// ========================
|
||||||
|
// Sparepart Validation
|
||||||
|
// ========================
|
||||||
|
const insertSparepartSchema = Joi.object({
|
||||||
|
sparepart_name: Joi.string().max(255).required(),
|
||||||
|
sparepart_description: Joi.string().max(255).optional(),
|
||||||
|
sparepart_model: Joi.string().max(255).optional(),
|
||||||
|
sparepart_foto: Joi.string().max(255).optional().allow(""),
|
||||||
|
sparepart_item_type: Joi.string().max(255).optional(),
|
||||||
|
sparepart_qty: Joi.number().integer().min(0),
|
||||||
|
sparepart_unit: Joi.string().max(255).optional(),
|
||||||
|
sparepart_merk: Joi.string().max(255).optional(),
|
||||||
|
sparepart_stok: Joi.string().max(255).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update Validation
|
||||||
|
const updateSparepartSchema = Joi.object({
|
||||||
|
sparepart_name: Joi.string().max(255).optional(),
|
||||||
|
sparepart_description: Joi.string().max(255).optional(),
|
||||||
|
sparepart_model: Joi.string().max(255).optional(),
|
||||||
|
sparepart_foto: Joi.string().max(255).optional().allow(''),
|
||||||
|
sparepart_item_type: Joi.string().max(255).optional(),
|
||||||
|
sparepart_qty: Joi.number().integer().min(0),
|
||||||
|
sparepart_unit: Joi.string().max(255).optional(),
|
||||||
|
sparepart_merk: Joi.string().max(255).optional(),
|
||||||
|
sparepart_stok: Joi.string().max(255).optional(),
|
||||||
|
});
|
||||||
|
module.exports = {
|
||||||
|
insertSparepartSchema,
|
||||||
|
updateSparepartSchema,
|
||||||
|
};
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
const Joi = require("joi");
|
|
||||||
|
|
||||||
// ========================
|
|
||||||
// Plant Sub Section Validation
|
|
||||||
// ========================
|
|
||||||
const insertSubSectionSchema = Joi.object({
|
|
||||||
sub_section_name: Joi.string()
|
|
||||||
.max(200)
|
|
||||||
.required()
|
|
||||||
.messages({
|
|
||||||
"string.base": "Sub section name must be a string",
|
|
||||||
"string.max": "Sub section name cannot exceed 200 characters",
|
|
||||||
"any.required": "Sub section name is required"
|
|
||||||
}).required(),
|
|
||||||
is_active: Joi.boolean().required(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateSubSectionSchema = Joi.object({
|
|
||||||
sub_section_name: Joi.string()
|
|
||||||
.max(200)
|
|
||||||
.messages({
|
|
||||||
"string.base": "Sub section name must be a string",
|
|
||||||
"string.max": "Sub section name cannot exceed 200 characters",
|
|
||||||
}).optional(),
|
|
||||||
is_active: Joi.boolean().optional(),
|
|
||||||
}).min(1).messages({
|
|
||||||
"object.min": "At least one field must be provided to update",
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
insertSubSectionSchema,
|
|
||||||
updateSubSectionSchema
|
|
||||||
};
|
|
||||||
@@ -8,22 +8,36 @@ const insertTagsSchema = Joi.object({
|
|||||||
device_id: Joi.number().optional(),
|
device_id: Joi.number().optional(),
|
||||||
tag_name: Joi.string().max(200).required(),
|
tag_name: Joi.string().max(200).required(),
|
||||||
tag_number: Joi.number().required(),
|
tag_number: Joi.number().required(),
|
||||||
is_active: Joi.boolean().required(),
|
tag_description: Joi.string().max(200).optional(),
|
||||||
data_type: Joi.string().max(50).required(),
|
is_active: Joi.boolean().optional(),
|
||||||
unit: Joi.string().max(50).required(),
|
data_type: Joi.string().max(50).optional(),
|
||||||
sub_section_id: Joi.number().optional(),
|
unit: Joi.string().max(50).optional(),
|
||||||
is_alarm: Joi.boolean().required()
|
plant_sub_section_id: Joi.number().optional(),
|
||||||
|
is_alarm: Joi.boolean().optional(),
|
||||||
|
is_report: Joi.boolean().optional(),
|
||||||
|
is_history: Joi.boolean().optional(),
|
||||||
|
lim_low_crash: Joi.number().optional(),
|
||||||
|
lim_low: Joi.number().optional(),
|
||||||
|
lim_high: Joi.number().optional(),
|
||||||
|
lim_high_crash: Joi.number().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateTagsSchema = Joi.object({
|
const updateTagsSchema = Joi.object({
|
||||||
device_id: Joi.number(),
|
device_id: Joi.number().optional(),
|
||||||
tag_name: Joi.string().max(200),
|
tag_name: Joi.string().max(200),
|
||||||
tag_number: Joi.number(),
|
tag_number: Joi.number(),
|
||||||
|
tag_description: Joi.string().max(200).optional(),
|
||||||
is_active: Joi.boolean(),
|
is_active: Joi.boolean(),
|
||||||
data_type: Joi.string().max(50),
|
data_type: Joi.string().max(50),
|
||||||
unit: Joi.string().max(50),
|
unit: Joi.string().max(50),
|
||||||
is_alarm: Joi.boolean().optional(),
|
is_alarm: Joi.boolean().optional(),
|
||||||
sub_section_id: Joi.number().optional(),
|
plant_sub_section_id: Joi.number().optional(),
|
||||||
|
is_report: Joi.boolean().optional(),
|
||||||
|
is_history: Joi.boolean().optional(),
|
||||||
|
lim_low_crash: Joi.number().optional(),
|
||||||
|
lim_low: Joi.number().optional(),
|
||||||
|
lim_high: Joi.number().optional(),
|
||||||
|
lim_high_crash: Joi.number().optional(),
|
||||||
}).min(1);
|
}).min(1);
|
||||||
|
|
||||||
// ✅ Export dengan CommonJS
|
// ✅ Export dengan CommonJS
|
||||||
|
|||||||
@@ -5,14 +5,14 @@ const Joi = require("joi");
|
|||||||
// ========================
|
// ========================
|
||||||
const insertUnitSchema = Joi.object({
|
const insertUnitSchema = Joi.object({
|
||||||
unit_name: Joi.string().max(100).required(),
|
unit_name: Joi.string().max(100).required(),
|
||||||
tag_id: Joi.number().integer().optional(),
|
|
||||||
is_active: Joi.boolean().required(),
|
is_active: Joi.boolean().required(),
|
||||||
|
unit_description: Joi.string().max(255).allow('')
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateUnitSchema = Joi.object({
|
const updateUnitSchema = Joi.object({
|
||||||
unit_name: Joi.string().max(100).optional(),
|
unit_name: Joi.string().max(100).optional(),
|
||||||
tag_id: Joi.number().integer().optional(),
|
is_active: Joi.boolean().optional(),
|
||||||
is_active: Joi.boolean().optional()
|
unit_description: Joi.string().max(255).allow('')
|
||||||
}).min(1);
|
}).min(1);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|||||||
21
validate/user_schedule.schema.js
Normal file
21
validate/user_schedule.schema.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
const Joi = require("joi");
|
||||||
|
|
||||||
|
// ========================
|
||||||
|
// User Schedule Validation
|
||||||
|
// ========================
|
||||||
|
const insertUserScheduleSchema = Joi.object({
|
||||||
|
user_id: Joi.number().integer().required(),
|
||||||
|
schedule_id: Joi.number().integer().optional(),
|
||||||
|
shift_id: Joi.number().required(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateUserScheduleSchema = Joi.object({
|
||||||
|
user_id: Joi.number().integer().optional(),
|
||||||
|
schedule_id: Joi.number().integer().optional(),
|
||||||
|
shift_id: Joi.number().optional()
|
||||||
|
}).min(1);
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
insertUserScheduleSchema,
|
||||||
|
updateUserScheduleSchema
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user