repair: reset brand device without sparepart

This commit is contained in:
2025-11-24 14:56:33 +07:00
parent 98a1b15669
commit 4253e29889
3 changed files with 242 additions and 227 deletions

View File

@@ -13,8 +13,6 @@ const getErrorCodesByBrandIdDb = async (brandId) => {
return result.recordset; return result.recordset;
}; };
// Create error code for brand
const createErrorCodeDb = async (brandId, data) => { const createErrorCodeDb = async (brandId, data) => {
const store = { const store = {
brand_id: brandId, brand_id: brandId,
@@ -33,7 +31,6 @@ const createErrorCodeDb = async (brandId, data) => {
return insertedId; return insertedId;
}; };
// Update error code by brand ID and error code
const updateErrorCodeDb = async (brandId, errorCode, data) => { const updateErrorCodeDb = async (brandId, errorCode, data) => {
const store = { ...data }; const store = { ...data };
const whereData = { const whereData = {
@@ -46,7 +43,6 @@ const updateErrorCodeDb = async (brandId, errorCode, data) => {
return true; return true;
}; };
// Soft delete error code by brand ID and error code
const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => { const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => {
const queryText = ` const queryText = `
UPDATE brand_code UPDATE brand_code
@@ -57,7 +53,6 @@ const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => {
return true; return true;
}; };
// Get error code by error_code_id
const getErrorCodeByIdDb = async (error_code_id) => { const getErrorCodeByIdDb = async (error_code_id) => {
const queryText = ` const queryText = `
SELECT SELECT

View File

@@ -1,4 +1,4 @@
// BrandService.js // Brand operations
const { const {
getAllBrandsDb, getAllBrandsDb,
getBrandByIdDb, getBrandByIdDb,
@@ -7,308 +7,352 @@ const {
updateBrandDb, updateBrandDb,
deleteBrandDb, deleteBrandDb,
checkBrandNameExistsDb, checkBrandNameExistsDb,
} = require('../db/brand.db'); } = require("../db/brand.db");
// Error code operations
const { const {
getErrorCodesByBrandIdDb, getErrorCodesByBrandIdDb,
createErrorCodeDb, createErrorCodeDb,
updateErrorCodeDb, updateErrorCodeDb,
deleteErrorCodeDb, deleteErrorCodeDb,
} = require('../db/brand_code.db'); } = require("../db/brand_code.db");
const {
getSparePartnsByErrorCodeIdDb,
createSparePartDb,
updateSparePartDb,
deleteSparePartDb,
} = require('../db/brand_sparepart.db');
// Solution operations
const { const {
getSolutionsByErrorCodeIdDb, getSolutionsByErrorCodeIdDb,
createSolutionDb, createSolutionDb,
updateSolutionDb, updateSolutionDb,
deleteSolutionDb, deleteSolutionDb,
} = require('../db/brand_code_solution.db'); } = require("../db/brand_code_solution.db");
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
const { getFileUploadByPathDb } = require('../db/file_uploads.db'); const { ErrorHandler } = require("../helpers/error");
const { ErrorHandler } = require('../helpers/error');
class BrandService { class BrandService {
// Get all brands
static async getAllBrands(param) { static async getAllBrands(param) {
try { try {
const results = await getAllBrandsDb(param); const results = await getAllBrandsDb(param);
results.data.map((element) => {});
return results; return results;
} catch (error) { } catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message || 'Failed to get brands'); throw new ErrorHandler(error.statusCode, error.message);
} }
} }
// Get brand by ID with complete data
static async getBrandById(id) { static async getBrandById(id) {
try { try {
const brand = await getBrandByIdDb(id); const brand = await getBrandByIdDb(id);
if (!brand) throw new ErrorHandler(404, 'Brand not found'); if (!brand) throw new ErrorHandler(404, "Brand not found");
const errorCodes = await getErrorCodesByBrandIdDb(brand.brand_id) || []; const errorCodes = await getErrorCodesByBrandIdDb(brand.brand_id);
const errorCodesWithDetails = await Promise.all( const errorCodesWithSolutions = await Promise.all(
errorCodes.map(async (errorCode) => { errorCodes.map(async (errorCode) => {
const solutions = (await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || []; const solutions = await getSolutionsByErrorCodeIdDb(
const solutionsWithFile = await Promise.all( errorCode.error_code_id
solutions.map(async (s) => { );
const solutionsWithFiles = await Promise.all(
solutions.map(async (solution) => {
let fileData = null; let fileData = null;
if (s.path_solution && s.type_solution && s.type_solution !== 'text') { // console.log('Processing solution:', {
try { // solution_id: solution.brand_code_solution_id,
fileData = await getFileUploadByPathDb(s.path_solution); // path_solution: solution.path_solution,
} catch (e) { // type_solution: solution.type_solution
fileData = null; // });
}
if (solution.path_solution && solution.type_solution !== "text") {
fileData = await getFileUploadByPathDb(solution.path_solution);
console.log("File data found:", fileData);
} }
return {
...s, const enhancedSolution = {
...solution,
file_upload_name: fileData?.file_upload_name || null, file_upload_name: fileData?.file_upload_name || null,
path_document: fileData?.path_document || null path_document: fileData?.path_document || null,
}; };
// console.log('Enhanced solution:', {
// solution_id: enhancedSolution.brand_code_solution_id,
// original_path_solution: enhancedSolution.path_solution,
// path_document: enhancedSolution.path_document,
// file_upload_name: enhancedSolution.file_upload_name
// });
return enhancedSolution;
}) })
); );
const spareparts = (await getSparePartnsByErrorCodeIdDb(errorCode.error_code_id)) || [];
return { return {
...errorCode, ...errorCode,
solution: solutionsWithFile, solution: solutionsWithFiles,
sparepart: spareparts
}; };
}) })
); );
return { return {
...brand, ...brand,
error_code: errorCodesWithDetails error_code: errorCodesWithSolutions,
}; };
} catch (error) { } catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message || 'Failed to get brand detail'); throw new ErrorHandler(error.statusCode, error.message);
} }
} }
// Create brand
static async createBrandWithFullData(data) { static async createBrandWithFullData(data) {
try { try {
if (!data || typeof data !== 'object') data = {}; if (!data || typeof data !== "object") data = {};
if (!data.brand_name) throw new ErrorHandler(400, 'brand_name is required'); if (data.brand_name) {
const exists = await checkBrandNameExistsDb(data.brand_name); const brandExists = await checkBrandNameExistsDb(data.brand_name);
if (exists) throw new ErrorHandler(400, 'Brand name already exists'); if (brandExists) {
throw new ErrorHandler(400, "Brand name already exists");
if (!Array.isArray(data.error_code) || data.error_code.length === 0) { }
throw new ErrorHandler(400, 'Brand must have at least 1 error code with solution');
} }
for (const ec of data.error_code) { if (
if (!Array.isArray(ec.solution) || ec.solution.length === 0) { !data.error_code ||
throw new ErrorHandler(400, `Error code ${ec.error_code} must have at least 1 solution`); !Array.isArray(data.error_code) ||
data.error_code.length === 0
) {
throw new ErrorHandler(
400,
"Brand must have at least 1 error code with solution"
);
}
for (const errorCode of data.error_code) {
if (
!errorCode.solution ||
!Array.isArray(errorCode.solution) ||
errorCode.solution.length === 0
) {
throw new ErrorHandler(
400,
`Error code ${errorCode.error_code} must have at least 1 solution`
);
} }
} }
const brandData = { const brandData = {
brand_name: data.brand_name, brand_name: data.brand_name,
brand_type: data.brand_type || null, brand_type: data.brand_type,
brand_manufacture: data.brand_manufacture || null, brand_manufacture: data.brand_manufacture,
brand_model: data.brand_model || null, brand_model: data.brand_model,
is_active: data.is_active, is_active: data.is_active,
created_by: data.created_by || null created_by: data.created_by,
}; };
const createdBrand = await createBrandDb(brandData); const createdBrand = await createBrandDb(brandData);
if (!createdBrand || !createdBrand.brand_id) { if (!createdBrand) {
throw new Error('Failed to create brand'); throw new Error("Failed to create brand");
} }
const brandId = createdBrand.brand_id; const brandId = createdBrand.brand_id;
for (const ec of data.error_code) { for (const errorCodeData of data.error_code) {
const errorCodePayload = { const errorId = await createErrorCodeDb(brandId, {
error_code: ec.error_code, error_code: errorCodeData.error_code,
error_code_name: ec.error_code_name || null, error_code_name: errorCodeData.error_code_name,
error_code_description: ec.error_code_description || null, error_code_description: errorCodeData.error_code_description,
error_code_color: ec.error_code_color || null, error_code_color: errorCodeData.error_code_color,
path_icon: ec.path_icon || null, path_icon: errorCodeData.path_icon,
is_active: ec.is_active, is_active: errorCodeData.is_active,
created_by: data.created_by || null created_by: data.created_by,
}; });
const errorId = await createErrorCodeDb(brandId, errorCodePayload);
if (!errorId) { if (!errorId) {
throw new Error('Failed to create error code'); throw new Error("Failed to create error code");
} }
// solutions // Create solutions for this error code
if (Array.isArray(ec.solution)) { if (errorCodeData.solution && Array.isArray(errorCodeData.solution)) {
for (const s of ec.solution) { for (const solutionData of errorCodeData.solution) {
const solPayload = { await createSolutionDb(errorId, {
solution_name: s.solution_name, solution_name: solutionData.solution_name,
type_solution: s.type_solution, type_solution: solutionData.type_solution,
text_solution: s.text_solution || null, text_solution: solutionData.text_solution || null,
path_solution: s.path_solution || null, path_solution: solutionData.path_solution || null,
is_active: s.is_active, is_active: solutionData.is_active,
created_by: data.created_by || null created_by: data.created_by,
}; });
await createSolutionDb(errorId, solPayload);
}
}
// spareparts
if (Array.isArray(ec.sparepart)) {
for (const sp of ec.sparepart) {
const spPayload = {
sparepart_name: sp.sparepart_name,
brand_sparepart_description: sp.brand_sparepart_description || null,
path_foto: sp.path_foto || null,
is_active: sp.is_active,
created_by: data.created_by || null
};
await createSparePartDb(errorId, spPayload);
} }
} }
} }
return await this.getBrandById(brandId); return await this.getBrandById(brandId);
} catch (error) { } catch (error) {
if (error instanceof ErrorHandler) throw error; throw new ErrorHandler(500, `Bulk insert failed: ${error.message}`);
throw new ErrorHandler(500, error.message || 'Create brand failed');
} }
} }
// Soft delete brand by ID
static async deleteBrand(id, userId) {
try {
const brandExist = await getBrandByIdDb(id);
if (!brandExist) {
throw new ErrorHandler(404, "Brand not found");
}
const result = await deleteBrandDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
// Update brand
static async updateBrandWithFullData(id, data) { static async updateBrandWithFullData(id, data) {
try { try {
const existingBrand = await getBrandByIdDb(id); const existingBrand = await getBrandByIdDb(id);
if (!existingBrand) throw new ErrorHandler(404, 'Brand not found'); if (!existingBrand) throw new ErrorHandler(404, "Brand not found");
if (data.brand_name && data.brand_name !== existingBrand.brand_name) { if (data.brand_name && data.brand_name !== existingBrand.brand_name) {
const brandExists = await checkBrandNameExistsDb(data.brand_name, id); const brandExists = await checkBrandNameExistsDb(data.brand_name, id);
if (brandExists) throw new ErrorHandler(400, 'Brand name already exists'); if (brandExists) {
throw new ErrorHandler(400, "Brand name already exists");
}
} }
const brandUpdatePayload = { const brandData = {
brand_name: data.brand_name ?? existingBrand.brand_name, brand_name: data.brand_name,
brand_type: data.brand_type ?? existingBrand.brand_type, brand_type: data.brand_type,
brand_manufacture: data.brand_manufacture ?? existingBrand.brand_manufacture, brand_manufacture: data.brand_manufacture,
brand_model: data.brand_model ?? existingBrand.brand_model, brand_model: data.brand_model,
is_active: typeof data.is_active === 'boolean' ? data.is_active : existingBrand.is_active, is_active: data.is_active,
updated_by: data.updated_by || null updated_by: data.updated_by,
}; };
await updateBrandDb(existingBrand.brand_name, brandUpdatePayload);
if (!Array.isArray(data.error_code)) { await updateBrandDb(existingBrand.brand_name, brandData);
return await this.getBrandById(id);
}
const existingErrorCodes = await getErrorCodesByBrandIdDb(id) || []; if (data.error_code && Array.isArray(data.error_code)) {
const incomingErrorCodes = data.error_code.map(ec => ec.error_code); const existingErrorCodes = await getErrorCodesByBrandIdDb(id);
const incomingErrorCodes = data.error_code.map((ec) => ec.error_code);
for (const ec of data.error_code) { // Create/update/delete error codes
const existingEC = existingErrorCodes.find(e => e.error_code === ec.error_code); for (const errorCodeData of data.error_code) {
let errorId = null; // Check if error code already exists
const existingEC = existingErrorCodes.find(
(ec) => ec.error_code === errorCodeData.error_code
);
if (existingEC) { if (existingEC) {
const updatePayload = { // Update existing error code using separate db function
error_code_name: ec.error_code_name ?? existingEC.error_code_name, await updateErrorCodeDb(
error_code_description: ec.error_code_description ?? existingEC.error_code_description, existingEC.brand_id,
error_code_color: ec.error_code_color ?? existingEC.error_code_color, existingEC.error_code,
path_icon: ec.path_icon ?? existingEC.path_icon, {
is_active: existingEC.is_active, error_code_name: errorCodeData.error_code_name,
updated_by: data.updated_by || null error_code_description: errorCodeData.error_code_description,
}; error_code_color: errorCodeData.error_code_color,
await updateErrorCodeDb(existingEC.brand_id, existingEC.error_code, updatePayload); path_icon: errorCodeData.path_icon,
errorId = existingEC.error_code_id; is_active: errorCodeData.is_active,
} else { updated_by: data.updated_by,
const createPayload = { }
error_code: ec.error_code, );
error_code_name: ec.error_code_name || null,
error_code_description: ec.error_code_description || null,
error_code_color: ec.error_code_color || null,
path_icon: ec.path_icon || null,
is_active: ec.is_active,
created_by: data.updated_by || null
};
errorId = await createErrorCodeDb(id, createPayload);
}
if (!errorId) throw new Error(`Failed to create/update error code ${ec.error_code}`); if (
errorCodeData.solution &&
Array.isArray(errorCodeData.solution)
) {
const existingSolutions = await getSolutionsByErrorCodeIdDb(
existingEC.error_code_id
);
const incomingSolutionNames = errorCodeData.solution.map(
(s) => s.solution_name
);
const existingSolutions = await getSolutionsByErrorCodeIdDb(errorId) || []; // Update or create solutions
const incomingSolutionNames = (ec.solution || []).map(s => s.solution_name); for (const solutionData of errorCodeData.solution) {
const existingSolution = existingSolutions.find(
(s) => s.solution_name === solutionData.solution_name
);
for (const s of (ec.solution || [])) { if (existingSolution) {
const existsSolution = existingSolutions.find(es => es.solution_name === s.solution_name); // Update existing solution
const solPayload = { await updateSolutionDb(
solution_name: s.solution_name, existingSolution.brand_code_solution_id,
type_solution: s.type_solution, {
text_solution: s.text_solution || null, solution_name: solutionData.solution_name,
path_solution: s.path_solution || null, type_solution: solutionData.type_solution,
is_active: s.is_active, text_solution: solutionData.text_solution || null,
updated_by: data.updated_by || null, path_solution: solutionData.path_solution || null,
created_by: data.updated_by || null is_active: solutionData.is_active,
}; updated_by: data.updated_by,
if (existsSolution) { }
await updateSolutionDb(existsSolution.brand_code_solution_id, solPayload); );
} else {
// Create new solution
await createSolutionDb(existingEC.error_code_id, {
solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution,
text_solution: solutionData.text_solution || null,
path_solution: solutionData.path_solution || null,
is_active: solutionData.is_active,
created_by: data.updated_by,
});
}
}
// Delete solutions that are not in the incoming request
for (const existingSolution of existingSolutions) {
if (
!incomingSolutionNames.includes(
existingSolution.solution_name
)
) {
await deleteSolutionDb(
existingSolution.brand_code_solution_id,
data.updated_by
);
}
}
}
} else { } else {
await createSolutionDb(errorId, solPayload); const errorId = await createErrorCodeDb(id, {
error_code: errorCodeData.error_code,
error_code_name: errorCodeData.error_code_name,
error_code_description: errorCodeData.error_code_description,
error_code_color: errorCodeData.error_code_color,
path_icon: errorCodeData.path_icon,
is_active: errorCodeData.is_active,
created_by: data.updated_by,
});
if (
errorCodeData.solution &&
Array.isArray(errorCodeData.solution)
) {
for (const solutionData of errorCodeData.solution) {
await createSolutionDb(errorId, {
solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution,
text_solution: solutionData.text_solution || null,
path_solution: solutionData.path_solution || null,
is_active: solutionData.is_active,
created_by: data.updated_by,
});
}
}
} }
} }
for (const es of existingSolutions) { for (const existingEC of existingErrorCodes) {
if (!incomingSolutionNames.includes(es.solution_name)) { if (!incomingErrorCodes.includes(existingEC.error_code)) {
await deleteSolutionDb(es.brand_code_solution_id, data.updated_by); await deleteErrorCodeDb(id, existingEC.error_code, data.updated_by);
} }
} }
const existingSpareparts = await getSparePartnsByErrorCodeIdDb(errorId) || [];
const incomingSparepartNames = (ec.sparepart || []).map(sp => sp.sparepart_name);
for (const sp of (ec.sparepart || [])) {
const existsSP = existingSpareparts.find(e => e.sparepart_name === sp.sparepart_name);
const spPayload = {
sparepart_name: sp.sparepart_name,
brand_sparepart_description: sp.brand_sparepart_description || null,
path_foto: sp.path_foto || null,
is_active: sp.is_active,
updated_by: data.updated_by || null,
created_by: data.updated_by || null
};
if (existsSP) {
await updateSparePartDb(existsSP.brand_sparepart_id, spPayload);
} else {
await createSparePartDb(errorId, spPayload);
}
}
for (const es of existingSpareparts) {
if (!incomingSparepartNames.includes(es.sparepart_name)) {
await deleteSparePartDb(es.brand_sparepart_id, data.updated_by);
}
}
}
for (const ec of existingErrorCodes) {
if (!incomingErrorCodes.includes(ec.error_code)) {
await deleteErrorCodeDb(id, ec.error_code, data.updated_by);
}
} }
return await this.getBrandById(id); return await this.getBrandById(id);
} catch (error) { } catch (error) {
if (error instanceof ErrorHandler) throw error; throw new ErrorHandler(500, `Update failed: ${error.message}`);
throw new ErrorHandler(500, `Update failed: ${error.message || 'unknown error'}`);
}
}
static async deleteBrand(id, userId) {
try {
const brandExist = await getBrandByIdDb(id);
if (!brandExist) throw new ErrorHandler(404, 'Brand not found');
const result = await deleteBrandDb(id, userId);
return result;
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message || 'Delete failed');
} }
} }
} }

View File

@@ -42,18 +42,6 @@ const insertBrandSchema = Joi.object({
) )
.min(1) .min(1)
.required(), .required(),
sparepart: Joi.array()
.items(
Joi.object({
sparepart_name: Joi.string().max(100).optional(),
brand_sparepart_description: Joi.string()
.max(255)
.optional(),
path_foto: Joi.string().optional().allow(""),
is_active: Joi.boolean().required(),
})
)
.optional(),
}) })
) )
.min(1) .min(1)
@@ -100,18 +88,6 @@ const updateBrandSchema = Joi.object({
) )
.min(1) .min(1)
.required(), .required(),
sparepart: Joi.array()
.items(
Joi.object({
sparepart_name: Joi.string().max(100).optional(),
brand_sparepart_description: Joi.string()
.max(255)
.optional(),
path_foto: Joi.string().optional().allow(""),
is_active: Joi.boolean().required(),
})
)
.optional(),
}) })
) )
.optional(), .optional(),