diff --git a/src/controllers/bmdashboard/bmInventoryTypeController.js b/src/controllers/bmdashboard/bmInventoryTypeController.js index cd9b8cde6..4b6966fdf 100644 --- a/src/controllers/bmdashboard/bmInventoryTypeController.js +++ b/src/controllers/bmdashboard/bmInventoryTypeController.js @@ -1,15 +1,5 @@ -const fs = require('fs'); -const fsPromises = require('fs/promises'); -const path = require('path'); const mongoose = require('mongoose'); -const filename = 'BuildingUnits.json'; -const currentFilePath = __filename; -const rootPath = path.resolve(path.dirname(currentFilePath), '../../../'); // Go up three levels to the root -const filepath = path.join(rootPath, filename); -const { readFile } = fs; -const { writeFile } = fs; - function bmInventoryTypeController( InvType, MatType, @@ -18,6 +8,7 @@ function bmInventoryTypeController( ToolType, EquipType, invTypeHistory, + InvUnit, ) { async function fetchMaterialTypes(req, res) { try { @@ -76,25 +67,12 @@ function bmInventoryTypeController( } }; - const fetchInvUnitsFromJson = async (req, res) => { + const fetchInvUnits = async (req, res) => { try { - // console.log(__dirname,filepath) - readFile(filepath, 'utf8', (err, data) => { - if (err) { - console.error('Error reading file:', err); - res.status(500).send(err); - } - - try { - const jsonData = JSON.parse(data); - res.status(200).send(jsonData); - } catch (parseError) { - console.error('Error parsing JSON:', parseError); - res.status(500).send(parseError); - } - }); + const units = await InvUnit.find(); + res.status(200).send(units); } catch (err) { - res.json(err); + res.status(500).send(err); } }; @@ -122,31 +100,9 @@ function bmInventoryTypeController( .then((results) => { res.status(201).send(results); if (req.body.customUnit) { - try { - // Add new unit to json file : src\controllers\bmdashboard\BuildingUnits.json - const newItem = { unit: req.body.customUnit, category: 'Material' }; - const newItemString = JSON.stringify(newItem, null, 2); - readFile(filepath, 'utf8', (err, data) => { - if (err) { - console.error('Error reading file:', err); - return; - } - // Remove the last array bracket and comma - const updatedContent = data.trim().replace(/\s*]$/, ''); - - // Add a comma and newline if the file is not empty - const separator = updatedContent !== '' ? ',\n' : ''; - const updatedFileContent = `${updatedContent}${separator}${newItemString}\n]`; - - writeFile(filepath, updatedFileContent, 'utf8', (error) => { - if (error) { - console.error('Error writing to file:', error); - } - }); - }); - } catch (e) { - console.log(e); - } + InvUnit.create({ unit: req.body.customUnit, category: 'Material' }).catch((e) => + console.error('Error saving custom unit:', e), + ); } }) .catch((error) => { @@ -512,20 +468,17 @@ function bmInventoryTypeController( } try { - // read JSON file and parse it into an array - const unitsJSON = await fsPromises.readFile(filepath, { encoding: 'utf8' }); - const unitsArray = JSON.parse(unitsJSON); - - // append new unit into array - unitsArray.push({ unit, category }); - - // save updated array into JSON file and rend it back - await fsPromises.writeFile(filepath, JSON.stringify(unitsArray, null, ' ')); + const duplicate = await InvUnit.findOne({ unit }); + if (duplicate) { + res.status(409).json({ error: 'Unit already exists' }); + return; + } - res.status(201).send(unitsArray); + await InvUnit.create({ unit, category }); + const updatedUnits = await InvUnit.find(); + res.status(201).send(updatedUnits); } catch (err) { res.status(500).send(err); - console.error(err); } }; @@ -537,26 +490,17 @@ function bmInventoryTypeController( } try { - // read JSON file and parse it into an array - const unitsJSON = await fsPromises.readFile(filepath, { encoding: 'utf8' }); - const unitsArray = JSON.parse(unitsJSON); - - // if unit does not exist, send err response - const index = unitsArray.findIndex((unitObject) => unitObject.unit === unit); - if (index === -1) { + const existing = await InvUnit.findOne({ unit }); + if (!existing) { res.status(400).json('Unit does not exist'); return; } - // otherwise, remove unit - const filteredUnits = unitsArray.filter((unitObject) => unitObject.unit !== unit); - - // save updated array into JSON file and rend it back - await fsPromises.writeFile(filepath, JSON.stringify(filteredUnits, null, ' ')); - res.status(200).send(filteredUnits); + await InvUnit.deleteOne({ unit }); + const updatedUnits = await InvUnit.find(); + res.status(200).send(updatedUnits); } catch (err) { res.status(500).send(err); - console.error(err); } }; @@ -756,7 +700,7 @@ function bmInventoryTypeController( addConsumableType, addToolType, updateNameAndUnit, - fetchInvUnitsFromJson, + fetchInvUnits, fetchInventoryByType, addInvUnit, deleteInvUnit, diff --git a/src/models/bmdashboard/buildingInventoryUnit.js b/src/models/bmdashboard/buildingInventoryUnit.js new file mode 100644 index 000000000..b6bcdea02 --- /dev/null +++ b/src/models/bmdashboard/buildingInventoryUnit.js @@ -0,0 +1,14 @@ +const mongoose = require('mongoose'); + +const { Schema } = mongoose; + +const buildingInventoryUnitSchema = new Schema({ + unit: { type: String, required: true, unique: true }, + category: { type: String, default: 'Material' }, +}); + +module.exports = mongoose.model( + 'buildingInventoryUnit', + buildingInventoryUnitSchema, + 'buildingInventoryUnits', +); diff --git a/src/routes/bmdashboard/bmInventoryTypeRouter.js b/src/routes/bmdashboard/bmInventoryTypeRouter.js index 2c57438bb..eb6a79f0d 100644 --- a/src/routes/bmdashboard/bmInventoryTypeRouter.js +++ b/src/routes/bmdashboard/bmInventoryTypeRouter.js @@ -8,6 +8,7 @@ const routes = function ( toolType, equipType, invTypeHistory, + invUnit, ) { const inventoryTypeRouter = express.Router(); const controller = require('../../controllers/bmdashboard/bmInventoryTypeController')( @@ -18,6 +19,7 @@ const routes = function ( toolType, equipType, invTypeHistory, + invUnit, ); // Route for fetching all material types @@ -57,7 +59,7 @@ const routes = function ( inventoryTypeRouter .route('/inventoryUnits') - .get(controller.fetchInvUnitsFromJson) + .get(controller.fetchInvUnits) .post(controller.addInvUnit) .delete(controller.deleteInvUnit); diff --git a/src/startup/routes.js b/src/startup/routes.js index c6cab27e5..986cfdd96 100644 --- a/src/startup/routes.js +++ b/src/startup/routes.js @@ -240,13 +240,8 @@ const bmConsumablesRouter = require('../routes/bmdashboard/bmConsumablesRouter') ); const costBreakdown = require('../models/bmdashboard/costBreakdown'); const costBreakdownRouter = require('../routes/bmdashboard/costBreakdownRouter')(costBreakdown); +const buildingInventoryUnit = require('../models/bmdashboard/buildingInventoryUnit'); const bmInventoryTypeRouter = require('../routes/bmdashboard/bmInventoryTypeRouter')( - invTypeBase, - materialType, - consumableType, - reusableType, - toolType, - equipmentType, invTypeBase, materialType, consumableType, @@ -254,6 +249,7 @@ const bmInventoryTypeRouter = require('../routes/bmdashboard/bmInventoryTypeRout toolType, equipmentType, invTypeHistory, + buildingInventoryUnit, ); const toolAvailabilityRoutes = require('../routes/bmdashboard/bmToolAvailabilityRoutes');