const asyncHandler = require("../Middleware/async"); const sequelize = require('sequelize') const db = require('../Config/db') const SupplierModel = require('../Model/SupplierModel') const ErrorResponse = require('../utils/ErrorResponse') const fs = require('fs'); const SuccessResponse = require('../utils/SuccessResponse'); const dateFormat = require('dateformat'); exports.getAllSupplier = asyncHandler(async (req, res, next) => { try { const bodySizeInBytes = Buffer.byteLength(JSON.stringify(req.body), 'utf8'); console.log(`Body size: ${bodySizeInBytes} bytes`); const supplier = await SupplierModel.findAll({ where: { DB_CODE: req.user.DB_CODE } } ) res.status(200).send({ success: true, data: supplier }) } catch (e) { throw new ErrorResponse(e, 400) } }) exports.createSupplier = asyncHandler(async (req, res, next) => { var date = dateFormat(new Date(), "yyyy-mm-dd") const data = JSON.parse(req.body.data) // const data = (req.body); console.log("DATA", data) if (!data.ADD_NAME || !data.phoneNumber) { throw new ErrorResponse('Please provide all required fields', 400) } var photos = req.files; console.log("PHOTOS ", photos) try { // increaset the last supplier code by 1 let newSupplierCode = await generateNextSupplierCode() console.log("NEW SUPPLIER CODE : ", newSupplierCode) const supplier = await SupplierModel.create({ DB_CODE: req.user.DB_CODE, USER_CODE: req.user.USER_NAME, ADD_NAME: data.ADD_NAME, ADD_CODE: newSupplierCode, ADD_LINE_1: data.addressLine1, ADD_LINE_2: data.addressLine2 ?? "", ADD_LINE_3: data.addressLine3 ?? "", ADD_LINE_4: data.addressLine4 ?? "", ADD_LINE_5: data.addressLine5 ?? "", ADD_TEL: data.phoneNumber, ADD_FAX: data.faxNumber ?? "", ADD_CONT: data.contactPerson ?? "", ADD_COM_1: data.company1 ?? "", ADD_COM_2: data.company2 ?? "", ADD_STAT: "A", ADD_TYPE: "1",// NOT SURE WHAT THIS IS TRANS_PRES: "N", USER_CREA: date, USER_UPDT: date, ADD_LOOKUP: "", ADD_EMAIL: data.email ?? "", ADD_WEB: data.website ?? "", }) if (photos) { let folderPath = process.env.SUPPLIER_IMAGE_LOCATION + "/" + supplier.ADD_CODE + "/" let imageData = fs.readFileSync(req.file.path) if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { recursive: true, }) fs.writeFileSync(folderPath + supplier.ADD_CODE + '.jpg', imageData) fs.unlinkSync(req.file.path) } res.send(new SuccessResponse("Operation Successful")); } catch (e) { throw new ErrorResponse(e, 400) } }) async function generateNextSupplierCode() { const lastSupplier = await SupplierModel.findOne({ order: [[sequelize.cast(sequelize.col('ADD_CODE'), 'integer'), 'DESC']] }); if (!lastSupplier) { return '0001'; // Starting point if no suppliers are present } console.log("LAST SUPPLIER CODE ", lastSupplier.ADD_CODE) let nextCode = parseInt(lastSupplier.ADD_CODE, 10) + 1; // Check if the number is less than 10000 for zero-padding if (nextCode < 10000) { return nextCode.toString().padStart(4, '0'); } else { // If it's 10000 or more, just return the number return nextCode.toString(); } }