Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 22 additions & 78 deletions src/controllers/bmdashboard/bmInventoryTypeController.js
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -18,6 +8,7 @@ function bmInventoryTypeController(
ToolType,
EquipType,
invTypeHistory,
InvUnit,
) {
async function fetchMaterialTypes(req, res) {
try {
Expand Down Expand Up @@ -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);
}
};

Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
}
};

Expand All @@ -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);
}
};

Expand Down Expand Up @@ -756,7 +700,7 @@ function bmInventoryTypeController(
addConsumableType,
addToolType,
updateNameAndUnit,
fetchInvUnitsFromJson,
fetchInvUnits,
fetchInventoryByType,
addInvUnit,
deleteInvUnit,
Expand Down
14 changes: 14 additions & 0 deletions src/models/bmdashboard/buildingInventoryUnit.js
Original file line number Diff line number Diff line change
@@ -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',
);
4 changes: 3 additions & 1 deletion src/routes/bmdashboard/bmInventoryTypeRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const routes = function (
toolType,
equipType,
invTypeHistory,
invUnit,
) {
const inventoryTypeRouter = express.Router();
const controller = require('../../controllers/bmdashboard/bmInventoryTypeController')(
Expand All @@ -18,6 +19,7 @@ const routes = function (
toolType,
equipType,
invTypeHistory,
invUnit,
);

// Route for fetching all material types
Expand Down Expand Up @@ -57,7 +59,7 @@ const routes = function (

inventoryTypeRouter
.route('/inventoryUnits')
.get(controller.fetchInvUnitsFromJson)
.get(controller.fetchInvUnits)
.post(controller.addInvUnit)
.delete(controller.deleteInvUnit);

Expand Down
8 changes: 2 additions & 6 deletions src/startup/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,20 +240,16 @@ 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,
reusableType,
toolType,
equipmentType,
invTypeHistory,
buildingInventoryUnit,
);

const toolAvailabilityRoutes = require('../routes/bmdashboard/bmToolAvailabilityRoutes');
Expand Down
Loading