Skip to content

Commit 2b1746a

Browse files
Merge pull request #2059 from OneCommunityGlobal/SaiKrishna_AddEditDeleteInConsumables
SaiKrishna add Edit Delete Inventory Type Backend
2 parents 5dd7ae0 + dbaf122 commit 2b1746a

2 files changed

Lines changed: 164 additions & 4 deletions

File tree

src/controllers/bmdashboard/bmInventoryTypeController.js

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,145 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
388388
res.status(500).send(error);
389389
}
390390
};
391+
392+
// PUT - Update any inventory type by ID (generic)
393+
const updateInventoryType = async (req, res) => {
394+
try {
395+
const { invtypeId } = req.params;
396+
const updateData = req.body;
397+
398+
// Remove fields that shouldn't be updated directly
399+
delete updateData._id;
400+
delete updateData.__t;
401+
delete updateData.__v;
402+
403+
const updatedInvType = await InvType.findByIdAndUpdate(invtypeId, updateData, {
404+
new: true,
405+
runValidators: true,
406+
});
407+
408+
if (!updatedInvType) {
409+
return res.status(404).json({ error: 'Inventory type not found' });
410+
}
411+
412+
res.status(200).json(updatedInvType);
413+
} catch (error) {
414+
res.status(500).json({ error: error.message });
415+
}
416+
};
417+
418+
// DELETE - Delete any inventory type by ID
419+
const deleteInventoryType = async (req, res) => {
420+
try {
421+
const { invtypeId } = req.params;
422+
423+
const deletedInvType = await InvType.findByIdAndDelete(invtypeId);
424+
425+
if (!deletedInvType) {
426+
return res.status(404).json({ error: 'Inventory type not found' });
427+
}
428+
429+
res.status(200).json({ message: 'Inventory type deleted successfully' });
430+
} catch (error) {
431+
res.status(500).json({ error: error.message });
432+
}
433+
};
434+
435+
// POST - Add a new unit to the JSON file
436+
const addInventoryUnit = async (req, res) => {
437+
try {
438+
const { unit, category } = req.body;
439+
440+
if (!unit) {
441+
return res.status(400).json({ error: 'Unit is required' });
442+
}
443+
444+
readFile(filepath, 'utf8', (err, data) => {
445+
if (err) {
446+
console.error('Error reading file:', err);
447+
return res.status(500).json({ error: 'Error reading units file' });
448+
}
449+
450+
try {
451+
const jsonData = JSON.parse(data);
452+
453+
// Check if unit already exists
454+
const exists = jsonData.some(
455+
(item) => item.unit.toLowerCase() === unit.toLowerCase(),
456+
);
457+
if (exists) {
458+
return res.status(409).json({ error: 'Unit already exists' });
459+
}
460+
461+
// Add new unit
462+
const newUnit = { unit, category: category || 'Material' };
463+
jsonData.push(newUnit);
464+
465+
writeFile(filepath, JSON.stringify(jsonData, null, 2), 'utf8', (writeErr) => {
466+
if (writeErr) {
467+
console.error('Error writing to file:', writeErr);
468+
return res.status(500).json({ error: 'Error saving unit' });
469+
}
470+
res.status(201).json(newUnit);
471+
});
472+
} catch (parseError) {
473+
console.error('Error parsing JSON:', parseError);
474+
res.status(500).json({ error: 'Error parsing units file' });
475+
}
476+
});
477+
} catch (error) {
478+
res.status(500).json({ error: error.message });
479+
}
480+
};
481+
482+
// DELETE - Remove a unit from the JSON file by unit name
483+
const deleteInventoryUnit = async (req, res) => {
484+
try {
485+
const { unitName } = req.params;
486+
487+
if (!unitName) {
488+
return res.status(400).json({ error: 'Unit name is required' });
489+
}
490+
491+
readFile(filepath, 'utf8', (err, data) => {
492+
if (err) {
493+
console.error('Error reading file:', err);
494+
return res.status(500).json({ error: 'Error reading units file' });
495+
}
496+
497+
try {
498+
const jsonData = JSON.parse(data);
499+
500+
// Find index of unit to delete
501+
const decodedUnitName = decodeURIComponent(unitName);
502+
const unitIndex = jsonData.findIndex(
503+
(item) => item.unit.toLowerCase() === decodedUnitName.toLowerCase(),
504+
);
505+
506+
if (unitIndex === -1) {
507+
return res.status(404).json({ error: 'Unit not found' });
508+
}
509+
510+
// Remove the unit
511+
jsonData.splice(unitIndex, 1);
512+
513+
writeFile(filepath, JSON.stringify(jsonData, null, 2), 'utf8', (writeErr) => {
514+
if (writeErr) {
515+
console.error('Error writing to file:', writeErr);
516+
return res.status(500).json({ error: 'Error deleting unit' });
517+
}
518+
res.status(200).json({ message: 'Unit deleted successfully' });
519+
});
520+
} catch (parseError) {
521+
console.error('Error parsing JSON:', parseError);
522+
res.status(500).json({ error: 'Error parsing units file' });
523+
}
524+
});
525+
} catch (error) {
526+
res.status(500).json({ error: error.message });
527+
}
528+
};
529+
391530
return {
392531
fetchMaterialTypes,
393532
fetchConsumableTypes,
@@ -402,6 +541,10 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
402541
addToolType,
403542
fetchInvUnitsFromJson,
404543
fetchInventoryByType,
544+
updateInventoryType,
545+
deleteInventoryType,
546+
addInventoryUnit,
547+
deleteInventoryUnit,
405548
};
406549
}
407550

src/routes/bmdashboard/bmInventoryTypeRouter.js

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,33 @@ const routes = function (baseInvType, matType, consType, reusType, toolType, equ
3030

3131
inventoryTypeRouter.route('/invtypes/consumables').get(controller.fetchConsumableTypes);
3232

33-
// Route for fetching types by selected type
34-
inventoryTypeRouter.route('/invtypes/:type').get(controller.fetchInventoryByType);
35-
3633
// Combined routes for getting a single inventory type and updating its name and unit of measurement
3734
inventoryTypeRouter
3835
.route('/invtypes/material/:invtypeId')
3936
.get(controller.fetchSingleInventoryType)
4037
.put(controller.updateNameAndUnit);
4138

42-
inventoryTypeRouter.route('/inventoryUnits').get(controller.fetchInvUnitsFromJson);
39+
// Generic route for updating/deleting any inventory type by ID
40+
// Using regex to match MongoDB ObjectId format (24 hex characters) - must come BEFORE :type route
41+
inventoryTypeRouter
42+
.route('/invtypes/:invtypeId([0-9a-fA-F]{24})')
43+
.get(controller.fetchSingleInventoryType)
44+
.put(controller.updateInventoryType)
45+
.delete(controller.deleteInventoryType);
46+
47+
// Route for fetching types by selected type (Materials, Consumables, etc.)
48+
// This comes AFTER the ObjectId route so it only matches non-ObjectId strings
49+
inventoryTypeRouter.route('/invtypes/:type').get(controller.fetchInventoryByType);
50+
51+
// Routes for inventory units (JSON file based)
52+
inventoryTypeRouter
53+
.route('/inventoryUnits')
54+
.get(controller.fetchInvUnitsFromJson)
55+
.post(controller.addInventoryUnit);
56+
57+
inventoryTypeRouter
58+
.route('/inventoryUnits/:unitName')
59+
.delete(controller.deleteInventoryUnit);
4360

4461
return inventoryTypeRouter;
4562
};

0 commit comments

Comments
 (0)