Skip to content

Commit

Permalink
Merge pull request #2 from fga-eps-mds/testes
Browse files Browse the repository at this point in the history
Testes
  • Loading branch information
guipeeix7 authored Dec 17, 2024
2 parents dbbcb48 + 536128e commit 82ca953
Show file tree
Hide file tree
Showing 10 changed files with 558 additions and 146 deletions.
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ const config = {

// Whether to use watchman for file crawling
// watchman: true,
};

Check failure on line 207 in jest.config.js

View workflow job for this annotation

GitHub Actions / lint

Delete `⏎····⏎`

};
module.exports = config;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,5 @@
"prettier": "^3.3.3",
"supertest": "^7.0.0"
}

}
22 changes: 16 additions & 6 deletions src/Controllers/bankAccountController.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,30 @@ const getAll = async (req, res) => {

const getBankAccountbyId = async (req, res) => {
try {
const bankAccount = await BankAccount.findById(req.params.id); // Buscando conta pelo ID
const { id } = req.params;
if (!id || !mongoose.Types.ObjectId.isValid(id)) {
return res.status(500).send({ error: "ID inválido ou ausente" });
}
const bankAccount = await BankAccount.findById(id); // Buscando conta pelo ID
if (!bankAccount) {
return res.status(404).send({ message: "Conta não encontrada" }); // Enviando mensagem de erro se a conta não for encontrada
return res.status(404).send({ message: "Conta não encontrada" });
}
res.status(200).json(bankAccount); // Enviando conta bancária encontrada
} catch (error) {
// Log do erro para depuração
console.error("Erro ao buscar conta bancária:", error.message);

Check warning on line 63 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message }); // Enviando mensagem de erro
res.status(500).send({ error: error.message || "Erro interno" }); // Garantindo que a resposta tenha a chave 'error'
}
};


Check failure on line 68 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `⏎`
const deleteBankAccount = async (req, res) => {
try {

Check failure on line 70 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `⏎`

const { id } = req.params;

if (!id || !mongoose.Types.ObjectId.isValid(id)) {
return res.status(500).send({ error: "ID inválido ou ausente" });
}
const bankAccount = await BankAccount.findByIdAndDelete(req.params.id); // Deletando conta pelo ID
if (!bankAccount) {
return res.status(404).send({ message: "Conta não encontrada" }); // Enviando mensagem de erro se a conta não for encontrada
Expand All @@ -79,8 +89,8 @@ const deleteBankAccount = async (req, res) => {
const updateBankAccount = async (req, res) => {
try {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({ message: "ID inválido" });
if (!id || !mongoose.Types.ObjectId.isValid(id)) {
return res.status(500).send({ error: "ID inválido ou ausente" });
}

// Log dos dados recebidos
Expand Down
11 changes: 11 additions & 0 deletions src/Controllers/financialMovementsController.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
const FinancialMovements = require("../Models/financialMovementsSchema");

const validateCPF = (cpf) => {
return /\d{3}\.\d{3}\.\d{3}-\d{2}/.test(cpf);
};


Check failure on line 7 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `⏎`
const createFinancialMovements = async (req, res) => {
try {
console.log("Dados recebidos:", req.body);

Check warning on line 10 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
const financialMovementsData = req.body.financialMovementsData || {};
if (!financialMovementsData) {
return res.status(400).send({ error: "No data provided" });
}
if (!validateCPF(financialMovementsData.cpFCnpj)) {
return res.status(400).send({ error: "Invalid CPF" });

Check failure on line 16 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `··`
}
if (!financialMovementsData.contaOrigem) {

Check failure on line 18 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `··`
throw new Error("Database error");

Check failure on line 19 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `·`
}

// Criação da movimentação financeira
const financialMovement = new FinancialMovements(
Expand Down
17 changes: 16 additions & 1 deletion src/Controllers/financialReportController.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,26 @@ const generateFinancialReport = async (req, res) => {
const sanitizedTipoDocumento = sanitizeInput(tipoDocumento);
const sanitizedSitPagamento = sanitizeInput(sitPagamento);

const query = {};
const query = {
sitPagamento: sanitizedSitPagamento,
datadeVencimento: {
$gte: new Date(dataInicio),

Check failure on line 67 in src/Controllers/financialReportController.js

View workflow job for this annotation

GitHub Actions / lint

Insert `····`
$lte: new Date(dataFinal),

Check failure on line 68 in src/Controllers/financialReportController.js

View workflow job for this annotation

GitHub Actions / lint

Insert `····`
}

Check failure on line 69 in src/Controllers/financialReportController.js

View workflow job for this annotation

GitHub Actions / lint

Insert `,`
};
if (sanitizedNomeOrigem) query.nomeOrigem = sanitizedNomeOrigem;
if (sanitizedContaOrigem) query.contaOrigem = sanitizedContaOrigem;
if (sanitizedContaDestino) query.contaDestino = sanitizedContaDestino;
if (sanitizedTipoDocumento)
query.tipoDocumento = sanitizedTipoDocumento;
if (sanitizedNomeDestino) query.nomeDestino = sanitizedNomeDestino;
if (req.body.contaDestino) {
query.contaDestino = req.body.contaDestino;
}
if (req.body.contaOrigem) {
query.contaOrigem = req.body.contaOrigem;
}

if (sanitizedSitPagamento) {
const today = new Date(); // Data atual

Expand All @@ -80,6 +93,8 @@ const generateFinancialReport = async (req, res) => {
{ datadePagamento: { $eq: null } },
{ datadePagamento: { $gt: today } },
];
}else {
delete query.datadePagamento;
}
}

Expand Down
84 changes: 40 additions & 44 deletions src/Models/csvGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,25 @@ const { parse } = require("json2csv");
const formatNumericDate = (date) => {
if (!date) return "";
const d = new Date(date);
if (isNaN(d.getTime())) {
return ""; // Retorna string vazia se a data for inválida
}
const day = String(d.getUTCDate()).padStart(2, "0");
const month = String(d.getUTCMonth() + 1).padStart(2, "0");
const year = d.getUTCFullYear();
return `${day}/${month}/${year}`;
};

const generateFinancialReportCSV = (
financialMovements,
filePath,
includeFields
) => {
const generateFinancialReportCSV = (financialMovements, filePath, includeFields) => {
return new Promise((resolve, reject) => {
try {
// Define todos os campos possíveis
if (financialMovements.length === 0) {
fs.writeFileSync(filePath, "");
return resolve();
}

const allFields = {
tipoDocumento: {
label: "Tipo Documento",
value: "tipoDocumento",
},
tipoDocumento: { label: "Tipo Documento", value: "tipoDocumento" },
valorBruto: { label: "Valor Bruto", value: "valorBruto" },
valorLiquido: { label: "Valor Líquido", value: "valorLiquido" },
contaOrigem: { label: "Conta Origem", value: "contaOrigem" },
Expand All @@ -37,52 +37,48 @@ const generateFinancialReportCSV = (
label: "Data de Pagamento",
value: (row) => formatNumericDate(row.datadePagamento),
},
formaPagamento: {
label: "Forma de Pagamento",
value: "formadePagamento",
},
formaPagamento: { label: "Forma de Pagamento", value: "formaPagamento" },
sitPagamento: {
label: "Situação de Pagamento",
value: (row) => {
const today = new Date(); // Data atual
const paymentDate = row.datadePagamento
? new Date(row.datadePagamento)
: null;

// Verifica se a data de pagamento é nula ou se é uma data futura
return !paymentDate || paymentDate > today
? "Não pago"
: "Pago";
// Verificar se a linha ou o campo de data está ausente ou inválido
if (!row || row.datadePagamento == null) {
console.log("Linha sem data de pagamento:", row); // Log para debugar
return "Não pago"; // Retorna 'Não pago' se não houver data
}

// Verificar se a data é válida
const paymentDate = new Date(row.datadePagamento);
if (isNaN(paymentDate.getTime())) {
console.log("Data inválida:", row.datadePagamento); // Log para debugar
return "Não pago"; // Retorna 'Não pago' se a data for inválida
}

const today = new Date();
return paymentDate <= today ? "Pago" : "Não pago";
},
},

descricao: { label: "Descrição", value: "descricao" },
};

if (!includeFields || includeFields.length === 0) {
fs.writeFileSync(filePath, "");
return resolve();
}

// Reorder the includeFields array based on the desired order
const orderedFields = [
"tipoDocumento",
"valorBruto",
"valorLiquido",
"contaOrigem",
"nomeOrigem",
"contaDestino",
"nomeDestino",
"dataVencimento",
"dataPagamento",
"formaPagamento",
"sitPagamento",
"descricao",
];
const fields = includeFields.map((field) => allFields[field]).filter(Boolean);

// Filtra os campos com base no array `orderedFields`
const fields = orderedFields
.filter((field) => includeFields.includes(field)) // Filtra para pegar apenas os campos selecionados
.map((field) => allFields[field]); // Mapeia para o formato necessário pelo `json2csv`
if (fields.length === 0) {
fs.writeFileSync(filePath, "");
return resolve();
}

// Gera o CSV com os campos filtrados
const csv = parse(financialMovements, { fields });

console.log("Campos incluídos:", fields);
console.log("CSV gerado:", csv);

fs.writeFileSync(filePath, csv);
resolve();
} catch (error) {
Expand Down
60 changes: 59 additions & 1 deletion src/__tests__/bankAccountController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ describe("BankAccount API", () => {

console.log("Update Response:", response.body); // Adicione um log para depuração

expect(response.status).toBe(400);
expect(response.status).toBe(500);
});

it("should delete a bank account", async () => {
Expand Down Expand Up @@ -226,3 +226,61 @@ describe("BankAccount API", () => {
expect(response.status).toBe(404);
});
});
it("should return 500 when fetching a bank account with invalid ID", async () => {
const response = await request(app).get(`/finance/bankAccount/${null}`);

expect(response.status).toBe(500);
expect(response.body.error).toBe("ID inválido ou ausente");
});
it("should return 500 when updating a bank account with invalid ID", async () => {
const response = await request(app)
.patch(`/finance/updateBankAccount/${null}`)
.send({ name: "Conta Atualizada" });

expect(response.status).toBe(500);
expect(response.body.error).toBe("ID inválido ou ausente");
});
it("should delete a bank account", async () => {
const newAccount = await request(app)
.post("/finance/createBankAccount")
.send({
formData: {
name: "Conta a ser Deletada",
bank: "Banco Teste Deletar",

accaccountNumber: "33333333",
status: "Ativo",
accountType: "Conta Corrente",
},
}); const response = await request(app).delete(
`/finance/deleteBankAccount/${newAccount.body._id}`
);

expect(response.status).toBe(200);
expect(response.body.message).toBe("Conta deletada com sucesso");
});

it("should return 500 when deleting a bank account with invalid ID", async () => {
const response = await request(app).delete(`/finance/deleteBankAccount/${null}`);

expect(response.status).toBe(500);
expect(response.body.error).toBe("ID inválido ou ausente");
});

it("should return 500 if the name is invalid", async () => {
const response = await request(app)
.post("/finance/createBankAccount")
.send({
formData: {
name: 12345, // Tipo inválido
bank: "Banco Teste",
accountNumber: "98765432",
status: "Ativo",
accountType: "Conta Corrente",
},
});

expect(response.status).toBe(500);
expect(response.body.error).toBe("Tipo de dado incorreto");
});

Loading

0 comments on commit 82ca953

Please sign in to comment.