Skip to content

Commit

Permalink
Merge pull request #24 from fga-eps-mds/feat/122-remover-filtragem
Browse files Browse the repository at this point in the history
Remove filtragem do lado do cliente
  • Loading branch information
sergiosacj authored and senaarth committed Jul 3, 2023
2 parents 7e6640e + a805b07 commit 34fb783
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 14 deletions.
8 changes: 7 additions & 1 deletion src/controllers/FlowController.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import FlowUser from "../models/FlowUser.js";
import FlowProcess from "../models/FlowProcess.js";
import { QueryTypes } from "sequelize";
import { tokenToUser } from "../middleware/authMiddleware.js";
import { filterByName } from "../utils/filters.js";

class FlowController {
static #stagesSequencesFromFlowStages(flowStages) {
Expand Down Expand Up @@ -143,10 +144,15 @@ class FlowController {
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
const unitFilter = idRole === 5 ? {} : { idUnit };
where = {
...filterByName(req),
...unitFilter,
};
} else {
where = {};
}

const { limit, offset } = req.query;

const flows = limit
Expand Down
21 changes: 12 additions & 9 deletions src/controllers/ProcessController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Stage from "../models/Stage.js";
import Database from "../database/index.js";
import { QueryTypes } from "sequelize";
import { tokenToUser } from "../middleware/authMiddleware.js";
import { filterByNicknameAndRecord } from "../utils/filters.js";

const isRecordValid = (record) => {
const regex = /^\d{20}$/;
Expand Down Expand Up @@ -49,7 +50,11 @@ class ProcessController {
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
const unitFilter = idRole === 5 ? {} : { idUnit };
where = {
...filterByNicknameAndRecord(req),
...unitFilter,
};
} else {
where = {};
}
Expand Down Expand Up @@ -247,7 +252,7 @@ class ProcessController {
type: QueryTypes.SELECT,
}
);

const totalCount = countQuery[0].total;
const totalPages = Math.ceil(totalCount / limit) || 0;

Expand Down Expand Up @@ -291,9 +296,9 @@ class ProcessController {
const startingProcess =
process.status === "notStarted" && status === "inProgress"
? {
idStage: flowStages[0].idStageA,
effectiveDate: new Date(),
}
idStage: flowStages[0].idStageA,
effectiveDate: new Date(),
}
: {};
let tempProgress = [];
if (process.status === "notStarted" && status === "inProgress") {
Expand All @@ -305,7 +310,7 @@ class ProcessController {
const stageEndDate = new Date(stageStartDate);
stageEndDate.setDate(
stageEndDate.getDate() +
handleVerifyDate(stageStartDate, currentStage.duration)
handleVerifyDate(stageStartDate, currentStage.duration)
);

const progressData = {
Expand Down Expand Up @@ -347,7 +352,6 @@ class ProcessController {

return res.status(200).json({ process, flows: flowProcesses });
} catch (error) {
console.log(error);
return res.status(500).json(error);
}
}
Expand Down Expand Up @@ -430,7 +434,7 @@ class ProcessController {
const stageEndDate = new Date(stageStartDate);
stageEndDate.setDate(
stageEndDate.getDate() +
handleVerifyDate(stageStartDate, currentToStage.duration)
handleVerifyDate(stageStartDate, currentToStage.duration)
);

maturityDate = stageEndDate;
Expand Down Expand Up @@ -482,7 +486,6 @@ class ProcessController {
message: `Impossível atualizar processo '${record}' para etapa '${to}`,
});
} catch (error) {
console.log(error);
return res.status(500).json({
error,
message: `Erro ao atualizar processo '${record}' para etapa '${to}`,
Expand Down
7 changes: 6 additions & 1 deletion src/controllers/StageController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ import Stage from "../models/Stage.js";
import FlowStage from "../models/FlowStage.js";
import { Op } from "sequelize";
import { tokenToUser } from "../middleware/authMiddleware.js";
import { filterByName } from "../utils/filters.js";

class StageController {
async index(req, res) {
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
const unitFilter = idRole === 5 ? {} : { idUnit };
where = {
...filterByName(req),
...unitFilter,
};
} else {
where = {};
}
Expand Down
7 changes: 6 additions & 1 deletion src/controllers/UnitController.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import Unit from "../models/Unit.js";
import User from "../models/User.js";
import { ROLE } from "../schemas/role.js";
import { filterByName } from "../utils/filters.js";

class UnitController {
async index(req, res) {
try {
const where = {
...filterByName(req),
};
const units = await Unit.findAll({
where,
offset: req.query.offset,
limit: req.query.limit,
});
const totalCount = await Unit.count();
const totalCount = await Unit.count({ where });
const totalPages = Math.ceil(totalCount / parseInt(req.query.limit, 10));
return res.json({ units: units || [], totalPages });
} catch (error) {
Expand Down
8 changes: 7 additions & 1 deletion src/controllers/UserContoller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { tokenToUser } from "../middleware/authMiddleware.js";
import { Op } from "sequelize";
import User from "../models/User.js";
import jwt from "jsonwebtoken";
import { filterByFullName } from "../utils/filters.js";

const cpfFilter = (cpf) => cpf.replace(/[^0-9]/g, "");
const jwtToken = process.env.JWT_SECRET || "ABC";
Expand All @@ -11,6 +12,7 @@ const generateToken = (id) => {
expiresIn: "3d",
});
};

class UserController {
async login(req, res) {
try {
Expand Down Expand Up @@ -81,7 +83,11 @@ class UserController {
let where;
if (req.headers.test !== "ok") {
const { idUnit, idRole } = await tokenToUser(req);
where = idRole === 5 ? {} : { idUnit };
const unitFilter = idRole === 5 ? {} : { idUnit };
where = {
...filterByFullName(req),
...unitFilter,
};
} else {
where = {};
}
Expand Down
9 changes: 8 additions & 1 deletion src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { ROLE } from "./schemas/role.js";

const routes = Router();

routes.get("/", (req, res) => {
routes.get("/", (_req, res) => {
res.json({
status: "OK",
message: "Up and running",
Expand All @@ -21,6 +21,7 @@ routes.get("/priorities", ProcessController.getPriorities);

//Rotas de processos
routes.get("/processes", ProcessController.index);
routes.get("/processes/:filter", ProcessController.index);
routes.get(
"/processes/:idFlow",
protect,
Expand Down Expand Up @@ -68,6 +69,8 @@ routes.get("/flows/process/:record", FlowController.indexByRecord);

routes.get("/flows", FlowController.index);

routes.get("/flows/:filter", FlowController.index);

routes.get("/flow/:idFlow", FlowController.getById);

routes.get("/flowStages", FlowController.getFlowStages);
Expand All @@ -88,6 +91,8 @@ routes.post("/newStage", StageController.store);

routes.get("/stages", StageController.index);

routes.get("/stages/:filter", StageController.index);

routes.get("/stage/:id", StageController.getById);

routes.delete("/deleteStage/:id", StageController.delete);
Expand All @@ -97,6 +102,8 @@ routes.post("/newUnit", UnitController.store);

routes.get("/units", UnitController.index);

routes.get("/units/:filter", UnitController.index);

routes.put("/setUnitAdmin", UnitController.setUnitAdmin);
routes.put("/removeUnitAdmin", UnitController.removeUnitAdmin);

Expand Down
89 changes: 89 additions & 0 deletions src/tests/__tests__/test_filters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Op } from "sequelize";
import {
filterByNicknameAndRecord,
filterByName,
filterByFullName,
} from "../../utils/filters.js";

describe("filters", () => {
describe("filterByNicknameAndRecord", () => {
it("should return the correct filter object when filter is provided", () => {
const req = {
query: {
filter: "John",
},
};

const result = filterByNicknameAndRecord(req);

expect(result).toEqual({
[Op.or]: [
{ record: { [Op.like]: "%John%" } },
{ nickname: { [Op.like]: "%John%" } },
],
});
});

it("should return an empty object when filter is not provided", () => {
const req = {
query: {},
};

const result = filterByNicknameAndRecord(req);

expect(result).toEqual({});
});
});

describe("filterByName", () => {
it("should return the correct filter object when filter is provided", () => {
const req = {
query: {
filter: "Smith",
},
};

const result = filterByName(req);

expect(result).toEqual({
[Op.or]: [{ name: { [Op.like]: "%Smith%" } }],
});
});

it("should return an empty object when filter is not provided", () => {
const req = {
query: {},
};

const result = filterByName(req);

expect(result).toEqual({});
});
});

describe("filterByFullName", () => {
it("should return the correct filter object when filter is provided", () => {
const req = {
query: {
filter: "John Doe",
},
};

const result = filterByFullName(req);

expect(result).toEqual({
[Op.or]: [{ fullName: { [Op.like]: "%John Doe%" } }],
});
});

it("should return an empty object when filter is not provided", () => {
const req = {
query: {},
};

const result = filterByFullName(req);

expect(result).toEqual({});
});
});
});
26 changes: 26 additions & 0 deletions src/tests/__tests__/test_user_routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,32 @@ describe("user endpoints", () => {
expect(response.body.message).toBe("Usuário inexistente");
});

it("should return error for wrong password", async () => {
const testUser = {
fullName: "Nomen Nomes",
cpf: "86891382424",
email: "[email protected]",
password: "spw123456",
idUnit: 1,
idRole: 3,
};

await supertest(app).post("/newUser").send(testUser);

await supertest(app).post(`/acceptRequest/${testUser.cpf}`);

const response = await supertest(app)
.post("/login")
.send({
cpf: testUser.cpf,
password: "senha_qualquer",
})
.expect(401);

expect(response.body.message).toBe("Senha ou usuário incorretos");
expect(response.body.error).toBe("Impossível autenticar");
});

test("get all users", async () => {
const testUser = {
fullName: "Nomenni Nomesos",
Expand Down
28 changes: 28 additions & 0 deletions src/utils/filters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Op } from "sequelize";

export function filterByNicknameAndRecord(req) {
return req.query.filter
? {
[Op.or]: [
{ record: { [Op.like]: `%${req.query.filter}%` } },
{ nickname: { [Op.like]: `%${req.query.filter}%` } },
],
}
: {};
}

export function filterByName(req) {
return req.query.filter
? {
[Op.or]: [{ name: { [Op.like]: `%${req.query.filter}%` } }],
}
: {};
}

export function filterByFullName(req) {
return req.query.filter
? {
[Op.or]: [{ fullName: { [Op.like]: `%${req.query.filter}%` } }],
}
: {};
}

0 comments on commit 34fb783

Please sign in to comment.