update and delete item api

development
hengvisoth 8 months ago
parent 719c2388be
commit 404c516022
  1. 183
      Controller/Items.js

@ -1,34 +1,35 @@
const asyncHandler = require("../Middleware/async"); const asyncHandler = require("../Middleware/async");
const sequelize = require('sequelize') const sequelize = require("sequelize");
const DBInfo = require("../Model/Database"); const DBInfo = require("../Model/Database");
const ItemModel = require("../Model/ItemModel"); const ItemModel = require("../Model/ItemModel");
const CategoryModel = require("../Model/CategoryModel"); const CategoryModel = require("../Model/CategoryModel");
const SupplierItemModel = require("../Model/SupplierItemModel"); const SupplierItemModel = require("../Model/SupplierItemModel");
const ErrorResponse = require("../utils/ErrorResponse"); const ErrorResponse = require("../utils/ErrorResponse");
const SuccessResponse = require("../utils/SuccessResponse"); const SuccessResponse = require("../utils/SuccessResponse");
const fs = require('fs') const fs = require("fs");
const dateFormat = require("dateformat"); const dateFormat = require("dateformat");
const path = require('path'); const path = require("path");
const { log } = require("console"); const { log } = require("console");
const CategoryDetail = require("../Model/CategoryDetailModel"); const CategoryDetail = require("../Model/CategoryDetailModel");
exports.getAllItemsByStore = asyncHandler(async (req, res, next) => { exports.getAllItemsByStore = asyncHandler(async (req, res, next) => {
try { try {
let items = await ItemModel.findAll({ let items = await ItemModel.findAll({
where: { where: {
DB_CODE: req.user.DB_CODE DB_CODE: req.user.DB_CODE,
} },
}); });
console.log("DB CODE ", req.user.DB_CODE); console.log("DB CODE ", req.user.DB_CODE);
const folderPath = path.join(
process.env.ITEM_IMAGE_LOCATION,
const folderPath = path.join(process.env.ITEM_IMAGE_LOCATION, req.user.DB_CODE); req.user.DB_CODE
);
// Use Promise.all to wait for all promises to resolve // Use Promise.all to wait for all promises to resolve
items = await Promise.all(items.map(async (item) => { items = await Promise.all(
items.map(async (item) => {
let itemObject = item.get({ plain: true }); let itemObject = item.get({ plain: true });
try { try {
@ -37,7 +38,7 @@ exports.getAllItemsByStore = asyncHandler(async (req, res, next) => {
where: { where: {
ID: item.CAT_CODE, ID: item.CAT_CODE,
// DB_CODE: req.user.DB_CODE // DB_CODE: req.user.DB_CODE
} },
}); });
if (category) { if (category) {
itemObject.CAT_DESC_EN = category.DESC_EN; itemObject.CAT_DESC_EN = category.DESC_EN;
@ -54,11 +55,12 @@ exports.getAllItemsByStore = asyncHandler(async (req, res, next) => {
itemObject.ITEM_IMG = fs.existsSync(imagePath) ? imagePath : ""; itemObject.ITEM_IMG = fs.existsSync(imagePath) ? imagePath : "";
return itemObject; return itemObject;
})); })
);
res.status(200).send({ res.status(200).send({
success: true, success: true,
data: items data: items,
}); });
} catch (err) { } catch (err) {
console.error("ERROR GET ALL ITEMS", err); console.error("ERROR GET ALL ITEMS", err);
@ -68,42 +70,39 @@ exports.getAllItemsByStore = asyncHandler(async (req, res, next) => {
exports.createItemByStore = asyncHandler(async (req, res, next) => { exports.createItemByStore = asyncHandler(async (req, res, next) => {
try { try {
var date = dateFormat(new Date(), "yyyy-mm-dd HH:mm:ss");
var date = dateFormat(new Date(), "yyyy-mm-dd HH:mm:ss")
const data = JSON.parse(req.body["data"]);
const data = JSON.parse(req.body['data']); const items = data["items"];
const items = data['items']; var photo = req.file.path;
var photo = req.file.path let imageData = fs.readFileSync(req.file.path);
let imageData = fs.readFileSync(req.file.path) const itemCode = items["ITEM_CODE"];
const itemCode = items['ITEM_CODE']; const itemBarCode = items["ITEM_BCODE"];
const itemBarCode = items['ITEM_BCODE'] const itemDes = items["ITEM_DESC"];
const itemDes = items['ITEM_DESC']; const unitStock = items["UNIT_STOCK"] ?? "1";
const unitStock = items['UNIT_STOCK'] ?? '1'; const unitSale = items["UNIT_SALE"] ?? "1";
const unitSale = items['UNIT_SALE'] ?? '1'; const catCode = items["CATE_CODE"]; // CAT_CODE -> CAT_DETAIL_ID
const catCode = items['CATE_CODE']; // CAT_CODE -> CAT_DETAIL_ID const supplierCode = items["SUPP_CODE"];
const supplierCode = items['SUPP_CODE'];
const itemCost1 = items["ITEM_COST1"];
const itemCost1 = items['ITEM_COST1']; const itemPrice1 = items["ITEM_PRICE1"];
const itemPrice1 = items['ITEM_PRICE1'];
if (!itemBarCode || !itemDes || !catCode || !itemCost1 || !itemPrice1) { if (!itemBarCode || !itemDes || !catCode || !itemCost1 || !itemPrice1) {
throw ("Please provide all required fields"); throw "Please provide all required fields";
} }
// var itemCode = await generateNextItemCode(); // var itemCode = await generateNextItemCode();
const existingItem = await ItemModel.findOne({ const existingItem = await ItemModel.findOne({
where: { where: {
ITEM_CODE: itemCode, ITEM_CODE: itemCode,
DB_CODE: req.user.DB_CODE DB_CODE: req.user.DB_CODE,
} },
}); });
if (existingItem) { if (existingItem) {
throw (`ITEM_CODE ${itemCode} already exists`); throw `ITEM_CODE ${itemCode} already exists`;
} }
await ItemModel.sequelize.transaction(async (t) => { await ItemModel.sequelize.transaction(async (t) => {
const item = await ItemModel.create({ const item = await ItemModel.create({
ITEM_CODE: itemCode, ITEM_CODE: itemCode,
@ -133,7 +132,7 @@ exports.createItemByStore = asyncHandler(async (req, res, next) => {
ITEM_CUS10_KH: "", ITEM_CUS10_KH: "",
USER_UPDT: req.user.USER_NAME, USER_UPDT: req.user.USER_NAME,
DATE_UPDT: date, DATE_UPDT: date,
}) });
// add to TDITEMSP table // add to TDITEMSP table
@ -142,77 +141,121 @@ exports.createItemByStore = asyncHandler(async (req, res, next) => {
DB_CODE: req.user.DB_CODE, DB_CODE: req.user.DB_CODE,
SUPP_CODE: supplierCode, SUPP_CODE: supplierCode,
SUPP_COST: itemCost1, SUPP_COST: itemCost1,
SUPP_UNIT: "1" SUPP_UNIT: "1",
}) });
let folderPath = process.env.ITEM_IMAGE_LOCATION + "/" + req.user.DB_CODE + "/" let folderPath =
if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { process.env.ITEM_IMAGE_LOCATION + "/" + req.user.DB_CODE + "/";
if (!fs.existsSync(folderPath))
fs.mkdirSync(folderPath, {
recursive: true, recursive: true,
}) });
log("ITEM CODE ", item.ITEM_CODE) log("ITEM CODE ", item.ITEM_CODE);
fs.writeFileSync(folderPath + item.ITEM_CODE + '.jpg', imageData) fs.writeFileSync(folderPath + item.ITEM_CODE + ".jpg", imageData);
fs.unlinkSync(req.file.path) fs.unlinkSync(req.file.path);
res.send(new SuccessResponse("Operation Successful")); res.send(new SuccessResponse("Operation Successful"));
});
} catch (err) {
console.log("ERROR CREATE ITEM", err);
fs.unlinkSync(req.file.path);
return next(new ErrorResponse(err, 400));
}
});
}) exports.updateByItemCode = asyncHandler(async (req, res, next) => {
try {
const itemCode = req.params.item_code;
const updateData = req.body;
const item = await ItemModel.findOne({
where: { ITEM_CODE: itemCode, DB_CODE: req.user.DB_CODE },
});
if (!item) {
return next(new ErrorResponse("Item not found", 404));
}
await item.update(updateData);
res.status(200).send({
success: true,
data: item,
});
} catch (err) { } catch (err) {
console.log("ERROR CREATE ITEM", err) console.error("ERROR UPDATE ITEM", err);
fs.unlinkSync(req.file.path) return next(new ErrorResponse(err.message, 400));
return next(new ErrorResponse(err, 400));
} }
}) });
exports.deleteByItemCode = asyncHandler(async (req, res, next) => {
try {
const itemCode = req.params.item_code;
const item = await ItemModel.findOne({
where: { ITEM_CODE: itemCode, DB_CODE: req.user.DB_CODE },
});
if (!item) {
return next(new ErrorResponse("Item not found", 404));
}
// check user permission to delete item
await item.destroy();
res.status(200).send({
success: true,
data: {},
message: `Item with ITEM_CODE ${itemCode} deleted successfully`,
});
} catch (err) {
console.error("ERROR DELETE ITEM", err);
return next(new ErrorResponse(err.message, 400));
}
});
exports.checkIfItemExist = asyncHandler(async (req, res, next) => { exports.checkIfItemExist = asyncHandler(async (req, res, next) => {
try { try {
const item = await ItemModel.findOne({ const item = await ItemModel.findOne({
where: { where: {
ITEM_CODE: req.params.item_code, ITEM_CODE: req.params.item_code,
DB_CODE: req.user.DB_CODE DB_CODE: req.user.DB_CODE,
} },
}) });
if (!item) { if (!item) {
return next(new ErrorResponse("Item not found", 400)); return next(new ErrorResponse("Item not found", 400));
} }
res.status(200).send({ res.status(200).send({
success: true, success: true,
data: item data: item,
}) });
} catch (err) { } catch (err) {
console.log("ERROR CHECK ITEM", err) console.log("ERROR CHECK ITEM", err);
return next(new ErrorResponse(err, 400)); return next(new ErrorResponse(err, 400));
} }
} });
)
async function generateNextItemCode() { async function generateNextItemCode() {
try { try {
const lastItem = await ItemModel.findOne({ const lastItem = await ItemModel.findOne({
order: [['ITEM_CODE', 'DESC']] order: [["ITEM_CODE", "DESC"]],
}); });
console.log("LAST ITEM ", lastItem) console.log("LAST ITEM ", lastItem);
if (!lastItem) { if (!lastItem) {
return '0001'; // Starting point if no suppliers are present return "0001"; // Starting point if no suppliers are present
} }
console.log("LAST ITEM CODE ", lastItem.ITEM_CODE) console.log("LAST ITEM CODE ", lastItem.ITEM_CODE);
let nextCode = parseInt(lastItem.ITEM_CODE, 10) + 1; let nextCode = parseInt(lastItem.ITEM_CODE, 10) + 1;
console.log("NEXT CODE ", nextCode) console.log("NEXT CODE ", nextCode);
// Check if the number is less than 10000 for zero-padding // Check if the number is less than 10000 for zero-padding
if (nextCode < 10000) { if (nextCode < 10000) {
return nextCode.toString().padStart(4, '0'); return nextCode.toString().padStart(4, "0");
} else { } else {
// If it's 10000 or more, just return the number // If it's 10000 or more, just return the number
return nextCode.toString(); return nextCode.toString();
} }
} } catch (e) {
catch (e) { console.log("CATCH ERROR IN GENERATE ITEM CODE ", e);
console.log("CATCH ERROR IN GENERATE ITEM CODE ", e)
} }
} }
Loading…
Cancel
Save