From 2b93baa64886af8786c41178915a5ee35694ccc4 Mon Sep 17 00:00:00 2001 From: mhmmdafif Date: Tue, 9 Dec 2025 16:30:19 +0700 Subject: [PATCH] add: crud notif error user --- .../notification_error_user.controller.js | 71 ++++++++++++ db/notification_error_user.db.js | 105 ++++++++++++++++++ routes/index.js | 2 + routes/notification_error_user.route.js | 17 +++ services/notification_error_user.service.js | 88 +++++++++++++++ validate/notification_error_user.schema.js | 44 ++++++++ 6 files changed, 327 insertions(+) create mode 100644 controllers/notification_error_user.controller.js create mode 100644 db/notification_error_user.db.js create mode 100644 routes/notification_error_user.route.js create mode 100644 services/notification_error_user.service.js create mode 100644 validate/notification_error_user.schema.js diff --git a/controllers/notification_error_user.controller.js b/controllers/notification_error_user.controller.js new file mode 100644 index 0000000..6855991 --- /dev/null +++ b/controllers/notification_error_user.controller.js @@ -0,0 +1,71 @@ +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, 'Contact updated successfully') + + res.status(response.statusCode).json(response); + } + + // Soft delete contact + static async delete(req, res) { + const { id } = req.params; + + const results = await NotificationErrorUserService.deleteNotificationErrorUser(id, req.user.user_id); + const response = await setResponse(results, 'Contact deleted successfully') + + res.status(response.statusCode).json(response); + } +} + +module.exports = NotificationErrorUserController; diff --git a/db/notification_error_user.db.js b/db/notification_error_user.db.js new file mode 100644 index 0000000..5893d1c --- /dev/null +++ b/db/notification_error_user.db.js @@ -0,0 +1,105 @@ +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.* + FROM notification_error_user a + WHERE a.notification_error_user_id = $1 AND a.deleted_at IS NULL + `; + const result = await pool.query(queryText, [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, + createNotificationErrorUserDb, + updateNotificationErrorUserDb, + deleteNotificationErrorUserDb, +}; diff --git a/routes/index.js b/routes/index.js index e6121bf..fabe125 100644 --- a/routes/index.js +++ b/routes/index.js @@ -18,6 +18,7 @@ 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); @@ -39,6 +40,7 @@ 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; diff --git a/routes/notification_error_user.route.js b/routes/notification_error_user.route.js new file mode 100644 index 0000000..473a0a7 --- /dev/null +++ b/routes/notification_error_user.route.js @@ -0,0 +1,17 @@ +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); + +module.exports = router; \ No newline at end of file diff --git a/services/notification_error_user.service.js b/services/notification_error_user.service.js new file mode 100644 index 0000000..f589a7a --- /dev/null +++ b/services/notification_error_user.service.js @@ -0,0 +1,88 @@ +const { + getAllNotificationErrorUserDb, + getNotificationErrorUserByIdDb, + createNotificationErrorUserDb, + updateNotificationErrorUserDb, + deleteNotificationErrorUserDb +} = require('../db/notification_error_user.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, 'NotificationErrorUser 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, 'NotificationErrorUser 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, 'NotificationErrorUser not found'); + } + + const result = await deleteNotificationErrorUserDb(id, userId); + + return result; + } catch (error) { + throw new ErrorHandler(error.statusCode, error.message); + } + } +} + +module.exports = NotificationErrorUserService; diff --git a/validate/notification_error_user.schema.js b/validate/notification_error_user.schema.js new file mode 100644 index 0000000..5aae2ce --- /dev/null +++ b/validate/notification_error_user.schema.js @@ -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, +};