Skip to content

Commit

Permalink
Merge pull request #714 from OneCommunityGlobal/development
Browse files Browse the repository at this point in the history
Backend Release to Main [1.35]
  • Loading branch information
one-community authored Jan 22, 2024
2 parents b472a67 + 97076bd commit 1fc91ff
Show file tree
Hide file tree
Showing 10 changed files with 404 additions and 5 deletions.
122 changes: 122 additions & 0 deletions src/controllers/bmdashboard/BuildingUnits.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
[
{
"unit":"Micrograms",
"category":"Material"
},
{
"unit": "Milligrams (mg)",
"category": "Material"
},
{
"unit": "Centigrams (cg)",
"category": "Material"
},
{
"unit": "Decigrams (dg)",
"category": "Material"
},
{
"unit": "Grams (g)",
"category": "Material"
},
{
"unit": "Dekagram (dag)",
"category": "Material"
},
{
"unit": "Hectogram (hg)",
"category": "Material"
},
{
"unit": "Kilograms",
"category": "Material"
},
{
"unit": "Cubic Centimeter (cm³)",
"category": "Material"
},
{
"unit": "Cubic Millimeter (mm³)",
"category": "Material"
},
{
"unit": "Cubic Yard (yd³)",
"category": "Material"
},
{
"unit": "Square Meter (m²)",
"category": "Material"
},
{
"unit": "Metric ton (t)",
"category": "Material"
},
{
"unit": "Pounds",
"category": "Material"
},
{
"unit": "Ounces",
"category": "Material"
},
{
"unit": "Carats",
"category": "Material"
},
{
"unit": "Stone",
"category": "Material"
},
{
"unit": "Bags",
"category": "Material"
},
{
"unit": "Numbers",
"category": "Material"
},
{
"unit": "Board Feet (BDFT)",
"category": "Material"
},
{
"unit": "Cords",
"category": "Material"
},
{
"unit": "Pieces",
"category": "Material"
},
{
"unit": "Roll (for rolled insulation)",
"category": "Material"
},
{
"unit": "Bundle (for shingles)",
"category": "Material"
},
{
"unit": "Meter (for wiring,pipes)",
"category": "Material"
},
{
"unit": "Tubes (for caulking)",
"category": "Material"
},
{
"unit": "Tons",
"category": "Material"
},
{
"unit": "Cubic Meter",
"category": "Material"
},
{
"unit": "Sand",
"category": "Material"
},
{
"unit": "FakeUnitForTesting",
"category": "Material"
}
]
123 changes: 123 additions & 0 deletions src/controllers/bmdashboard/bmInventoryTypeController.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
const fs = require('fs');

const filepath = 'src/controllers/bmdashboard/BuildingUnits.json';

function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolType, EquipType) {
async function fetchMaterialTypes(req, res) {
try {
Expand All @@ -11,6 +15,122 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
}
}

const fetchInvUnitsFromJson = async (req, res) => {
try {
fs.readFile(filepath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}

try {
const jsonData = JSON.parse(data);
res.status(200).send(jsonData);
} catch (parseError) {
console.error('Error parsing JSON:', parseError);
res.status(500).send(parseError);
}
});
} catch (err) {
res.json(err);
}
};


async function addMaterialType(req, res) {
const {
name,
description,
requestor: { requestorId },
} = req.body;
const unit = req.body.unit || req.body.customUnit;
try {
MatType
.find({ name })
.then((result) => {
if (result.length) {
res.status(409).send('Oops!! Material already exists!');
} else {
const newDoc = {
category: 'Material',
name,
description,
unit,
createdBy: requestorId,
};
MatType
.create(newDoc)
.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);
fs.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]`;

fs.writeFile(filepath, updatedFileContent, 'utf8', (error) => {
if (error) {
console.error('Error writing to file:', error);
return;
}
});
});
} catch (e) {
console.log(e);
}
}
})
.catch((error) => {
if (error._message.includes('validation failed')) {
res.status(400).send(error);
} else {
res.status(500).send(error);
}
});
}
})
.catch(error => res.status(500).send(error));
} catch (error) {
res.status(500).send(error);
}
}

async function fetchInventoryByType(req, res) {
const { type } = req.params;
let SelectedType = InvType;
if (type === 'Materials') {
SelectedType = MatType;
} else if (type === 'Consumables') {
SelectedType = ConsType;
} else if (type === 'Reusables') {
SelectedType = ReusType;
} else if (type === 'Tools') {
SelectedType = ToolType;
} else if (type === 'Equipments') {
SelectedType = EquipType;
}
try {
SelectedType
.find()
.exec()
.then(result => res.status(200).send(result))
.catch(error => res.status(500).send(error));
} catch (err) {
res.json(err);
}
}

async function addEquipmentType(req, res) {
const {
name,
Expand Down Expand Up @@ -94,6 +214,9 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
addEquipmentType,
fetchSingleInventoryType,
updateNameAndUnit,
addMaterialType,
fetchInvUnitsFromJson,
fetchInventoryByType,
};
}

Expand Down
4 changes: 4 additions & 0 deletions src/controllers/bmdashboard/bmToolController.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ const bmToolController = (BuildingTool) => {
path: 'itemType',
select: '_id name description unit imageUrl category',
},
{
path: 'project',
select: 'name',
},
{
path: 'userResponsible',
select: '_id firstName lastName',
Expand Down
30 changes: 30 additions & 0 deletions src/controllers/permissionChangeLogsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const UserProfile = require('../models/userProfile');

const permissionChangeLogController = function (PermissionChangeLog) {

const getPermissionChangeLogs = async function (req, res) {

try {
const userProfile = await UserProfile.findOne({ _id: req.params.userId }).exec()

if (userProfile) {
if (userProfile.role !== 'Owner') {
res.status(204).send([])
} else {
const changeLogs = await PermissionChangeLog.find({})
res.status(200).send(changeLogs)
}
} else {
res.status(403).send(`User (${req.params.userId}) not found.`)
}
} catch (err) {
console.error(err)
}
}

return {
getPermissionChangeLogs
}
}

module.exports = permissionChangeLogController
26 changes: 26 additions & 0 deletions src/models/permissionChangeLog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./userProfile');
const rolesMergedPermissions = require('./role')

const PermissionChangeLog = new Schema({
logDateTime: { type: String, required: true },
roleId: {
type: mongoose.Types.ObjectId,
ref: rolesMergedPermissions,
required: true
},
roleName: { type: String },
permissions: { type: [String], required: true },
permissionsAdded: { type: [String], required: true },
permissionsRemoved: { type: [String], required: true },
requestorId: {
type: mongoose.Types.ObjectId,
ref: User
},
requestorRole: { type: String },
requestorEmail: { type: String, required: true},
});

module.exports = mongoose.model('permissionChangeLog', PermissionChangeLog, 'permissionChangeLogs');
10 changes: 10 additions & 0 deletions src/routes/bmdashboard/bmInventoryTypeRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,23 @@ const routes = function (baseInvType, matType, consType, reusType, toolType, equ
inventoryTypeRouter.route('/invtypes/materials')
.get(controller.fetchMaterialTypes);

inventoryTypeRouter.route('/invtypes/material')
.post(controller.addMaterialType);
// Route for fetching types by selected type
inventoryTypeRouter.route('/invtypes/:type')
.get(controller.fetchInventoryByType);

inventoryTypeRouter.route('/invtypes/equipment')
.post(controller.addEquipmentType);

// Combined routes for getting a single inventory type and updating its name and unit of measurement
inventoryTypeRouter.route('/invtypes/material/:invtypeId')
.get(controller.fetchSingleInventoryType)
.put(controller.updateNameAndUnit);

inventoryTypeRouter.route('/inventoryUnits')
.get(controller.fetchInvUnitsFromJson);

return inventoryTypeRouter;
};

Expand Down
14 changes: 14 additions & 0 deletions src/routes/permissionChangeLogsRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const express = require('express');

const routes = function (permissionChangeLog) {
const controller = require('../controllers/permissionChangeLogsController')(permissionChangeLog)

const permissionChangeLogRouter = express.Router()

permissionChangeLogRouter.route("/permissionChangeLogs/:userId")
.get(controller.getPermissionChangeLogs)

return permissionChangeLogRouter
}

module.exports = routes
3 changes: 2 additions & 1 deletion src/routes/roleRouter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const express = require('express');
const changedPermissionsLogger = require('../utilities/logPermissionChangeByAccount')

const routes = function (role) {
const controller = require('../controllers/rolesController')(role);
Expand All @@ -10,7 +11,7 @@ const routes = function (role) {

RolesRouter.route('/roles/:roleId')
.get(controller.getRoleById)
.patch(controller.updateRoleById)
.patch(changedPermissionsLogger,controller.updateRoleById)
.delete(controller.deleteRoleById);
return RolesRouter;
};
Expand Down
Loading

0 comments on commit 1fc91ff

Please sign in to comment.