diff --git a/src/controllers/Emailer.js b/src/controllers/Emailer.js index 226dc91e..8ad0fbb5 100644 --- a/src/controllers/Emailer.js +++ b/src/controllers/Emailer.js @@ -25,7 +25,6 @@ export async function getMailContents() { }); return mailContents; } catch (error) { - console.log(error); return { error, message: "Erro ao obter conteúdo dos emails", @@ -40,11 +39,9 @@ export async function sendEmail() { json = await getMailContents(); if (json.length == 0) { - console.log("Não há processos atrasados"); return true; } if (!senha) { - console.log("Não há senha"); return false; } @@ -199,7 +196,6 @@ export async function sendEmail() { transport.sendMail(message); process = []; } catch (err) { - console.log("Error occurred. " + err.message); return false; } } diff --git a/src/controllers/FlowController.js b/src/controllers/FlowController.js index 584702e7..2065d18d 100644 --- a/src/controllers/FlowController.js +++ b/src/controllers/FlowController.js @@ -131,7 +131,6 @@ class FlowController { message: `Não há fluxos com o processo '${record}'`, }); } catch (error) { - console.log(error); return res.status(500).json({ error, message: `Erro ao buscar fluxos do processo ${record}`, @@ -181,12 +180,10 @@ class FlowController { flowsWithSequences.push(flowSequence); } - console.log("aquii pelo amor"); return res .status(200) .json({ flows: flowsWithSequences || [], totalPages }); } catch (error) { - console.log(error); return res .status(500) .json({ error, message: "Impossível obter fluxos" }); @@ -218,7 +215,6 @@ class FlowController { return res.status(200).json(flowSequence); } catch (error) { - console.log(error); return res.status(500).json({ error, message: `Impossível obter fluxo ${idFlow}`, @@ -258,7 +254,6 @@ class FlowController { sequences: sequences, }); } catch (error) { - console.log(error); return res .status(500) .json({ error, message: "Impossível ler sequências" }); @@ -277,7 +272,6 @@ class FlowController { return res.status(200).json(flowStages); } catch (error) { - console.log(error); return res .status(500) .json({ error, message: "Erro ao ler fluxos ligados a etapas" }); @@ -304,7 +298,6 @@ class FlowController { res.status(200).json({ usersToNotify: result }); } catch (error) { - console.log(error); res.status(500).json({ error, message: "Impossível obter usuários que devem ser notificados no fluxo", @@ -327,7 +320,6 @@ class FlowController { ? res.status(status).json(json) : res.status(status).json({ message }); } catch (error) { - console.log(error); return res.status(500).json({ error: "Impossível criar fluxo" }); } } @@ -368,7 +360,6 @@ class FlowController { : res.status(status).json({ message }); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Impossível criar fluxo" }); } } @@ -392,7 +383,6 @@ class FlowController { return res.status(404).json({ message: "Fluxo não encontrado" }); } } catch (error) { - console.log(error); return res .status(500) .json({ error, message: "Impossível apagar fluxo" }); @@ -417,7 +407,6 @@ class FlowController { message: `Desassociação entre fluxo '${idFlow}' e etapas '${idStageA}' e '${idStageB}' concluída`, }); } catch (error) { - console.log(error); return res.status(500).json({ error, message: `Falha ao desassociar fluxo '${idFlow}' e etapas '${idStageA}' e '${idStageB}'`, diff --git a/src/controllers/ProcessController.js b/src/controllers/ProcessController.js index 71b592a6..efbd16c2 100644 --- a/src/controllers/ProcessController.js +++ b/src/controllers/ProcessController.js @@ -3,6 +3,7 @@ import FlowStage from "../models/FlowStage.js"; import Priority from "../models/Priority.js"; import Process from "../models/Process.js"; import Flow from "../models/Flow.js"; +import Stage from "../models/Stage.js"; import Database from "../database/index.js"; import { QueryTypes } from "sequelize"; import { tokenToUser } from "../middleware/authMiddleware.js"; @@ -17,6 +18,23 @@ const recordFilter = (record) => { return record.replace(regex, ""); }; +const IsUtilDay = (data) => { + const diaDaSemana = data.getDay(); + return diaDaSemana >= 1 && diaDaSemana <= 5; +}; + +const handleVerifyDate = (startDate, duration) => { + let days = 0; + while (duration > 0) { + startDate.setDate(startDate.getDate() + 1); + if (IsUtilDay(startDate)) { + duration--; + } + days++; + } + return days; +}; + const validateRecord = (record) => { const filtered = recordFilter(record); return { @@ -44,7 +62,7 @@ class ProcessController { }); if (!processes || processes.length === 0) { - return res.status(404).json({ error: "Não há processos" }); + return res.status(204).json({ error: "Não há processos" }); } else { const processesWithFlows = []; for (const process of processes) { @@ -67,6 +85,7 @@ class ProcessController { idPriority: process.idPriority, idFlow: flowProcessesIdFlows, status: process.status, + progress: process.progress, }); } @@ -78,7 +97,6 @@ class ProcessController { .json({ processes: processesWithFlows, totalPages }); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Erro ao buscar processos", @@ -137,7 +155,6 @@ class ProcessController { return res.json(process); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: `Erro ao procurar processo ${idProcess}`, @@ -181,13 +198,11 @@ class ProcessController { .json({ message: "Criado com sucesso!", flowProcess }); } } catch (error) { - console.log(error); return res.status(500).json(error); } } return res.status(404).json({ message: "Erro na criação de processo" }); } catch (error) { - console.log(error); return res.status(500).json(error); } } @@ -219,7 +234,6 @@ class ProcessController { return res.status(200).json(processes); } catch (error) { - console.log(error); return res .status(500) .json({ error, message: "Erro ao buscar processos" }); @@ -262,12 +276,37 @@ class ProcessController { effectiveDate: new Date(), } : {}; + let tempProgress = []; + if (process.status === "notStarted" && status === "inProgress") { + const currentStage = await Stage.findOne({ + where: { idStage: flowStages[0].idStageA }, + }); + + const stageStartDate = new Date(); + const stageEndDate = new Date(stageStartDate); + stageEndDate.setDate( + stageEndDate.getDate() + + handleVerifyDate(stageStartDate, currentStage.duration) + ); + + const progressData = { + idStage: flowStages[0].idStageA, + entrada: new Date(), + vencimento: stageEndDate, + }; + tempProgress.push(progressData); + } else { + // let aux = []; + // aux.push(process.progress); + tempProgress = process.progress; + } process.set({ nickname, idStage: idStage || process.idStage, idPriority: priority, status, + progress: tempProgress, ...startingProcess, }); @@ -309,13 +348,12 @@ class ProcessController { return res.status(200).json({ message: "OK" }); } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Impossível apagar" }); } } async updateProcessStage(req, res) { - const { record, from, to, idFlow } = req.body; + const { record, from, to, idFlow, isNextStage } = req.body; if ( isNaN(parseInt(from)) || @@ -355,10 +393,57 @@ class ProcessController { message: `Não há a transição da etapa '${to}' para '${from}' no fluxo '${idFlow}'`, }); } + + const currentProcess = await Process.findOne({ + where: { record }, + }); + const currentToStage = await Stage.findOne({ + where: { idStage: to }, + }); + + const currentFromStage = await Stage.findOne({ + where: { idStage: from }, + }); + + let tempProgress = []; + let maturityDate; + const stageStartDate = new Date(); + const stageEndDate = new Date(stageStartDate); + stageEndDate.setDate( + stageEndDate.getDate() + + handleVerifyDate(stageStartDate, currentToStage.duration) + ); + + maturityDate = stageEndDate; + + if (isNextStage) { + const progressData = { + idStage: to, + entrada: new Date(), + vencimento: maturityDate, + }; + tempProgress = currentProcess.progress; + const index = tempProgress.findIndex((x) => x.idStage == to); + index === -1 && tempProgress.push(progressData); + } else { + tempProgress = Array.isArray(currentProcess.progress) + ? currentProcess.progress + : [currentProcess.progres]; + tempProgress.pop(); + tempProgress[tempProgress.length - 1] = { + idStage: to, + entrada: new Date(), + vencimento: maturityDate, + }; + } + + console.log("FROM TO", currentProcess.idStage, from, to); + const process = await Process.update( { idStage: to, effectiveDate: new Date(), + progress: tempProgress, }, { where: { @@ -367,7 +452,6 @@ class ProcessController { }, } ); - console.log(process[0]); if (process[0] > 0) { return res.status(200).json({ message: "Etapa atualizada com sucesso", @@ -424,12 +508,10 @@ class ProcessController { } ); - console.log("updateResult = ", updateResult); return res.status(200).json({ message: "Comentário adicionado com sucesso", }); } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Falha ao adicionar comentário", diff --git a/src/controllers/RoleController.js b/src/controllers/RoleController.js index 36146728..04f00e53 100644 --- a/src/controllers/RoleController.js +++ b/src/controllers/RoleController.js @@ -63,7 +63,6 @@ class RoleController { }); return res.json(role); } catch (error) { - console.log(error); return res.status(error).json(error); } } diff --git a/src/controllers/StageController.js b/src/controllers/StageController.js index e44d26d4..9c767d5e 100644 --- a/src/controllers/StageController.js +++ b/src/controllers/StageController.js @@ -51,7 +51,6 @@ class StageController { return res.json(stage); } catch (error) { - console.log(error); return res.status(error).json(error); } } diff --git a/src/controllers/UnitController.js b/src/controllers/UnitController.js index f4535e6d..e4dcb711 100644 --- a/src/controllers/UnitController.js +++ b/src/controllers/UnitController.js @@ -13,7 +13,6 @@ class UnitController { 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", @@ -29,7 +28,6 @@ class UnitController { }); return res.json(unit); } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Erro ao criar unidade", @@ -127,7 +125,6 @@ class UnitController { }; return res.status(200).json(userNoPassword); } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Erro ao configurar usuário como administrador", @@ -154,7 +151,6 @@ class UnitController { await user.save(); return res.status(200).json(user); } catch (error) { - console.log(error); return res.status(500).json({ error: "Erro ao configurar usuário como administrador", }); diff --git a/src/controllers/UserContoller.js b/src/controllers/UserContoller.js index 0fea5396..1a204617 100644 --- a/src/controllers/UserContoller.js +++ b/src/controllers/UserContoller.js @@ -46,7 +46,6 @@ class UserController { }); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: "erro inesperado" }); } } @@ -153,7 +152,6 @@ class UserController { return res.status(200).json({ users: mappedUsers || [] }); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Erro ao listar usuários aceitos ou não", @@ -176,8 +174,6 @@ class UserController { }); return res.json(user); } catch (error) { - console.log(error); - if (error.name === "SequelizeUniqueConstraintError") { const errorMessages = { cpf: "Este CPF já foi cadastrado na plataforma.", @@ -215,7 +211,6 @@ class UserController { }); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Impossível atualizar email", @@ -240,7 +235,6 @@ class UserController { }); } } catch (error) { - console.log(error); return res.status(500).json({ message: "Usuário não atualizado!" }); } } @@ -266,7 +260,6 @@ class UserController { return res.status(400).json({ message: "Senha inválida!" }); } } catch (error) { - console.log(error); return res.status(500).json({ error, message: "Erro a atualizar usuário ", @@ -310,7 +303,6 @@ class UserController { }); } } catch (error) { - console.log("error", error); return res.status(500).json({ error, message: "Falha ao aceitar usuário", @@ -332,7 +324,6 @@ class UserController { }); } } catch (error) { - console.log("error", error); return res.status(500).json({ error, message: "Erro ao negar pedido do usuário", diff --git a/src/database/migrations/20230614132802-add-progress-column-in-process.js b/src/database/migrations/20230614132802-add-progress-column-in-process.js new file mode 100644 index 00000000..f8576147 --- /dev/null +++ b/src/database/migrations/20230614132802-add-progress-column-in-process.js @@ -0,0 +1,15 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addColumn("process", "progress", { + type: Sequelize.ARRAY(Sequelize.JSON), + allowNull: true, + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeColumn("process", "progress"); + }, +}; diff --git a/src/models/Process.js b/src/models/Process.js index b71e3194..62ef4355 100644 --- a/src/models/Process.js +++ b/src/models/Process.js @@ -39,6 +39,10 @@ class Process extends Model { allowNull: false, defaultValue: "notStarted", }, + progress: { + type: DataTypes.ARRAY(DataTypes.JSON), + allowNull: true, + }, }, { sequelize, diff --git a/src/tests/__tests__/test_emailer.js b/src/tests/__tests__/test_emailer.js index 29a7d8fe..67834cbd 100644 --- a/src/tests/__tests__/test_emailer.js +++ b/src/tests/__tests__/test_emailer.js @@ -89,17 +89,9 @@ describe("Test for function sendEmail", () => { const result = sendEmail(); expect(result).toBeTruthy(); }); - it("Retorno dos console.log", async () => { - const mockGetMailContents = jest.fn().mockResolvedValue([]); - console.log = jest.fn(); - await sendEmail(mockGetMailContents); - expect(console.log).toHaveBeenCalledTimes(2); - }); it("should log 'Não há senha' and return false if password is not set", async () => { process.env.CAPJU_EMAIL_PASSWORD = ""; - console.log = jest.fn(); const result = await sendEmail(); - expect(console.log).toHaveBeenCalledWith("Não há senha"); expect(result).toBe(false); delete process.env.CAPJU_EMAIL_PASSWORD; }); diff --git a/src/tests/__tests__/test_flow_routes.js b/src/tests/__tests__/test_flow_routes.js index 1395ab4d..3feca6b3 100644 --- a/src/tests/__tests__/test_flow_routes.js +++ b/src/tests/__tests__/test_flow_routes.js @@ -5,8 +5,6 @@ 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"; describe("flow endpoints", () => { beforeEach(async () => { diff --git a/src/tests/__tests__/test_process_routes.js b/src/tests/__tests__/test_process_routes.js index 9e8c8583..8c90607c 100644 --- a/src/tests/__tests__/test_process_routes.js +++ b/src/tests/__tests__/test_process_routes.js @@ -315,11 +315,12 @@ describe("process endpoints", () => { .put(`/processUpdateStage`) .send(processStageData); - expect(updatedProcessStage.status).toBe(200); expect(updatedProcessStage.body.message).toEqual( "Etapa atualizada com sucesso" ); + expect(updatedProcessStage.status).toBe(200); }); + test("test", async () => { const testUser = { cpf: "12345678901", diff --git a/src/tests/__tests__/test_user_routes.js b/src/tests/__tests__/test_user_routes.js index d88dc84f..87df0bdc 100644 --- a/src/tests/__tests__/test_user_routes.js +++ b/src/tests/__tests__/test_user_routes.js @@ -81,8 +81,6 @@ describe("user endpoints", () => { expect(usersDb.length).toBe(testUsers.length + 2); - console.info(usersDb); - expect(usersDb).toEqual( expect.arrayContaining( expectedTestUsers.map((etu) => { @@ -142,8 +140,6 @@ describe("user endpoints", () => { where: { accepted: true, idRole: 5 }, }); - console.info(acceptedUsersDb[0].dataValues.cpf); - // Only the administrator is accepted expect(acceptedUsersDb.length).toBe(1); expect(acceptedUsersDb[0].dataValues.cpf).toEqual(adminUser[0].cpf); diff --git a/src/tests/__tests__/teste_role_routes.js b/src/tests/__tests__/teste_role_routes.js index 2070815a..58c819f9 100644 --- a/src/tests/__tests__/teste_role_routes.js +++ b/src/tests/__tests__/teste_role_routes.js @@ -2,7 +2,6 @@ import { Database } from "../TestDatabase.js"; import "sequelize"; import supertest from "supertest"; import { app, injectDB } from "../TestApp"; -import Unit from "../../models/Unit.js"; describe("role endpoints", () => { beforeEach(async () => {