Compare commits

...

4 Commits

Author SHA1 Message Date
afebb64e47 dummy pdf 2025-10-26 18:27:06 +07:00
cd77fda212 fix: file uploads api 2025-10-26 18:26:58 +07:00
a3b7f79546 update verify token 2025-10-26 18:26:38 +07:00
409e2d3750 fix: brand api 2025-10-26 18:26:22 +07:00
10 changed files with 138 additions and 197 deletions

View File

@@ -4,7 +4,6 @@ const { createFileUploadDb } = require('../db/file_uploads.db');
const { const {
insertBrandSchema, insertBrandSchema,
updateBrandSchema, updateBrandSchema,
uploadSolutionSchema
} = require('../validate/brand.schema'); } = require('../validate/brand.schema');
class BrandController { class BrandController {
@@ -23,6 +22,9 @@ class BrandController {
const { id } = req.params; const { id } = req.params;
const results = await BrandService.getBrandById(id); const results = await BrandService.getBrandById(id);
// console.log('Brand response structure:', JSON.stringify(results, null, 2));
const response = await setResponse(results, 'Brand found'); const response = await setResponse(results, 'Brand found');
res.status(response.statusCode).json(response); res.status(response.statusCode).json(response);
@@ -98,14 +100,8 @@ class BrandController {
// Soft delete brand by ID // Soft delete brand by ID
static async delete(req, res) { static async delete(req, res) {
const { id } = req.params; const { id } = req.params;
// Get brand by ID first to get name for deletion
const brand = await BrandService.getBrandById(id);
if (!brand) {
const response = await setResponse([], 'Brand not found', 404);
return res.status(response.statusCode).json(response);
}
const results = await BrandService.deleteBrand(brand.brand_name, req.user.user_id); const results = await BrandService.deleteBrand(id, req.user.user_id);
const response = await setResponse(results, 'Brand deleted successfully'); const response = await setResponse(results, 'Brand deleted successfully');
res.status(response.statusCode).json(response); res.status(response.statusCode).json(response);

View File

@@ -5,9 +5,6 @@ const {
createFileUploadDb, createFileUploadDb,
deleteFileUploadByPathDb, deleteFileUploadByPathDb,
} = require("../db/file_uploads.db"); } = require("../db/file_uploads.db");
const {
createSolutionDb,
} = require("../db/brand.db");
const uploadFile = async (req, res) => { const uploadFile = async (req, res) => {
try { try {
@@ -23,7 +20,6 @@ const uploadFile = async (req, res) => {
const pathDocument = `${folder}/${file.filename}`; const pathDocument = `${folder}/${file.filename}`;
// Insert ke DB via DB layer
const fileData = { const fileData = {
file_upload_name: file.originalname, file_upload_name: file.originalname,
path_document: pathDocument, path_document: pathDocument,
@@ -34,7 +30,11 @@ const uploadFile = async (req, res) => {
await createFileUploadDb(fileData); await createFileUploadDb(fileData);
const response = await setResponse( const response = await setResponse(
{ name: file.originalname, path: pathDocument }, {
file_upload_name: file.originalname,
path_document: pathDocument,
path_solution: pathDocument
},
"File berhasil diunggah" "File berhasil diunggah"
); );
res.status(200).json(response); res.status(200).json(response);
@@ -44,27 +44,54 @@ const uploadFile = async (req, res) => {
} }
}; };
const getFile = (folder) => async (req, res) => {
const getFileByPath = async (req, res) => {
try { try {
const { filename } = req.params; const { folder, filename } = req.params;
const filePath = path.join(__dirname, "../uploads", folder, filename);
// Decode filename from URL encoding
const decodedFilename = decodeURIComponent(filename);
const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);
console.log('getFileByPath Debug:', {
folder,
originalFilename: filename,
decodedFilename,
filePath
});
if (!fs.existsSync(filePath)) { if (!fs.existsSync(filePath)) {
console.log('File not found at path:', filePath);
// try {
// const folderPath = path.join(__dirname, "../uploads", folder);
// const availableFiles = fs.readdirSync(folderPath);
// console.log('Available files in', folderPath, ':', availableFiles);
// } catch (listError) {
// console.log('Could not list files in folder:', listError.message);
// }
const response = await setResponse([], "File tidak ditemukan", 404); const response = await setResponse([], "File tidak ditemukan", 404);
return res.status(404).json(response); return res.status(404).json(response);
} }
res.sendFile(filePath); res.sendFile(filePath);
} catch (error) { } catch (error) {
console.error('getFileByPath Error:', error);
const response = await setResponse([], error.message, 500); const response = await setResponse([], error.message, 500);
res.status(500).json(response); res.status(500).json(response);
} }
}; };
const deleteFile = (folder) => async (req, res) => { const deleteFileByPath = async (req, res) => {
try { try {
const { filename } = req.params; const { folder, filename } = req.params;
const filePath = path.join(__dirname, "../uploads", folder, filename);
// Decode filename from URL encoding
const decodedFilename = decodeURIComponent(filename);
const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);
if (!fs.existsSync(filePath)) { if (!fs.existsSync(filePath)) {
const response = await setResponse([], "File tidak ditemukan", 404); const response = await setResponse([], "File tidak ditemukan", 404);
@@ -74,8 +101,8 @@ const deleteFile = (folder) => async (req, res) => {
// Delete physical file // Delete physical file
fs.unlinkSync(filePath); fs.unlinkSync(filePath);
const pathDocument = `${folder}/${filename}`; const pathDocument = `${folder}/${decodedFilename}`;
const deletedBy = req.user?.user_id || null; const deletedBy = req.user?.user_id || null;
await deleteFileUploadByPathDb(pathDocument, deletedBy); await deleteFileUploadByPathDb(pathDocument, deletedBy);
const response = await setResponse([], "File berhasil dihapus"); const response = await setResponse([], "File berhasil dihapus");
@@ -86,66 +113,8 @@ const deleteFile = (folder) => async (req, res) => {
} }
}; };
const uploadSolutionFile = async (req, res) => {
try {
if (!req.file) {
const response = await setResponse([], "Tidak ada file yang diunggah", 400);
return res.status(400).json(response);
}
const { error_code_id, solution_name } = req.body;
if (!error_code_id || !solution_name) {
const response = await setResponse([], "error_code_id dan solution_name harus diisi", 400);
return res.status(400).json(response);
}
const file = req.file;
const ext = path.extname(file.originalname).toLowerCase();
const typeDoc = ext === ".pdf" ? "PDF" : "IMAGE";
const folder = typeDoc === "PDF" ? "pdf" : "images";
const pathDocument = `${folder}/${file.filename}`;
const fileData = {
file_upload_name: file.originalname,
path_document: pathDocument,
type_document: typeDoc,
createdBy: req.user?.user_id || null,
};
await createFileUploadDb(fileData);
const solutionData = {
solution_name: solution_name,
type_solution: typeDoc.toLowerCase(),
path_solution: pathDocument,
is_active: true,
created_by: req.user?.user_id || null
};
const solutionId = await createSolutionDb(error_code_id, solutionData);
const response = await setResponse(
{
solution_id: solutionId,
solution_name: solution_name,
error_code_id: error_code_id,
file_name: file.originalname,
file_path: pathDocument,
file_type: typeDoc.toLowerCase()
},
"Solution file berhasil diunggah"
);
res.status(200).json(response);
} catch (error) {
const response = await setResponse([], error.message, 500);
res.status(500).json(response);
}
};
module.exports = { module.exports = {
uploadFile, uploadFile,
uploadSolutionFile, getFileByPath,
getFile, deleteFileByPath,
deleteFile,
}; };

View File

@@ -102,14 +102,14 @@ const updateBrandDb = async (brandName, data) => {
return getBrandByNameDb(brandName); return getBrandByNameDb(brandName);
}; };
// Soft delete brand by name // Soft delete brand
const deleteBrandDb = async (brandName, deletedBy) => { const deleteBrandDb = async (id, deletedBy) => {
const queryText = ` const queryText = `
UPDATE m_brands UPDATE m_brands
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1 SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE brand_name = $2 AND deleted_at IS NULL WHERE brand_id = $2 AND deleted_at IS NULL
`; `;
await pool.query(queryText, [deletedBy, brandName]); await pool.query(queryText, [deletedBy, id]);
return true; return true;
}; };
@@ -131,33 +131,6 @@ const checkBrandNameExistsDb = async (brandName, excludeId = null) => {
return result.recordset.length > 0; return result.recordset.length > 0;
}; };
// Get brand with error codes count
const getBrandsWithErrorCodeCountDb = async (searchParams = {}) => {
let queryParams = [];
const queryText = `
SELECT
a.brand_id,
a.brand_name,
a.brand_type,
a.brand_manufacture,
a.brand_model,
a.brand_code,
a.is_active,
a.created_at,
COUNT(bc.error_code_id) as error_code_count
FROM m_brands a
LEFT JOIN brand_code bc ON a.brand_id = bc.brand_id AND bc.deleted_at IS NULL
WHERE a.deleted_at IS NULL
GROUP BY
a.brand_id, a.brand_name, a.brand_type, a.brand_manufacture,
a.brand_model, a.brand_code, a.is_active, a.created_at
ORDER BY a.brand_name
`;
const result = await pool.query(queryText, queryParams);
return result.recordset;
};
module.exports = { module.exports = {
getAllBrandsDb, getAllBrandsDb,
@@ -167,5 +140,4 @@ module.exports = {
updateBrandDb, updateBrandDb,
deleteBrandDb, deleteBrandDb,
checkBrandNameExistsDb, checkBrandNameExistsDb,
getBrandsWithErrorCodeCountDb,
}; };

View File

@@ -13,17 +13,6 @@ const getErrorCodesByBrandIdDb = async (brandId) => {
return result.recordset; 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 // Create error code for brand
const createErrorCodeDb = async (brandId, data) => { const createErrorCodeDb = async (brandId, data) => {
@@ -66,29 +55,10 @@ const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => {
return true; 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 = { module.exports = {
getErrorCodesByBrandIdDb, getErrorCodesByBrandIdDb,
getErrorCodeByBrandIdAndCodeDb,
createErrorCodeDb, createErrorCodeDb,
updateErrorCodeDb, updateErrorCodeDb,
deleteErrorCodeDb, deleteErrorCodeDb,
checkErrorCodeExistsDb,
}; };

View File

@@ -52,22 +52,9 @@ const deleteSolutionDb = async (solutionId, deletedBy) => {
return true; return true;
}; };
// Get solution by ID
const getSolutionByIdDb = async (solutionId) => {
const queryText = `
SELECT
a.*
FROM brand_code_solution a
WHERE a.brand_code_solution_id = $1 AND a.deleted_at IS NULL
`;
const result = await pool.query(queryText, [solutionId]);
return result.recordset[0];
};
module.exports = { module.exports = {
getSolutionsByErrorCodeIdDb, getSolutionsByErrorCodeIdDb,
createSolutionDb, createSolutionDb,
updateSolutionDb, updateSolutionDb,
deleteSolutionDb, deleteSolutionDb,
getSolutionByIdDb,
}; };

View File

@@ -19,10 +19,15 @@ function verifyAccessToken(req, res, next) {
if (!token) { if (!token) {
const authHeader = req.headers.authorization; const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer')) { if (authHeader && authHeader.startsWith('Bearer')) {
throw new ErrorHandler(401, 'Access Token is required'); token = authHeader.split(' ')[1];
} else {
token = req.query.token;
} }
token = authHeader.split(' ')[1]; }
if (!token) {
throw new ErrorHandler(401, 'Access Token is required');
} }
const decoded = JWTService.verifyToken(token); const decoded = JWTService.verifyToken(token);

View File

@@ -4,18 +4,14 @@ const verifyToken = require("../middleware/verifyToken");
const verifyAccess = require("../middleware/verifyAccess"); const verifyAccess = require("../middleware/verifyAccess");
const { const {
uploadFile, uploadFile,
getFile, getFileByPath,
deleteFile, deleteFileByPath,
} = require("../controllers/file_uploads.controller"); } = require("../controllers/file_uploads.controller");
router.post("/", verifyToken.verifyAccessToken, verifyAccess(), upload.single("file"), uploadFile); router.post("/", verifyToken.verifyAccessToken, verifyAccess(), upload.single("file"), uploadFile);
router.route("/pdf/:filename") router.route("/:folder/:filename")
.get(verifyToken.verifyAccessToken, getFile("pdf")) .get(verifyToken.verifyAccessToken, getFileByPath)
.delete(verifyToken.verifyAccessToken, verifyAccess(), deleteFile("pdf")); .delete(verifyToken.verifyAccessToken, verifyAccess(), deleteFileByPath);
router.route("/images/:filename")
.get(verifyToken.verifyAccessToken, getFile("images"))
.delete(verifyToken.verifyAccessToken, verifyAccess(), deleteFile("images"));
module.exports = router; module.exports = router;

View File

@@ -15,7 +15,6 @@ const {
createErrorCodeDb, createErrorCodeDb,
updateErrorCodeDb, updateErrorCodeDb,
deleteErrorCodeDb, deleteErrorCodeDb,
checkErrorCodeExistsDb,
} = require('../db/brand_code.db'); } = require('../db/brand_code.db');
// Solution operations // Solution operations
@@ -58,15 +57,31 @@ class BrandService {
const solutionsWithFiles = await Promise.all( const solutionsWithFiles = await Promise.all(
solutions.map(async (solution) => { solutions.map(async (solution) => {
let fileData = null; let fileData = null;
// console.log('Processing solution:', {
// solution_id: solution.brand_code_solution_id,
// path_solution: solution.path_solution,
// type_solution: solution.type_solution
// });
if (solution.path_solution && solution.type_solution !== 'text') { if (solution.path_solution && solution.type_solution !== 'text') {
fileData = await getFileUploadByPathDb(solution.path_solution); fileData = await getFileUploadByPathDb(solution.path_solution);
console.log('File data found:', fileData);
} }
return { const enhancedSolution = {
...solution, ...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;
}) })
); );
@@ -125,7 +140,6 @@ class BrandService {
const brandId = createdBrand.brand_id; const brandId = createdBrand.brand_id;
for (const errorCodeData of data.error_code) { for (const errorCodeData of data.error_code) {
// Use separate db function for error codes
const errorId = await createErrorCodeDb(brandId, { const errorId = await createErrorCodeDb(brandId, {
error_code: errorCodeData.error_code, error_code: errorCodeData.error_code,
error_code_name: errorCodeData.error_code_name, error_code_name: errorCodeData.error_code_name,
@@ -141,7 +155,6 @@ class BrandService {
// Create solutions for this error code // Create solutions for this error code
if (errorCodeData.solution && Array.isArray(errorCodeData.solution)) { if (errorCodeData.solution && Array.isArray(errorCodeData.solution)) {
for (const solutionData of errorCodeData.solution) { for (const solutionData of errorCodeData.solution) {
// Use separate db function for solutions
await createSolutionDb(errorId, { await createSolutionDb(errorId, {
solution_name: solutionData.solution_name, solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution, type_solution: solutionData.type_solution,
@@ -161,17 +174,16 @@ class BrandService {
} }
} }
// Soft delete brand by name (convert to ID for database operation) // Soft delete brand by ID
static async deleteBrand(brandName, userId) { static async deleteBrand(id, userId) {
try { try {
// Get brand by name first to get ID const brandExist = await getBrandByIdDb(id);
const brandExist = await getBrandByNameDb(brandName);
if (!brandExist) { if (!brandExist) {
throw new ErrorHandler(404, 'Brand not found'); throw new ErrorHandler(404, 'Brand not found');
} }
const result = await deleteBrandDb(brandName, userId); const result = await deleteBrandDb(id, userId);
return result; return result;
} catch (error) { } catch (error) {
@@ -185,7 +197,6 @@ class BrandService {
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');
// Check if brand name already exists (excluding current brand)
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) { if (brandExists) {
@@ -206,6 +217,7 @@ class BrandService {
if (data.error_code && Array.isArray(data.error_code)) { if (data.error_code && Array.isArray(data.error_code)) {
const existingErrorCodes = await getErrorCodesByBrandIdDb(id); const existingErrorCodes = await getErrorCodesByBrandIdDb(id);
const incomingErrorCodes = data.error_code.map(ec => ec.error_code);
// Create/update/delete error codes // Create/update/delete error codes
for (const errorCodeData of data.error_code) { for (const errorCodeData of data.error_code) {
@@ -222,15 +234,41 @@ class BrandService {
}); });
if (errorCodeData.solution && Array.isArray(errorCodeData.solution)) { if (errorCodeData.solution && Array.isArray(errorCodeData.solution)) {
const existingSolutions = await getSolutionsByErrorCodeIdDb(existingEC.error_code_id);
const incomingSolutionNames = errorCodeData.solution.map(s => s.solution_name);
// Update or create solutions
for (const solutionData of errorCodeData.solution) { for (const solutionData of errorCodeData.solution) {
await createSolutionDb(existingEC.error_code_id, { const existingSolution = existingSolutions.find(s => s.solution_name === solutionData.solution_name);
solution_name: solutionData.solution_name,
type_solution: solutionData.type_solution, if (existingSolution) {
text_solution: solutionData.text_solution || null, // Update existing solution
path_solution: solutionData.path_solution || null, await updateSolutionDb(existingSolution.brand_code_solution_id, {
is_active: solutionData.is_active, solution_name: solutionData.solution_name,
created_by: data.updated_by type_solution: solutionData.type_solution,
}); text_solution: solutionData.text_solution || null,
path_solution: solutionData.path_solution || null,
is_active: solutionData.is_active,
updated_by: data.updated_by
});
} 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 {
@@ -256,6 +294,12 @@ class BrandService {
} }
} }
} }
for (const existingEC of existingErrorCodes) {
if (!incomingErrorCodes.includes(existingEC.error_code)) {
await deleteErrorCodeDb(id, existingEC.error_code, data.updated_by);
}
}
} }
return await this.getBrandById(id); return await this.getBrandById(id);

Binary file not shown.

View File

@@ -5,17 +5,18 @@ const Joi = require("joi");
// ======================== // ========================
const insertBrandSchema = Joi.object({ const insertBrandSchema = Joi.object({
brand_name: Joi.string().max(100).required(), brand_name: Joi.string().max(100).required(),
brand_type: Joi.string().max(50).optional(), brand_type: Joi.string().max(50).optional().allow(''),
brand_manufacture: Joi.string().max(100).optional(), brand_manufacture: Joi.string().max(100).required(),
brand_model: Joi.string().max(100).optional(), brand_model: Joi.string().max(100).optional().allow(''),
is_active: Joi.boolean().required(), is_active: Joi.boolean().required(),
description: Joi.string().max(255).optional(), description: Joi.string().max(255).optional().allow(''),
error_code: Joi.array().items( error_code: Joi.array().items(
Joi.object({ Joi.object({
error_code: Joi.string().max(100).required(), error_code: Joi.string().max(100).required(),
error_code_name: Joi.string().max(100).required(), error_code_name: Joi.string().max(100).required(),
error_code_description: Joi.string().optional(), error_code_description: Joi.string().optional().allow(''),
is_active: Joi.boolean().required(), is_active: Joi.boolean().required(),
what_action_to_take: Joi.string().optional().allow(''),
solution: Joi.array().items( solution: Joi.array().items(
Joi.object({ Joi.object({
solution_name: Joi.string().max(100).required(), solution_name: Joi.string().max(100).required(),
@@ -40,17 +41,18 @@ const insertBrandSchema = Joi.object({
// Update Brand Validation // Update Brand Validation
const updateBrandSchema = Joi.object({ const updateBrandSchema = Joi.object({
brand_name: Joi.string().max(100).required(), brand_name: Joi.string().max(100).required(),
brand_type: Joi.string().max(50).optional(), brand_type: Joi.string().max(50).optional().allow(''),
brand_manufacture: Joi.string().max(100).optional(), brand_manufacture: Joi.string().max(100).required(),
brand_model: Joi.string().max(100).optional(), brand_model: Joi.string().max(100).optional().allow(''),
is_active: Joi.boolean().required(), is_active: Joi.boolean().required(),
description: Joi.string().max(255).optional(), description: Joi.string().max(255).optional().allow(''),
error_code: Joi.array().items( error_code: Joi.array().items(
Joi.object({ Joi.object({
error_code: Joi.string().max(100).required(), error_code: Joi.string().max(100).required(),
error_code_name: Joi.string().max(100).required(), error_code_name: Joi.string().max(100).required(),
error_code_description: Joi.string().optional(), error_code_description: Joi.string().optional().allow(''),
is_active: Joi.boolean().required(), is_active: Joi.boolean().required(),
what_action_to_take: Joi.string().optional().allow(''),
solution: Joi.array().items( solution: Joi.array().items(
Joi.object({ Joi.object({
solution_name: Joi.string().max(100).required(), solution_name: Joi.string().max(100).required(),
@@ -69,7 +71,7 @@ const updateBrandSchema = Joi.object({
}) })
).min(1).required() ).min(1).required()
}) })
).optional() ).optional()
}).min(1); }).min(1);
module.exports = { module.exports = {