add: filter schedule data harian/mingguan/bulanan
This commit is contained in:
@@ -31,11 +31,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 +58,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 +79,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,10 +94,9 @@ 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);
|
||||||
@@ -112,7 +116,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 +124,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 +136,60 @@ 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 +207,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 +228,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 +249,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");
|
||||||
|
|
||||||
@@ -238,6 +289,7 @@ module.exports = {
|
|||||||
checkConnection,
|
checkConnection,
|
||||||
query,
|
query,
|
||||||
buildFilterQuery,
|
buildFilterQuery,
|
||||||
|
buildDateFilter,
|
||||||
buildStringOrIlike,
|
buildStringOrIlike,
|
||||||
buildDynamicInsert,
|
buildDynamicInsert,
|
||||||
buildDynamicUpdate,
|
buildDynamicUpdate,
|
||||||
|
|||||||
@@ -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 * $1 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
|
||||||
|
|||||||
Reference in New Issue
Block a user