diff --git a/db/device.db.js b/db/device.db.js new file mode 100644 index 0000000..b92b754 --- /dev/null +++ b/db/device.db.js @@ -0,0 +1,76 @@ +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; +}; + +// 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, +};