Compare commits
5 Commits
2bb8712430
...
4083e8544e
| Author | SHA1 | Date | |
|---|---|---|---|
| 4083e8544e | |||
| 90f529bfde | |||
| f2109e5fdf | |||
| 7e769a1fac | |||
| 1aec3825e7 |
71
controllers/unit.controller.js
Normal file
71
controllers/unit.controller.js
Normal file
@@ -0,0 +1,71 @@
|
||||
const UnitService = require('../services/unit.service');
|
||||
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
|
||||
const { insertUnitSchema, updateUnitSchema } = require('../validate/unit.schema');
|
||||
|
||||
class UnitController {
|
||||
// Get all units
|
||||
static async getAll(req, res) {
|
||||
const queryParams = req.query;
|
||||
|
||||
const results = await UnitService.getAllUnits(queryParams);
|
||||
const response = await setResponsePaging(queryParams, results, 'Unit found');
|
||||
|
||||
res.status(response.statusCode).json(response);
|
||||
}
|
||||
|
||||
// Get unit by ID
|
||||
static async getById(req, res) {
|
||||
const { id } = req.params;
|
||||
|
||||
const results = await UnitService.getUnitById(id);
|
||||
const response = await setResponse(results, 'Unit found');
|
||||
|
||||
res.status(response.statusCode).json(response);
|
||||
}
|
||||
|
||||
// Create unit
|
||||
static async create(req, res) {
|
||||
const { error, value } = await checkValidate(insertUnitSchema, req);
|
||||
|
||||
if (error) {
|
||||
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||
}
|
||||
|
||||
value.created_by = req.user.user_id;
|
||||
|
||||
const results = await UnitService.createUnit(value);
|
||||
const response = await setResponse(results, 'Unit created successfully');
|
||||
|
||||
return res.status(response.statusCode).json(response);
|
||||
}
|
||||
|
||||
// Update unit
|
||||
static async update(req, res) {
|
||||
const { id } = req.params;
|
||||
|
||||
const { error, value } = checkValidate(updateUnitSchema, req);
|
||||
|
||||
if (error) {
|
||||
return res.status(400).json(setResponse(error, 'Validation failed', 400));
|
||||
}
|
||||
|
||||
value.updated_by = req.user.user_id;
|
||||
|
||||
const results = await UnitService.updateUnit(id, value);
|
||||
const response = await setResponse(results, 'Unit updated successfully');
|
||||
|
||||
res.status(response.statusCode).json(response);
|
||||
}
|
||||
|
||||
// Soft delete unit
|
||||
static async delete(req, res) {
|
||||
const { id } = req.params;
|
||||
|
||||
const results = await UnitService.deleteUnit(id, req.user.user_id);
|
||||
const response = await setResponse(results, 'Unit deleted successfully');
|
||||
|
||||
res.status(response.statusCode).json(response);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = UnitController;
|
||||
119
db/unit.db.js
Normal file
119
db/unit.db.js
Normal file
@@ -0,0 +1,119 @@
|
||||
const pool = require("../config");
|
||||
|
||||
// Get all units
|
||||
const getAllUnitsDb = 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.unit_code", "a.unit_name"],
|
||||
searchParams.criteria,
|
||||
queryParams
|
||||
);
|
||||
|
||||
queryParams = whereParamOr ? whereParamOr : queryParams;
|
||||
|
||||
// Filter
|
||||
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
||||
[
|
||||
{ column: "a.unit_code", param: searchParams.code, type: "string" },
|
||||
{ column: "a.unit_name", param: searchParams.name, type: "string" },
|
||||
{ column: "a.tag_id", param: searchParams.tag, type: "number" },
|
||||
{ column: "a.is_active", param: searchParams.status, type: "string" },
|
||||
],
|
||||
queryParams
|
||||
);
|
||||
|
||||
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
||||
|
||||
const queryText = `
|
||||
SELECT
|
||||
COUNT(*) OVER() AS total_data,
|
||||
a.*,
|
||||
COALESCE(a.unit_code, '') + ' - ' + COALESCE(a.unit_name, '') AS unit_code_name
|
||||
FROM m_unit a
|
||||
WHERE a.deleted_at IS NULL
|
||||
${whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""}
|
||||
${whereOrConditions ? whereOrConditions : ""}
|
||||
ORDER BY a.unit_id ASC
|
||||
${searchParams.limit ? `OFFSET $2 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 };
|
||||
};
|
||||
|
||||
// Get unit by ID
|
||||
const getUnitByIdDb = async (id) => {
|
||||
const queryText = `
|
||||
SELECT
|
||||
a.*,
|
||||
COALESCE(a.unit_code, '') + ' - ' + COALESCE(a.unit_name, '') AS unit_code_name
|
||||
FROM m_unit a
|
||||
WHERE a.unit_id = $1 AND a.deleted_at IS NULL
|
||||
`;
|
||||
const result = await pool.query(queryText, [id]);
|
||||
return result.recordset;
|
||||
};
|
||||
|
||||
// Create unit
|
||||
const createUnitDb = async (data) => {
|
||||
const newCode = await pool.generateKode("UNT", "m_unit", "unit_code");
|
||||
|
||||
const store = {
|
||||
...data,
|
||||
unit_code: newCode,
|
||||
};
|
||||
|
||||
const { query: queryText, values } = pool.buildDynamicInsert("m_unit", store);
|
||||
const result = await pool.query(queryText, values);
|
||||
const insertedId = result.recordset[0]?.inserted_id;
|
||||
return insertedId ? await getUnitByIdDb(insertedId) : null;
|
||||
};
|
||||
|
||||
// Update unit
|
||||
const updateUnitDb = async (id, data) => {
|
||||
const store = { ...data };
|
||||
const whereData = { unit_id: id };
|
||||
|
||||
const { query: queryText, values } = pool.buildDynamicUpdate(
|
||||
"m_unit",
|
||||
store,
|
||||
whereData
|
||||
);
|
||||
|
||||
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
||||
return getUnitByIdDb(id);
|
||||
};
|
||||
|
||||
// Soft delete unit
|
||||
const deleteUnitDb = async (id, deletedBy) => {
|
||||
const queryText = `
|
||||
UPDATE m_unit
|
||||
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
|
||||
WHERE unit_id = $2 AND deleted_at IS NULL
|
||||
`;
|
||||
await pool.query(queryText, [deletedBy, id]);
|
||||
return true;
|
||||
};
|
||||
|
||||
// Export
|
||||
module.exports = {
|
||||
getAllUnitsDb,
|
||||
getUnitByIdDb,
|
||||
createUnitDb,
|
||||
updateUnitDb,
|
||||
deleteUnitDb,
|
||||
};
|
||||
@@ -2,12 +2,13 @@ const router = require("express").Router();
|
||||
const auth = require("./auth.route");
|
||||
const users = require("./users.route");
|
||||
const device = require('./device.route');
|
||||
const roles = require('./roles.route')
|
||||
const tags = require("./tags.route")
|
||||
const subSection = require("./sub_section.route")
|
||||
const shift = require("./shift.route")
|
||||
const schedule = require("./schedule.route")
|
||||
const status = require("./status.route")
|
||||
const roles = require('./roles.route');
|
||||
const tags = require("./tags.route");
|
||||
const subSection = require("./sub_section.route");
|
||||
const shift = require("./shift.route");
|
||||
const schedule = require("./schedule.route");
|
||||
const status = require("./status.route");
|
||||
const unit = require("./unit.route")
|
||||
|
||||
router.use("/auth", auth);
|
||||
router.use("/user", users);
|
||||
@@ -17,7 +18,8 @@ router.use("/tags", tags);
|
||||
router.use("/plant-sub-section", subSection);
|
||||
router.use("/shift", shift);
|
||||
router.use("/schedule", schedule);
|
||||
router.use("/status", status)
|
||||
router.use("/status", status);
|
||||
router.use("/unit", unit);
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
17
routes/unit.route.js
Normal file
17
routes/unit.route.js
Normal file
@@ -0,0 +1,17 @@
|
||||
const express = require('express');
|
||||
const UnitController = require('../controllers/unit.controller');
|
||||
const verifyToken = require('../middleware/verifyToken');
|
||||
const verifyAccess = require('../middleware/verifyAccess');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.route('/')
|
||||
.get(verifyToken.verifyAccessToken, UnitController.getAll)
|
||||
.post(verifyToken.verifyAccessToken, verifyAccess(), UnitController.create);
|
||||
|
||||
router.route('/:id')
|
||||
.get(verifyToken.verifyAccessToken, UnitController.getById)
|
||||
.put(verifyToken.verifyAccessToken, verifyAccess(), UnitController.update)
|
||||
.delete(verifyToken.verifyAccessToken, verifyAccess(), UnitController.delete);
|
||||
|
||||
module.exports = router;
|
||||
88
services/unit.service.js
Normal file
88
services/unit.service.js
Normal file
@@ -0,0 +1,88 @@
|
||||
const {
|
||||
getAllUnitsDb,
|
||||
getUnitByIdDb,
|
||||
createUnitDb,
|
||||
updateUnitDb,
|
||||
deleteUnitDb
|
||||
} = require('../db/unit.db');
|
||||
const { ErrorHandler } = require('../helpers/error');
|
||||
|
||||
class UnitService {
|
||||
// Get all units
|
||||
static async getAllUnits(param) {
|
||||
try {
|
||||
const results = await getAllUnitsDb(param);
|
||||
|
||||
results.data.map(element => {
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
throw new ErrorHandler(error.statusCode, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Get unit by ID
|
||||
static async getUnitById(id) {
|
||||
try {
|
||||
const result = await getUnitByIdDb(id);
|
||||
|
||||
if (result.length < 1) throw new ErrorHandler(404, 'Unit not found');
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new ErrorHandler(error.statusCode, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Create unit
|
||||
static async createUnit(data) {
|
||||
try {
|
||||
if (!data || typeof data !== 'object') data = {};
|
||||
|
||||
const result = await createUnitDb(data);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new ErrorHandler(error.statusCode, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Update unit
|
||||
static async updateUnit(id, data) {
|
||||
try {
|
||||
if (!data || typeof data !== 'object') data = {};
|
||||
|
||||
const dataExist = await getUnitByIdDb(id);
|
||||
|
||||
if (dataExist.length < 1) {
|
||||
throw new ErrorHandler(404, 'Unit not found');
|
||||
}
|
||||
|
||||
const result = await updateUnitDb(id, data);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new ErrorHandler(error.statusCode, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Soft delete unit
|
||||
static async deleteUnit(id, userId) {
|
||||
try {
|
||||
const dataExist = await getUnitByIdDb(id);
|
||||
|
||||
if (dataExist.length < 1) {
|
||||
throw new ErrorHandler(404, 'Unit not found');
|
||||
}
|
||||
|
||||
const result = await deleteUnitDb(id, userId);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new ErrorHandler(error.statusCode, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = UnitService;
|
||||
@@ -11,6 +11,7 @@ const insertTagsSchema = Joi.object({
|
||||
is_active: Joi.boolean().required(),
|
||||
data_type: Joi.string().max(50).required(),
|
||||
unit: Joi.string().max(50).required(),
|
||||
is_alarm: Joi.boolean().required()
|
||||
});
|
||||
|
||||
const updateTagsSchema = Joi.object({
|
||||
@@ -20,6 +21,7 @@ const updateTagsSchema = Joi.object({
|
||||
is_active: Joi.boolean(),
|
||||
data_type: Joi.string().max(50),
|
||||
unit: Joi.string().max(50),
|
||||
is_alarm: Joi.boolean().optional()
|
||||
}).min(1);
|
||||
|
||||
// ✅ Export dengan CommonJS
|
||||
|
||||
21
validate/unit.schema.js
Normal file
21
validate/unit.schema.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const Joi = require("joi");
|
||||
|
||||
// ========================
|
||||
// Unit Validation
|
||||
// ========================
|
||||
const insertUnitSchema = Joi.object({
|
||||
unit_name: Joi.string().max(100).required(),
|
||||
tag_id: Joi.number().integer().optional(),
|
||||
is_active: Joi.boolean().required(),
|
||||
});
|
||||
|
||||
const updateUnitSchema = Joi.object({
|
||||
unit_name: Joi.string().max(100).optional(),
|
||||
tag_id: Joi.number().integer().optional(),
|
||||
is_active: Joi.boolean().optional()
|
||||
}).min(1);
|
||||
|
||||
module.exports = {
|
||||
insertUnitSchema,
|
||||
updateUnitSchema
|
||||
};
|
||||
Reference in New Issue
Block a user