113 lines
2.6 KiB
JavaScript
113 lines
2.6 KiB
JavaScript
const pool = require("../config");
|
|
|
|
// Get all roles
|
|
const getAllShiftDb = async (searchParams = {}) => {
|
|
let queryParams = [];
|
|
|
|
// Pagination
|
|
if (searchParams.limit) {
|
|
const page = Number(searchParams.page ?? 1) - 1;
|
|
queryParams = [Number(searchParams.limit ?? 10), page];
|
|
}
|
|
|
|
// Filtering
|
|
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
|
|
[
|
|
{ column: "a.shift_name", param: searchParams.shift_name, type: "string" },
|
|
{
|
|
column: "a.start_time",
|
|
param: searchParams.start_time,
|
|
type: "time",
|
|
},
|
|
{
|
|
column: "a.end_time",
|
|
param: searchParams.end_time,
|
|
type: "time",
|
|
},
|
|
],
|
|
queryParams
|
|
);
|
|
|
|
queryParams = whereParamAnd ? whereParamAnd : queryParams;
|
|
|
|
const queryText = `
|
|
SELECT
|
|
COUNT(*) OVER() AS total_data,
|
|
a.*
|
|
FROM m_shift a
|
|
WHERE a.deleted_at IS NULL
|
|
${whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""}
|
|
ORDER BY a.shift_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 role by ID
|
|
const getShiftByIdDb = async (id) => {
|
|
const queryText = `
|
|
SELECT
|
|
a.*
|
|
FROM m_shift a
|
|
WHERE a.shift_id = $1 AND a.deleted_at IS NULL
|
|
`;
|
|
const result = await pool.query(queryText, [id]);
|
|
return result.recordset;
|
|
};
|
|
|
|
// Create role
|
|
const createShiftDB = async (data) => {
|
|
const store = { ...data };
|
|
|
|
const { query: queryText, values } = pool.buildDynamicInsert(
|
|
"m_shift",
|
|
store
|
|
);
|
|
const result = await pool.query(queryText, values);
|
|
|
|
const insertedId = result.recordset[0]?.inserted_id;
|
|
return insertedId ? await getShiftByIdDb(insertedId) : null;
|
|
};
|
|
|
|
// Update role
|
|
const updateShiftDb = async (id, data) => {
|
|
const store = { ...data };
|
|
const whereData = { shift_id: id };
|
|
|
|
const { query: queryText, values } = pool.buildDynamicUpdate(
|
|
"m_shift",
|
|
store,
|
|
whereData
|
|
);
|
|
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
|
|
|
|
return getShiftByIdDb(id);
|
|
};
|
|
|
|
const deleteShiftDb = async (id, deletedBy) => {
|
|
const queryText = `
|
|
UPDATE m_shift
|
|
SET deleted_at = CURRENT_TIMESTAMP,
|
|
deleted_by = $1
|
|
WHERE shift_id = $2 AND deleted_at IS NULL
|
|
`;
|
|
await pool.query(queryText, [deletedBy, id]);
|
|
return true;
|
|
};
|
|
|
|
module.exports = {
|
|
getAllShiftDb,
|
|
getShiftByIdDb,
|
|
createShiftDB,
|
|
updateShiftDb,
|
|
deleteShiftDb,
|
|
};
|