const pool = require("../config"); // Get error codes by brand ID const getErrorCodesByBrandIdDb = async (brandId) => { const queryText = ` SELECT a.* FROM brand_code a WHERE a.brand_id = $1 AND a.deleted_at IS NULL ORDER BY a.error_code_id `; const result = await pool.query(queryText, [brandId]); return result.recordset; }; // Get error code by brand ID and error code const getErrorCodeByBrandIdAndCodeDb = async (brandId, errorCode) => { const queryText = ` SELECT a.* FROM brand_code a WHERE a.brand_id = $1 AND a.error_code = $2 AND a.deleted_at IS NULL `; const result = await pool.query(queryText, [brandId, errorCode]); return result.recordset[0]; }; // Create error code for brand const createErrorCodeDb = async (brandId, data) => { const store = { brand_id: brandId, error_code: data.error_code, error_code_name: data.error_code_name, error_code_description: data.error_code_description, is_active: data.is_active, created_by: data.created_by }; const { query: queryText, values } = pool.buildDynamicInsert("brand_code", store); const result = await pool.query(queryText, values); const insertedId = result.recordset[0]?.inserted_id; return insertedId; }; // Update error code by brand ID and error code const updateErrorCodeDb = async (brandId, errorCode, data) => { const store = { ...data }; const whereData = { brand_id: brandId, error_code: errorCode }; const { query: queryText, values } = pool.buildDynamicUpdate("brand_code", store, whereData); await pool.query(`${queryText} AND deleted_at IS NULL`, values); return true; }; // Soft delete error code by brand ID and error code const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => { const queryText = ` UPDATE brand_code SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1 WHERE brand_id = $2 AND error_code = $3 AND deleted_at IS NULL `; await pool.query(queryText, [deletedBy, brandId, errorCode]); return true; }; // Check if error code exists for brand const checkErrorCodeExistsDb = async (brandId, errorCode, excludeId = null) => { let queryText = ` SELECT error_code_id FROM brand_code WHERE brand_id = $1 AND error_code = $2 AND deleted_at IS NULL `; let values = [brandId, errorCode]; if (excludeId) { queryText += ` AND error_code_id != $3`; values.push(excludeId); } const result = await pool.query(queryText, values); return result.recordset.length > 0; }; module.exports = { getErrorCodesByBrandIdDb, getErrorCodeByBrandIdAndCodeDb, createErrorCodeDb, updateErrorCodeDb, deleteErrorCodeDb, checkErrorCodeExistsDb, };