Compare commits

...

4 Commits

Author SHA1 Message Date
95189e2014 add: sub section sroute 2025-10-11 16:21:38 +07:00
d5c53b2953 add: crud subsection 2025-10-11 16:21:14 +07:00
ace419fa3e add: validate sub section 2025-10-11 16:20:54 +07:00
7c55e786f3 add: sub section db 2025-10-11 16:20:22 +07:00
6 changed files with 317 additions and 1 deletions

View File

@@ -0,0 +1,71 @@
const SubSectionService = require('../services/sub_section.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertSubSectionSchema, updateSubSectionSchema } = require('../validate/sub_section.schema');
class SubSectionController {
// Get all sub sections
static async getAll(req, res) {
const queryParams = req.query;
const results = await SubSectionService.getAll(queryParams);
const response = await setResponsePaging(queryParams, results, 'Sub section found');
res.status(response.statusCode).json(response);
}
// Get sub section by ID
static async getById(req, res) {
const { id } = req.params;
const results = await SubSectionService.getById(id);
const response = await setResponse(results, 'Sub section found');
res.status(response.statusCode).json(response);
}
// Create sub section
static async create(req, res) {
const { error, value } = await checkValidate(insertSubSectionSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
value.userId = req.user.user_id;
const results = await SubSectionService.create(value);
const response = await setResponse(results, 'Sub section created successfully');
return res.status(response.statusCode).json(response);
}
// Update sub section
static async update(req, res) {
const { id } = req.params;
const { error, value } = checkValidate(updateSubSectionSchema, req);
if (error) {
return res.status(400).json(setResponse(error, 'Validation failed', 400));
}
value.userId = req.user.user_id;
const results = await SubSectionService.update(id, value);
const response = await setResponse(results, 'Sub section updated successfully');
res.status(response.statusCode).json(response);
}
// Soft delete sub section
static async delete(req, res) {
const { id } = req.params;
const results = await SubSectionService.delete(id, req.user.user_id);
const response = await setResponse(results, 'Sub section deleted successfully');
res.status(response.statusCode).json(response);
}
}
module.exports = SubSectionController;

108
db/sub_section.db.js Normal file
View File

@@ -0,0 +1,108 @@
const pool = require("../config");
// Get all sub sections
const getAllSubSectionsDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
// OR condition (pencarian bebas)
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["a.sub_section_code", "a.sub_section_name"],
searchParams.criteria,
queryParams
);
queryParams = whereParamOr ?? queryParams;
// AND condition (filter spesifik)
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "a.sub_section_code", param: searchParams.code, type: "string" },
{ column: "a.sub_section_name", param: searchParams.name, type: "string" },
],
queryParams
);
queryParams = whereParamAnd ?? queryParams;
// Query utama
const queryText = `
SELECT COUNT(*) OVER() AS total_data, a.*
FROM m_plant_sub_section a
WHERE a.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? whereOrConditions : ""}
ORDER BY a.sub_section_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 sub section by ID
const getSubSectionByIdDb = async (id) => {
const queryText = `
SELECT a.*
FROM m_plant_sub_section a
WHERE a.sub_section_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
// Create new sub section
const createSubSectionDb = async (data) => {
// Generate kode otomatis
const newCode = await pool.generateKode("SUB", "m_plant_sub_section", "sub_section_code");
const store = {
...data,
sub_section_code: newCode
};
const { query: queryText, values } = pool.buildDynamicInsert("m_plant_sub_section", store);
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId ? await getSubSectionByIdDb(insertedId) : null;
};
// Update sub section
const updateSubSectionDb = async (id, data) => {
const store = { ...data };
const whereData = { sub_section_id: id };
const { query: queryText, values } = pool.buildDynamicUpdate("m_plant_sub_section", store, whereData);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getSubSectionByIdDb(id);
};
// Soft delete sub section
const deleteSubSectionDb = async (id, deletedBy) => {
const queryText = `
UPDATE m_plant_sub_section
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE sub_section_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllSubSectionsDb,
getSubSectionByIdDb,
createSubSectionDb,
updateSubSectionDb,
deleteSubSectionDb,
};

View File

@@ -4,11 +4,13 @@ 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")
router.use("/auth", auth);
router.use("/user", users);
router.use("/device", device);
router.use("/roles", roles);
router.use("/tags", tags)
router.use("/tags", tags);
router.use("/plant-sub-section", subSection);
module.exports = router;

View File

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

View File

@@ -0,0 +1,87 @@
const {
getAllSubSectionsDb,
getSubSectionByIdDb,
createSubSectionDb,
updateSubSectionDb,
deleteSubSectionDb
} = require('../db/sub_section.db');
const { ErrorHandler } = require('../helpers/error');
class SubSectionService {
// Get all sub sections
static async getAll(param) {
try {
const results = await getAllSubSectionsDb(param);
results.data.map(el => {});
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Get sub section by ID
static async getById(id) {
try {
const result = await getSubSectionByIdDb(id);
if (result.length < 1) throw new ErrorHandler(404, 'Sub section not found');
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Create sub section
static async create(data) {
try {
if (!data || typeof data !== 'object') data = {};
const result = await createSubSectionDb(data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Update sub section
static async update(id, data) {
try {
if (!data || typeof data !== 'object') data = {};
const dataExist = await getSubSectionByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, 'Sub section not found');
}
const result = await updateSubSectionDb(id, data);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Soft delete sub section
static async delete(id, userId) {
try {
const dataExist = await getSubSectionByIdDb(id);
if (dataExist.length < 1) {
throw new ErrorHandler(404, 'Sub section not found');
}
const result = await deleteSubSectionDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
}
module.exports = SubSectionService;

View File

@@ -0,0 +1,31 @@
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"
}),
});
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",
}),
}).min(1).messages({
"object.min": "At least one field must be provided to update",
});
module.exports = {
insertSubSectionSchema,
updateSubSectionSchema
};