97 lines
2.3 KiB
JavaScript
97 lines
2.3 KiB
JavaScript
const pool = require("../config");
|
|
|
|
// Get all devices
|
|
const getAllDevicesDb = async () => {
|
|
const queryText = `
|
|
SELECT *
|
|
FROM m_device
|
|
WHERE deleted_at IS NULL
|
|
ORDER BY device_id ASC
|
|
`;
|
|
const result = await pool.query(queryText);
|
|
return result.recordset;
|
|
};
|
|
|
|
// Search devices by keyword
|
|
const searchDevicesDb = async (keyword) => {
|
|
const queryText = `
|
|
SELECT *
|
|
FROM m_device
|
|
WHERE deleted_at IS NULL
|
|
AND (
|
|
device_name LIKE '%' + $1 + '%'
|
|
OR device_code LIKE '%' + $1 + '%'
|
|
OR device_location LIKE '%' + $1 + '%'
|
|
OR ip_address LIKE '%' + $1 + '%'
|
|
OR device_description LIKE '%' + $1 + '%'
|
|
)
|
|
ORDER BY device_id ASC
|
|
`;
|
|
const result = await pool.query(queryText, [keyword]);
|
|
return result.recordset;
|
|
};
|
|
|
|
// Get device by ID
|
|
const getDeviceByIdDb = async (id) => {
|
|
const queryText = `
|
|
SELECT *
|
|
FROM m_device
|
|
WHERE device_id = $1
|
|
AND deleted_at IS NULL
|
|
`;
|
|
const result = await pool.query(queryText, [id]);
|
|
return result.recordset[0];
|
|
};
|
|
|
|
// Get device by device_code
|
|
const getDeviceByCodeDb = async (code) => {
|
|
const queryText = `
|
|
SELECT *
|
|
FROM m_device
|
|
WHERE device_code = $1
|
|
AND deleted_at IS NULL
|
|
`;
|
|
const result = await pool.query(queryText, [code]);
|
|
return result.recordset[0];
|
|
};
|
|
|
|
// Create device
|
|
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;
|
|
if (!insertedId) return null;
|
|
|
|
return getDeviceByIdDb(insertedId);
|
|
};
|
|
|
|
// Update device
|
|
const updateDeviceDb = async (id, data) => {
|
|
const { query: queryText, values } = pool.buildDynamicUpdate("m_device", data, { device_id: id });
|
|
await pool.query(queryText, values);
|
|
return getDeviceByIdDb(id);
|
|
};
|
|
|
|
// Soft delete device
|
|
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,
|
|
searchDevicesDb,
|
|
};
|