Files
cod-api/db/device.db.js
2025-10-08 11:37:33 +07:00

80 lines
2.4 KiB
JavaScript

const pool = require("../config");
// Get all devices
const getAllDevicesDb = async (searchParams = {}) => {
const { whereConditions, queryParams } = pool.buildFilterQuery([
{ column: "d.device_name", param: searchParams.name, type: "string" },
{ column: "d.device_code", param: searchParams.code, type: "string" },
{ column: "d.device_location", param: searchParams.location, type: "string" },
{ column: "b.brand_name", param: searchParams.brand, type: "string" },
]);
const whereClause = whereConditions.length
? `AND ${whereConditions.join(" AND ")}`
: "";
const queryText = `
SELECT d.*, b.brand_name
FROM m_device d
LEFT JOIN m_brands b ON d.brand_id = b.brand_id
WHERE d.deleted_at IS NULL ${whereClause}
ORDER BY d.device_id ASC
`;
const result = await pool.query(queryText, queryParams);
return result.recordset;
};
const getDeviceByIdDb = async (id) => {
const queryText = `
SELECT d.*, b.brand_name
FROM m_device d
LEFT JOIN m_brands b ON d.brand_id = b.brand_id
WHERE d.device_id = $1 AND d.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset[0];
};
const getDeviceByCodeDb = async (code) => {
const queryText = `
SELECT d.*, b.brand_name
FROM m_device d
LEFT JOIN m_brands b ON d.brand_id = b.brand_id
WHERE d.device_code = $1 AND d.deleted_at IS NULL
`;
const result = await pool.query(queryText, [code]);
return result.recordset[0];
};
const createDeviceDb = async (data) => {
const { query: queryText, values } = pool.buildDynamicInsert("m_device", data);
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId ? await getDeviceByIdDb(insertedId) : null;
};
const updateDeviceDb = async (id, data) => {
const { query: queryText, values } = pool.buildDynamicUpdate("m_device", data, { device_id: id });
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getDeviceByIdDb(id);
};
const softDeleteDeviceDb = async (id, deletedBy) => {
const queryText = `
UPDATE m_device
SET deleted_at = GETDATE(), deleted_by = $1
WHERE device_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllDevicesDb,
getDeviceByIdDb,
getDeviceByCodeDb,
createDeviceDb,
updateDeviceDb,
softDeleteDeviceDb,
};