Skip to content

Commit

Permalink
Merge pull request #21 from fga-eps-mds/feature/121-adiciona-paginaca…
Browse files Browse the repository at this point in the history
…o-as-tabelas

Adiciona paginação as tabelas
  • Loading branch information
faco400 authored and senaarth committed Jul 1, 2023
2 parents 49c3bea + 273052d commit f258ba9
Show file tree
Hide file tree
Showing 11 changed files with 1,464 additions and 804 deletions.
32 changes: 24 additions & 8 deletions src/controllers/FlowController.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,12 +141,26 @@ class FlowController {

async index(req, res) {
try {
const { idUnit, idRole } = await tokenToUser(req);
const where = idRole === 5 ? {} : { idUnit };

const flows = await Flow.findAll({
where,
});
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
} else {
where = {};
}
const { limit, offset } = req.query;

const flows = limit
? await Flow.findAll({
where,
offset: parseInt(offset),
limit: parseInt(limit),
})
: await Flow.findAll({
where,
});
const totalCount = await Flow.count({ where });
const totalPages = Math.ceil(totalCount / limit);

let flowsWithSequences = [];
for (const flow of flows) {
Expand All @@ -167,8 +181,10 @@ class FlowController {

flowsWithSequences.push(flowSequence);
}

return res.status(200).json(flowsWithSequences);
console.log("aquii pelo amor");
return res
.status(200)
.json({ flows: flowsWithSequences || [], totalPages });
} catch (error) {
console.log(error);
return res
Expand Down
31 changes: 24 additions & 7 deletions src/controllers/ProcessController.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,32 @@ const validateRecord = (record) => {
class ProcessController {
async index(req, res) {
try {
const { idUnit, idRole } = await tokenToUser(req);
const where = idRole === 5 ? {} : { idUnit };

let processes = await Process.findAll({
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
} else {
where = {};
}
const offset = parseInt(req.query.offset) || 0;
const limit = parseInt(req.query.limit) || 10;
const processes = await Process.findAll({
where,
limit,
offset,
});
if (!processes) {

if (!processes || processes.length === 0) {
return res.status(404).json({ error: "Não há processos" });
} else {
let processesWithFlows = [];
const processesWithFlows = [];
for (const process of processes) {
const flowProcesses = await FlowProcess.findAll({
where: {
record: process.record,
},
});

const flowProcessesIdFlows = flowProcesses.map((flowProcess) => {
return flowProcess.idFlow;
});
Expand All @@ -59,9 +69,16 @@ class ProcessController {
status: process.status,
});
}
return res.status(200).json(processesWithFlows);

const totalCount = await Process.count({ where });
const totalPages = Math.ceil(totalCount / limit) || 0;

return res
.status(200)
.json({ processes: processesWithFlows, totalPages });
}
} catch (error) {
console.log(error);
return res.status(500).json({
error,
message: "Erro ao buscar processos",
Expand Down
17 changes: 13 additions & 4 deletions src/controllers/StageController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,26 @@ import { tokenToUser } from "../middleware/authMiddleware.js";

class StageController {
async index(req, res) {
const { idUnit, idRole } = await tokenToUser(req);
const where = idRole === 5 ? {} : { idUnit };
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
} else {
where = {};
}

const stages = await Stage.findAll({
where,
offset: req.query.offset,
limit: req.query.limit,
});
const totalCount = await Stage.count({ where });
const totalPages = Math.ceil(totalCount / parseInt(req.query.limit, 10));

if (!stages) {
if (!stages || stages.length === 0) {
return res.status(401).json({ error: "Não Existem fluxos" });
} else {
return res.json(stages);
return res.json({ stages: stages || [], totalPages });
}
}

Expand Down
20 changes: 14 additions & 6 deletions src/controllers/UnitController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,20 @@ import { ROLE } from "../schemas/role.js";

class UnitController {
async index(req, res) {
const units = await Unit.findAll();

if (!units) {
return res.status(401).json({ message: "Não Existe unidades" });
} else {
return res.status(200).json(units);
try {
const units = await Unit.findAll({
offset: req.query.offset,
limit: req.query.limit,
});
const totalCount = await Unit.count();
const totalPages = Math.ceil(totalCount / parseInt(req.query.limit, 10));
return res.json({ units: units || [], totalPages });
} catch (error) {
console.log(error);
return res.status(500).json({
error,
message: "Erro ao listar unidades",
});
}
}

Expand Down
38 changes: 30 additions & 8 deletions src/controllers/UserContoller.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ class UserController {
async login(req, res) {
try {
const { cpf, password } = req.body;
// Check for user cpf
const user = await User.findByPk(cpfFilter(cpf));
if (!user) {
return res.status(401).json({
Expand Down Expand Up @@ -80,23 +79,43 @@ class UserController {

async allUser(req, res) {
try {
const { idUnit, idRole } = await tokenToUser(req);
const where = idRole === 5 ? {} : { idUnit };
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
} else {
where = {};
}

if (req.query.accepted) {
const { accepted } = req.query;
let users;
let totalCount;
let totalPages;

if (accepted === "true") {
users = await User.findAll({
where: { accepted: true, idRole: { [Op.ne]: 5 }, ...where },
offset: req.query.offset,
limit: req.query.limit,
});
totalCount = await User.count({
where: { accepted: true, idRole: { [Op.ne]: 5 }, ...where },
});
totalPages = Math.ceil(totalCount / parseInt(req.query.limit, 10));
} else if (accepted === "false") {
users = await User.findAll({
where: { accepted: false, idRole: { [Op.ne]: 5 }, ...where },
offset: req.query.offset,
limit: req.query.limit,
});
totalCount = await User.count({
where: { accepted: false, idRole: { [Op.ne]: 5 }, ...where },
});
totalPages = Math.ceil(totalCount / parseInt(req.query.limit, 10));
} else {
return res.status(400).json({
message: "Parâmetro accepted deve ser 'true' ou 'false'",
message: "O parâmetro accepted deve ser 'true' ou 'false'",
});
}

Expand All @@ -110,15 +129,17 @@ class UserController {
idRole: user.idRole,
};
});
return res.status(200).json(users);

return res.status(200).json({ users: users || [], totalPages });
} else {
let users = await User.findAll({
const users = await User.findAll({
where: {
idRole: { [Op.ne]: 5 },
...where,
},
});
users = users.map((user) => {

const mappedUsers = users.map((user) => {
return {
cpf: user.cpf,
fullName: user.fullName,
Expand All @@ -128,7 +149,8 @@ class UserController {
idRole: user.idRole,
};
});
return res.status(200).json(users);

return res.status(200).json({ users: mappedUsers || [] });
}
} catch (error) {
console.log(error);
Expand Down
61 changes: 61 additions & 0 deletions src/tests/__tests__/test_flow_routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import "sequelize";
import supertest from "supertest";
import { app, injectDB } from "../TestApp";
import Flow from "../../models/Flow.js";
import jwt from "jsonwebtoken";
import { tokenToUser } from "../../middleware/authMiddleware.js";
import Process from "../../models/Process.js";
import FlowProcess from "../../models/FlowProcess.js";

Expand Down Expand Up @@ -210,4 +212,63 @@ describe("flow endpoints", () => {
`Desassociação entre fluxo '${flowResponse.body.idFlow}' e etapas '${flowResponse.body.sequences[0].from}' e '${flowResponse.body.sequences[0].to}' concluída`
);
});

test("test", async () => {
const testUser = {
cpf: "12345678901",
password: "123Teste",
};
const login = await supertest(app)
.post("/login")
.send(testUser, tokenToUser);
const req = {
headers: { authorization: `Bearer ${login.body.token}` },
};
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
// Get token from header
const token = req.headers.authorization.split(" ")[1];

// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);

// Get user from the token
req.user = await Flow.findByPk(decoded.id);
if (req.user.accepted === false) {
throw new Error();
}
} catch (error) {
console.log(error);
}
}

const flowsResponse = await supertest(app).get("/flows").set("test", `ok`);
expect(flowsResponse.status).toBe(200);
expect(flowsResponse.body.flows.length).toBe(1);
});

it("should return 404 with error message if flow is not found", async () => {
const response = await supertest(app).get("/flows");

expect(response.status).toBe(500);
expect(response.body.message).toBe("Impossível obter fluxos");
});

it("should return a 404 status with an error message if there are less than two sequences", async () => {
const flowData = {
name: "Fluxo Teste",
idUnit: 1,
sequences: [],
idUsersToNotify: ["12345678901", "12345678909"],
};

const response = await supertest(app).post("/newFlow").send(flowData);

expect(response.status).toBe(404);
expect(response.body.message).toBe("Necessário pelo menos duas etapas!");
expect(response.body.json).toBeUndefined();
});
});
57 changes: 57 additions & 0 deletions src/tests/__tests__/test_process_routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import "sequelize";
import supertest from "supertest";
import Process from "../../models/Process.js";
import { app, injectDB } from "../TestApp";
import { tokenToUser } from "../../middleware/authMiddleware.js";
import jwt from "jsonwebtoken";
import User from "../../models/User.js";

describe("process endpoints", () => {
beforeEach(async () => {
Expand Down Expand Up @@ -317,4 +320,58 @@ describe("process endpoints", () => {
"Etapa atualizada com sucesso"
);
});
test("test", async () => {
const testUser = {
cpf: "12345678901",
password: "123Teste",
};
const login = await supertest(app)
.post("/login")
.send(testUser, tokenToUser);
const req = {
headers: { authorization: `Bearer ${login.body.token}` },
};
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
// Get token from header
const token = req.headers.authorization.split(" ")[1];

// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);

// Get user from the token
req.user = await User.findByPk(decoded.id);
if (req.user.accepted === false) {
throw new Error();
}
} catch (error) {
console.log(error);
}
}

const testProcess = {
record: "12345678901234567890",
idUnit: 1,
priority: 0,
idFlow: 1,
nickname: "Meu Primeiro Processo",
};

const newProcessResponse = await supertest(app)
.post("/newProcess")
.send(testProcess);

expect(newProcessResponse.status).toBe(200);

const processesResponse = await supertest(app)
.get("/processes")
.set("test", `ok`);
const result = await req.headers.test;
expect(result).not.toEqual("ok");
expect(processesResponse.status).toBe(200);
expect(processesResponse.body.processes.length).toBe(1);
});
});
Loading

0 comments on commit f258ba9

Please sign in to comment.