Skip to content

Commit

Permalink
Merge pull request #26 from fga-eps-mds/224-history
Browse files Browse the repository at this point in the history
Historico de alterações da demanda
  • Loading branch information
DaviMarinho authored Apr 30, 2021
2 parents 777b541 + ec47f06 commit c2c44e6
Show file tree
Hide file tree
Showing 14 changed files with 276 additions and 65 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# .env.example, commit to repo
SECRET=segredo
CLIENTS_URL=backend_clients

USERS_URL=backend_users
DB_USER=api_user
DB_PASS=api_password
DB_NAME=api_database
Expand Down
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"ecmaVersion": 12
},
"rules": {
"no-underscore-dangle": "off"
"no-underscore-dangle": "off",
"consistent-return": "off"
}
}
3 changes: 2 additions & 1 deletion scripts/consts.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

117 changes: 91 additions & 26 deletions src/Controllers/DemandController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const Demand = require('../Models/DemandSchema');
const Category = require('../Models/CategorySchema');
const validation = require('../Utils/validate');
const { getClients } = require('../Services/Axios/clientService');
const { getUser } = require('../Services/Axios/userService');
const verifyChanges = require('../Utils/verifyChanges');

const demandGetWithClientsNames = async (req, res) => {
try {
Expand Down Expand Up @@ -150,34 +152,50 @@ const demandsSectorsStatistic = async (req, res) => {
};

const demandCreate = async (req, res) => {
const {
name, description, process, categoryID, sectorID, clientID, userID,
} = req.body;
try {
const {
name, description, process, categoryID, sectorID, clientID, userID,
} = req.body;

const validFields = validation.validateDemand(
name, description, categoryID, sectorID, clientID, userID,
);
if (validFields.length) {
return res.status(400).json({ status: validFields });
}
const token = req.headers['x-access-token'];

const validFields = validation.validateDemand(
name, description, categoryID, sectorID, clientID, userID,
);
if (validFields.length) {
return res.status(400).json({ status: validFields });
}
const user = await getUser(userID, token);

const newDemand = await Demand.create({
name,
description,
process: process || '',
categoryID,
sectorHistory: {
sectorID,
createdAt: moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate(),
updatedAt: moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate(),
},
clientID,
userID,
createdAt: moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate(),
updatedAt: moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate(),
});
if (user.error) {
return res.status(400).json({ message: user.error });
}
const date = moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate();
const newDemand = await Demand.create({
name,
description,
process: process || '',
categoryID,
sectorHistory: {
sectorID,
createdAt: date,
updatedAt: date,
},
clientID,
userID,
demandHistory: {
userID,
date,
label: 'created',
},
createdAt: date,
updatedAt: date,
});

return res.json(newDemand);
return res.json(newDemand);
} catch (err) {
return res.status(400).json({ message: 'Failed to create demand' });
}
};

const demandUpdate = async (req, res) => {
Expand All @@ -195,6 +213,15 @@ const demandUpdate = async (req, res) => {
}

try {
const token = req.headers['x-access-token'];

const user = await getUser(userID, token);

if (user.error) {
return res.status(400).json({ message: user.error });
}

const demandHistory = await verifyChanges(req.body, id);
const updateStatus = await Demand.findOneAndUpdate({ _id: id }, {
name,
description,
Expand All @@ -203,8 +230,9 @@ const demandUpdate = async (req, res) => {
sectorID,
clientID,
userID,
demandHistory,
updatedAt: moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate(),
}, { new: true }, (user) => user);
}, { new: true }, (err) => err);
return res.json(updateStatus);
} catch {
return res.status(400).json({ err: 'invalid id' });
Expand Down Expand Up @@ -400,6 +428,42 @@ const deleteDemandUpdate = async (req, res) => {
}
};

const history = async (req, res) => {
const { id } = req.params;

try {
let error = '';
const token = req.headers['x-access-token'];
const demandFound = await Demand.findOne({ _id: id });
const userHistory = await Promise.all(demandFound.demandHistory.map(async (elem) => {
const user = await getUser(elem.userID, token);

if (user.error) {
error = user.error;
return;
}
return {
label: elem.label,
before: elem.before,
after: elem.after,
date: elem.date,
user: {
_id: user._id,
name: user.name,
sector: user.sector,
role: user.role,
},
};
}));
if (error) {
return res.status(400).json({ message: error });
}
return res.json(userHistory);
} catch {
return res.status(400).json({ message: 'Demand not found' });
}
};

module.exports = {
demandGet,
demandCreate,
Expand All @@ -414,4 +478,5 @@ module.exports = {
deleteDemandUpdate,
demandsCategoriesStatistic,
demandsSectorsStatistic,
history,
};
24 changes: 24 additions & 0 deletions src/Models/DemandSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,30 @@ const DemandSchema = new mongoose.Schema({
require: true,
},
}],
demandHistory: [{
userID: {
type: String,
require: true,
},
date: {
type: Date,
require: true,
},
label: {
type: String,
require: true,
},
before: {
type: String,
require: true,
default: '',
},
after: {
type: String,
require: true,
default: '',
},
}],
clientID: {
type: String,
require: true,
Expand Down
7 changes: 6 additions & 1 deletion src/Services/Axios/baseService.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
const axios = require('axios');

const { CLIENTS_URL } = process.env;
const { CLIENTS_URL, USERS_URL } = process.env;

const APIClients = axios.create({
baseURL: `http://${CLIENTS_URL}:3002/`,
});

const APIUsers = axios.create({
baseURL: `http://${USERS_URL}:3001/`,
});

module.exports = {
APIClients,
APIUsers,
};
16 changes: 16 additions & 0 deletions src/Services/Axios/userService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { APIUsers } = require('./baseService');

const getUser = async (userID, token) => {
try {
const user = await APIUsers.get(`/users/${userID}`, { headers: { 'x-access-token': token } })
.then((response) => response.data);
if (!user) {
return { error: 'User not found' };
}
return user;
} catch {
return { error: 'Could not connect to user api' };
}
};

module.exports = { getUser };
56 changes: 56 additions & 0 deletions src/Utils/verifyChanges.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const moment = require('moment-timezone');
const Demand = require('../Models/DemandSchema');

const buildHistory = (body, demand, label) => {
const date = moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate();
return {
label,
before: demand[label],
after: body[label],
userID: body.userID,
date,
};
};

const biggerArray = (arr1, arr2) => {
if (arr1.length > arr2.length) {
return { bigger: arr1, smaller: arr2, body: true };
}
return { bigger: arr2, smaller: arr1, body: false };
};

const verifyChanges = async (body, id) => {
const date = moment.utc(moment.tz('America/Sao_Paulo').format('YYYY-MM-DDTHH:mm:ss')).toDate();
const demand = await Demand.findOne({ _id: id });
const newHistory = [];

if (body.name !== demand.name) {
newHistory.push(buildHistory(body, demand, 'name'));
}
if (body.description !== demand.description) {
newHistory.push(buildHistory(body, demand, 'description'));
}
if (body.process !== demand.process) {
newHistory.push(buildHistory(body, demand, 'process'));
}

const categoryArrays = biggerArray(body.categoryID, demand.categoryID);
categoryArrays.bigger.map((item, index) => {
const value0 = String(item ?? '');
const value1 = String(categoryArrays.smaller[index] ?? '');
if (value0 !== value1) {
newHistory.push({
label: 'category',
before: categoryArrays.body ? value1 : value0,
after: categoryArrays.body ? value0 : value1,
userID: body.userID,
date,
});
}
return item;
});

return [...demand.demandHistory, ...newHistory];
};

module.exports = verifyChanges;
2 changes: 1 addition & 1 deletion src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ routes.get('/clientsNames', verifyJWT, DemandController.demandGetWithClientsName
routes.put('/demand/create-demand-update/:id', verifyJWT, DemandController.createDemandUpdate);
routes.put('/demand/update-demand-update/:id', verifyJWT, DemandController.updateDemandUpdate);
routes.put('/demand/delete-demand-update/:id', verifyJWT, DemandController.deleteDemandUpdate);
routes.get('/demand/history/:id', verifyJWT, DemandController.history);
routes.get('/statistic/category', verifyJWT, DemandController.demandsCategoriesStatistic);
routes.get('/statistic/sector', verifyJWT, DemandController.demandsSectorsStatistic);

module.exports = routes;
4 changes: 2 additions & 2 deletions tests/__mocks__/apiResponses/clients.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
{
"before": "",
"after": "",
"_id": "6085e65a664ee00049cc7639",
"_id": "6089c3538dfebe00555bc17e",
"userID": "608335084771520040cea104",
"date": "2021-04-25T18:59:54.000Z",
"label": "created"
},
{
"before": "Julia Batist",
"after": "Julia Batista",
"_id": "6085e6ae664ee00049cc763b",
"_id": "6089c3538dfebe00555bc17e",
"label": "name",
"userID": "608335084771520040cea104",
"date": "2021-04-25T19:01:18.000Z"
Expand Down
11 changes: 11 additions & 0 deletions tests/__mocks__/apiResponses/user.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"temporaryPassword": false,
"_id": "6089c3538dfebe00555bc17e",
"name": "Maria Joaquina",
"email": "[email protected]",
"role": "admin",
"sector": "606fa89e15281a0040cff1fd",
"createdAt": "2021-04-28T17:19:31.000Z",
"updatedAt": "2021-04-28T17:27:29.000Z",
"__v": 0
}
7 changes: 6 additions & 1 deletion tests/__mocks__/axios.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
const clients = require('./apiResponses/clients.json')
const user = require('./apiResponses/user.json')

const GET_CLIENTS = '/clients'
const GET_USER_BY_ID = '/users/6089c3538dfebe00555bc17e'

const axios = {
get: jest.fn((url) => {
switch (url) {
case GET_CLIENTS:
return Promise.resolve({ data: clients });
return Promise.resolve({ data: clients });
case GET_USER_BY_ID:
return Promise.resolve({ data: user });
default:
return Promise.resolve({ data: { error: `Mock URL ${url} not found` }});
}
Expand Down
Loading

0 comments on commit c2c44e6

Please sign in to comment.