From 30b30d46b17786aed6cee7ca2834a360c336cbe9 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Wed, 24 Jul 2024 00:12:45 -0300 Subject: [PATCH 01/22] =?UTF-8?q?[fix:20]=20-Cria=C3=A7=C3=A3o=20do=20banc?= =?UTF-8?q?o=20de=20dados=20com=20POST,=20GET=20e=20DELETE=20by=20id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: @stroch Signed-off-by: Milena Linda --- package-lock.json | 69 ++++++++++++------------ src/Controllers/bankAccountController.js | 39 ++++++++++++++ src/Models/bankAccountSchema.js | 38 +++++++++++++ src/routes.js | 21 +++++--- 4 files changed, 126 insertions(+), 41 deletions(-) create mode 100644 src/Controllers/bankAccountController.js create mode 100644 src/Models/bankAccountSchema.js diff --git a/package-lock.json b/package-lock.json index d201c60..e29c51f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,9 +42,9 @@ } }, "node_modules/@mongodb-js/saslprep": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.7.tgz", - "integrity": "sha512-dCHW/oEX0KJ4NjDULBo3JiOaK5+6axtpBbS+ao2ZInoAL9/YRQLhXzSNAFz7hP4nzLkIqsfYAK/PDE3+XHny0Q==", + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.8.tgz", + "integrity": "sha512-qKwC/M/nNNaKUBMQ0nuzm47b7ZYWQHN3pcXq4IIcoSBc2hOIrflAxJduIvvqmhoz3gR2TacTAs8vlsCVPkiEdQ==", "dependencies": { "sparse-bitfield": "^3.0.3" } @@ -55,9 +55,9 @@ "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" }, "node_modules/@types/whatwg-url": { - "version": "11.0.4", - "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.4.tgz", - "integrity": "sha512-lXCmTWSHJvf0TRSO58nm978b8HJ/EdsSsEKLd3ODHFjo+3VGAyyTp4v50nWvwtzBxSMQrVOK7tcuN0zGPLICMw==", + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", "dependencies": { "@types/webidl-conversions": "*" } @@ -230,9 +230,9 @@ } }, "node_modules/bson": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/bson/-/bson-6.7.0.tgz", - "integrity": "sha512-w2IquM5mYzYZv6rs3uN2DZTOBe2a0zXLj53TGDqwF4l6Sz/XsISrisXOJihArF9+BZ6Cq/GjVht7Sjfmri7ytQ==", + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.8.0.tgz", + "integrity": "sha512-iOJg8pr7wq2tg/zSlCCHMi3hMm5JTOxLTagf3zxhcenHsFp+c6uOs6K7W5UE7A4QIJGtqh/ZovFNMP4mOPJynQ==", "engines": { "node": ">=16.20.1" } @@ -1111,12 +1111,12 @@ } }, "node_modules/mongodb": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.5.0.tgz", - "integrity": "sha512-Fozq68InT+JKABGLqctgtb8P56pRrJFkbhW0ux+x1mdHeyinor8oNzJqwLjV/t5X5nJGfTlluxfyMnOXNggIUA==", + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.7.0.tgz", + "integrity": "sha512-TMKyHdtMcO0fYBNORiYdmM25ijsHs+Njs963r4Tro4OQZzqYigAzYQouwWRg4OIaiLRUEGUh/1UAcH5lxdSLIA==", "dependencies": { "@mongodb-js/saslprep": "^1.1.5", - "bson": "^6.4.0", + "bson": "^6.7.0", "mongodb-connection-string-url": "^3.0.0" }, "engines": { @@ -1165,13 +1165,13 @@ } }, "node_modules/mongoose": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.3.5.tgz", - "integrity": "sha512-2zqeAjHjCqT1o5HeUCvkE9tUHsXwemnwEZ2SKnUxsaP8p1a+UcSQSNbnSuOzUVePMwLETrsvLIRdFLjsNfCgWA==", + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.5.1.tgz", + "integrity": "sha512-OhVcwVl91A1G6+XpjDcpkGP7l7ikZkxa0DylX7NT/lcEqAjggzSdqDxb48A+xsDxqNAr0ntSJ1yiE3+KJTOd5Q==", "dependencies": { - "bson": "^6.5.0", + "bson": "^6.7.0", "kareem": "2.6.3", - "mongodb": "6.5.0", + "mongodb": "6.7.0", "mpath": "0.9.0", "mquery": "5.0.0", "ms": "2.1.3", @@ -1210,9 +1210,9 @@ } }, "node_modules/mquery/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", "dependencies": { "ms": "2.1.2" }, @@ -1295,9 +1295,9 @@ } }, "node_modules/nodemon": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz", - "integrity": "sha512-xqlktYlDMCepBJd43ZQhjWwMw2obW/JRvkrLxq5RCNcuDDX1DbcPT+qT1IlIIdf+DhnWs90JpTMe+Y5KxOchvA==", + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", "dev": true, "dependencies": { "chokidar": "^3.5.2", @@ -1323,9 +1323,9 @@ } }, "node_modules/nodemon/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", "dev": true, "dependencies": { "ms": "2.1.2" @@ -1389,9 +1389,12 @@ } }, "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -1575,9 +1578,9 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "bin": { "semver": "bin/semver.js" }, diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js new file mode 100644 index 0000000..22b62ae --- /dev/null +++ b/src/Controllers/bankAccountController.js @@ -0,0 +1,39 @@ +const BankAccount = require('../Models/bankAccountSchema'); // Importação do modelo + +const createBankAccount = async (req, res) => { + try { + const bankAccount = new BankAccount(req.body); // Criação de nova instância do modelo com os dados da requisição + await bankAccount.save(); // Salvando no banco de dados + res.status(201).send(bankAccount); // Correção para enviar a conta criada + } catch (error) { + res.status(400).send(error); // Enviando erro caso ocorra + } +}; + +const getBankAccount = async (req, res) => { + try { + const bankAccount = await BankAccount.find(); + res.status(200).send(bankAccount); + } catch (error) { + res.status(500).send({ error: error.message }); // Certifique-se de que `res` está sendo manipulado corretamente aqui + } +}; + +const deleteBankAccount = async(req,res) =>{ + try{ + const bankAccount = await BankAccount.findByIdAndDelete(req.params.id); + if(!bankAccount){ + res.status(404).send('Conta não encontrada'); + } + res.status(200).send('Conta deletada com sucesso'); + } + catch(error){ + res.status(500).send({error:error.message}); + } +}; + +module.exports = { + createBankAccount, + getBankAccount, + deleteBankAccount +}; diff --git a/src/Models/bankAccountSchema.js b/src/Models/bankAccountSchema.js new file mode 100644 index 0000000..475b261 --- /dev/null +++ b/src/Models/bankAccountSchema.js @@ -0,0 +1,38 @@ +const mongoose = require('mongoose'); // Import mongoose + +const bankAccountSchema = new mongoose.Schema({ // Criação do schema + name: { + type: String, + required: true + }, + bank: { + type: String, + required: true + }, + accountType: { + type: String, + required: true, + enum: ['Conta Corrente', 'Poupança', 'Investimento', 'Caixa'] + }, + accountNumber: { + type: String, + required: false + }, + dv: { + type: Number, + required: false + }, + status: { + type: String, + default: 'Ativo', // Corrigido para definir 'Ativo' como valor padrão + required: true, + enum: ['Ativo', 'Inativo'] + }, + agency: { + type: String, + required: false + } +}); + +const BankAccount = mongoose.model('BankAccount', bankAccountSchema); // Criação do modelo a partir do schema +module.exports = BankAccount; // Exportação do modelo diff --git a/src/routes.js b/src/routes.js index c23d3b8..ed578c6 100644 --- a/src/routes.js +++ b/src/routes.js @@ -1,13 +1,18 @@ const express = require('express'); const routes = express.Router(); -const NewController = require('./Controllers/newController'); +const newController = require('./Controllers/newController'); +const bankAccountController = require('./Controllers/bankAccountController'); -// Private -// routes.get('/finance', tokenValidation, ???.getUsers); -// routes.get('/finance/:id', tokenValidation, ???.getUserById); +// Rotas Privadas (Comentadas por enquanto, você pode descomentar quando implementar a validação de token) +// router.get('/finance', tokenValidation, ???.getUsers); +// router.get('/finance/:id', tokenValidation, ???.getUserById); +routes.post('/finance/createBankAccount', bankAccountController.createBankAccount); +routes.get("/finance/bankAccount", bankAccountController.getBankAccount); +routes.delete('/finance/deleteBankAccount/:id', bankAccountController.deleteBankAccount); -// Public -routes.post('/finance/create', NewController.createNew); -routes.get('/finance', NewController.getNews); +// Rotas Públicas -module.exports = routes; \ No newline at end of file +routes.post('/finance/create', newController.createNew); +routes.get('/finance', newController.getNews); + +module.exports = routes; From ba77d2018880c1a17739ec81cafc2f7d64851fd6 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Fri, 26 Jul 2024 14:02:53 -0300 Subject: [PATCH 02/22] [feat:20] - EndPoint de Post feito Co-Authored-by: @storch7 Signed-off-by: Milena Linda --- src/Controllers/bankAccountController.js | 45 +++++++++++++++--------- src/Models/bankAccountSchema.js | 5 ++- src/routes.js | 1 + 3 files changed, 34 insertions(+), 17 deletions(-) diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js index 22b62ae..21ba63b 100644 --- a/src/Controllers/bankAccountController.js +++ b/src/Controllers/bankAccountController.js @@ -2,33 +2,46 @@ const BankAccount = require('../Models/bankAccountSchema'); // Importação do m const createBankAccount = async (req, res) => { try { - const bankAccount = new BankAccount(req.body); // Criação de nova instância do modelo com os dados da requisição - await bankAccount.save(); // Salvando no banco de dados - res.status(201).send(bankAccount); // Correção para enviar a conta criada + // Log dos dados recebidos para depuração + console.log('Dados recebidos:', req.body); + + // Validação simples dos dados + const formData = req.body.formData; + + const bankAccount = new BankAccount(formData); // Criação de uma nova conta bancária + await bankAccount.save(); // Salvando a conta bancária no banco de dados + console.log('Conta bancária criada com sucesso:', bankAccount); + res.status(201).send(bankAccount); // Enviando resposta de sucesso + } catch (error) { - res.status(400).send(error); // Enviando erro caso ocorra + // Log do erro para depuração + console.error('Erro ao criar conta bancária:', error.message); + res.status(400).send({ error: error.message }); // Enviando erro caso ocorra } }; const getBankAccount = async (req, res) => { try { - const bankAccount = await BankAccount.find(); - res.status(200).send(bankAccount); + const bankAccounts = await BankAccount.find(); // Obtendo todas as contas bancárias + res.status(200).send(bankAccounts); } catch (error) { - res.status(500).send({ error: error.message }); // Certifique-se de que `res` está sendo manipulado corretamente aqui + // Log do erro para depuração + console.error('Erro ao listar contas bancárias:', error.message); + res.status(500).send({ error: error.message }); // Enviando mensagem de erro } }; -const deleteBankAccount = async(req,res) =>{ - try{ - const bankAccount = await BankAccount.findByIdAndDelete(req.params.id); - if(!bankAccount){ - res.status(404).send('Conta não encontrada'); +const deleteBankAccount = async (req, res) => { + try { + 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 } - res.status(200).send('Conta deletada com sucesso'); - } - catch(error){ - res.status(500).send({error:error.message}); + res.status(200).send({ message: 'Conta deletada com sucesso' }); + } catch (error) { + // Log do erro para depuração + console.error('Erro ao deletar conta bancária:', error.message); + res.status(500).send({ error: error.message }); // Enviando mensagem de erro } }; diff --git a/src/Models/bankAccountSchema.js b/src/Models/bankAccountSchema.js index 475b261..f89609a 100644 --- a/src/Models/bankAccountSchema.js +++ b/src/Models/bankAccountSchema.js @@ -24,13 +24,16 @@ const bankAccountSchema = new mongoose.Schema({ // Criação do schema }, status: { type: String, - default: 'Ativo', // Corrigido para definir 'Ativo' como valor padrão required: true, enum: ['Ativo', 'Inativo'] }, agency: { type: String, required: false + }, + pix: { + type: String, + required: false } }); diff --git a/src/routes.js b/src/routes.js index ed578c6..9d52cf0 100644 --- a/src/routes.js +++ b/src/routes.js @@ -3,6 +3,7 @@ const routes = express.Router(); const newController = require('./Controllers/newController'); const bankAccountController = require('./Controllers/bankAccountController'); + // Rotas Privadas (Comentadas por enquanto, você pode descomentar quando implementar a validação de token) // router.get('/finance', tokenValidation, ???.getUsers); // router.get('/finance/:id', tokenValidation, ???.getUserById); From ca8b51b64a83a78bafcc18734fe85c17fb9e3f94 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Sat, 27 Jul 2024 19:50:30 -0300 Subject: [PATCH 03/22] =?UTF-8?q?[feat:20]=20-=20Ajuste=20para=20m=C3=A9to?= =?UTF-8?q?do=20de=20GET?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-by: @storch7 Signed-off-by: Milena Linda --- src/Controllers/bankAccountController.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js index 21ba63b..7d5fa66 100644 --- a/src/Controllers/bankAccountController.js +++ b/src/Controllers/bankAccountController.js @@ -22,12 +22,21 @@ const createBankAccount = async (req, res) => { const getBankAccount = async (req, res) => { try { - const bankAccounts = await BankAccount.find(); // Obtendo todas as contas bancárias - res.status(200).send(bankAccounts); + // Retorna apenas a conta bancária do nome fornecido + if (req.query.name) { + const bankAccount = await BankAccount.findOne({ name: req.query.name }); + + if (bankAccount) { + return res.status(200).json(bankAccount); + } else { + return res.status(404).json({ message: 'Conta não encontrada' }); + } + } else { + return res.status(400).json({ message: 'Nome não fornecido' }); + } } catch (error) { - // Log do erro para depuração - console.error('Erro ao listar contas bancárias:', error.message); - res.status(500).send({ error: error.message }); // Enviando mensagem de erro + console.error(error); + return res.status(500).json({ message: 'Erro interno do servidor' }); } }; From 598f716c876eb66d8e2ff258f2c915b931f80705 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Sun, 28 Jul 2024 15:07:05 -0300 Subject: [PATCH 04/22] =?UTF-8?q?[feat:20]=20-=20Ajuste=20para=20m=C3=A9to?= =?UTF-8?q?do=20de=20GET?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-by: @storch7 Signed-off-by: Milena Linda --- src/Controllers/bankAccountController.js | 17 ++++++++++++++++- src/Models/bankAccountSchema.js | 3 ++- src/routes.js | 1 + 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js index 7d5fa66..e48dca9 100644 --- a/src/Controllers/bankAccountController.js +++ b/src/Controllers/bankAccountController.js @@ -40,6 +40,20 @@ const getBankAccount = async (req, res) => { } }; +const getBankAccountbyId = async (req, res) => { + try { + const bankAccount = await BankAccount.findById(req.params.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 + } + 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); + res.status(500).send({ error: error.message }); // Enviando mensagem de erro + } +}; + const deleteBankAccount = async (req, res) => { try { const bankAccount = await BankAccount.findByIdAndDelete(req.params.id); // Deletando conta pelo ID @@ -57,5 +71,6 @@ const deleteBankAccount = async (req, res) => { module.exports = { createBankAccount, getBankAccount, - deleteBankAccount + deleteBankAccount, + getBankAccountbyId }; diff --git a/src/Models/bankAccountSchema.js b/src/Models/bankAccountSchema.js index f89609a..88bfa86 100644 --- a/src/Models/bankAccountSchema.js +++ b/src/Models/bankAccountSchema.js @@ -3,7 +3,8 @@ const mongoose = require('mongoose'); // Import mongoose const bankAccountSchema = new mongoose.Schema({ // Criação do schema name: { type: String, - required: true + required: true, + unique: true }, bank: { type: String, diff --git a/src/routes.js b/src/routes.js index 9d52cf0..ec42880 100644 --- a/src/routes.js +++ b/src/routes.js @@ -9,6 +9,7 @@ const bankAccountController = require('./Controllers/bankAccountController'); // router.get('/finance/:id', tokenValidation, ???.getUserById); routes.post('/finance/createBankAccount', bankAccountController.createBankAccount); routes.get("/finance/bankAccount", bankAccountController.getBankAccount); +routes.get("/finance/bankAccount/:id", bankAccountController.getBankAccountbyId); routes.delete('/finance/deleteBankAccount/:id', bankAccountController.deleteBankAccount); // Rotas Públicas From bef13b1dee4584c7e32fcca28e3505c4064393d1 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Sun, 28 Jul 2024 20:56:53 -0300 Subject: [PATCH 05/22] [feat:20] - Update de dados Co-Authored-by: @storch7 Signed-off-by: Milena Linda --- src/Controllers/bankAccountController.js | 18 +++++++++++++++++- src/routes.js | 2 ++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js index e48dca9..a5c8c1c 100644 --- a/src/Controllers/bankAccountController.js +++ b/src/Controllers/bankAccountController.js @@ -68,9 +68,25 @@ const deleteBankAccount = async (req, res) => { } }; +const updateBankAccount = async (req, res) => { + try { + const bankAccount = await BankAccount.findByIdAndUpdate(req.params.id, req.body, { new: true }); // Atualizando 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 + } + res.status(200).send(bankAccount); // Enviando conta atualizada + } + catch (error) { + // Log do erro para depuração + console.error('Erro ao atualizar conta bancária:', error.message); + res.status(500).send({ error: error.message }); // Enviando mensagem de erro + } +} + module.exports = { createBankAccount, getBankAccount, deleteBankAccount, - getBankAccountbyId + getBankAccountbyId, + updateBankAccount }; diff --git a/src/routes.js b/src/routes.js index ec42880..8af799f 100644 --- a/src/routes.js +++ b/src/routes.js @@ -11,6 +11,8 @@ routes.post('/finance/createBankAccount', bankAccountController.createBankAccoun routes.get("/finance/bankAccount", bankAccountController.getBankAccount); routes.get("/finance/bankAccount/:id", bankAccountController.getBankAccountbyId); routes.delete('/finance/deleteBankAccount/:id', bankAccountController.deleteBankAccount); +routes.patch('/finance/updateBankAccount/:id', bankAccountController.updateBankAccount); + // Rotas Públicas From 2fe76cb312872ba53e6d72bab483d163bad87888 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Sun, 28 Jul 2024 22:56:38 -0300 Subject: [PATCH 06/22] [feat:20] - Update de dados corretos Co-Authored-by: @storch7 Signed-off-by: Milena Linda --- src/Controllers/bankAccountController.js | 41 ++++++++++++++++++------ src/routes.js | 2 ++ 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js index a5c8c1c..687c82c 100644 --- a/src/Controllers/bankAccountController.js +++ b/src/Controllers/bankAccountController.js @@ -1,3 +1,5 @@ +const mongoose = require('mongoose'); // Importar mongoose + const BankAccount = require('../Models/bankAccountSchema'); // Importação do modelo const createBankAccount = async (req, res) => { @@ -20,6 +22,17 @@ const createBankAccount = async (req, res) => { } }; +const getAll = async (req,res) => { + + try { + const bankAccount = await BankAccount.find({}); + return res.status(200).send(bankAccount); + } catch (error) { + return res.status(400).send({ error }); + } +}; + + const getBankAccount = async (req, res) => { try { // Retorna apenas a conta bancária do nome fornecido @@ -70,23 +83,33 @@ const deleteBankAccount = async (req, res) => { const updateBankAccount = async (req, res) => { try { - const bankAccount = await BankAccount.findByIdAndUpdate(req.params.id, req.body, { new: true }); // Atualizando conta pelo ID + const { id } = req.params; + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).send({ message: 'ID inválido' }); + } + + // Log dos dados recebidos + console.log('Dados recebidos para atualização:', req.body); + + // Atualizar apenas os campos fornecidos + const bankAccount = await BankAccount.findByIdAndUpdate(id, req.body, { new: true, runValidators: true }); 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).send(bankAccount); // Enviando conta atualizada - } - catch (error) { - // Log do erro para depuração + + res.status(200).send(bankAccount); + } catch (error) { console.error('Erro ao atualizar conta bancária:', error.message); - res.status(500).send({ error: error.message }); // Enviando mensagem de erro + res.status(500).send({ error: error.message }); } -} +}; + module.exports = { createBankAccount, getBankAccount, deleteBankAccount, getBankAccountbyId, - updateBankAccount + updateBankAccount, + getAll }; diff --git a/src/routes.js b/src/routes.js index 8af799f..7ddc684 100644 --- a/src/routes.js +++ b/src/routes.js @@ -12,6 +12,8 @@ routes.get("/finance/bankAccount", bankAccountController.getBankAccount); routes.get("/finance/bankAccount/:id", bankAccountController.getBankAccountbyId); routes.delete('/finance/deleteBankAccount/:id', bankAccountController.deleteBankAccount); routes.patch('/finance/updateBankAccount/:id', bankAccountController.updateBankAccount); +routes.get('/finance/getBankAccount', bankAccountController.getAll) + // Rotas Públicas From 428f16a6ff4d6c73f3538329b99c78f9d242fdf0 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Mon, 29 Jul 2024 00:55:23 -0300 Subject: [PATCH 07/22] [feat:20] - Verifica nome repetido Co-Authored-by: @storch7 Signed-off-by: Milena Linda --- src/Controllers/bankAccountController.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/Controllers/bankAccountController.js b/src/Controllers/bankAccountController.js index 687c82c..dd3e0ab 100644 --- a/src/Controllers/bankAccountController.js +++ b/src/Controllers/bankAccountController.js @@ -7,10 +7,24 @@ const createBankAccount = async (req, res) => { // Log dos dados recebidos para depuração console.log('Dados recebidos:', req.body); - // Validação simples dos dados - const formData = req.body.formData; + // Acessando dados diretamente + const formData = req.body.formData || {}; // Fallback para objeto vazio se formData estiver ausente + const { name } = formData; - const bankAccount = new BankAccount(formData); // Criação de uma nova conta bancária + if (!name) { + return res.status(400).send({ error: 'Nome não fornecido' }); // Erro caso 'name' esteja faltando + } + + // Verifica se já existe uma conta bancária com o mesmo nome + const existingName = await BankAccount.findOne({ name }); + + if (existingName) { + // Mensagem de erro se o nome já estiver repetido + return res.status(409).send({ error: 'Nome já cadastrado' }); // Código 409 para conflito + } + + // Criação de uma nova conta bancária + const bankAccount = new BankAccount(formData); await bankAccount.save(); // Salvando a conta bancária no banco de dados console.log('Conta bancária criada com sucesso:', bankAccount); res.status(201).send(bankAccount); // Enviando resposta de sucesso From 81d3c5824c6e1f139613f7011a7590f8f9105e8b Mon Sep 17 00:00:00 2001 From: Davi Mesquita Date: Fri, 2 Aug 2024 00:24:19 -0300 Subject: [PATCH 08/22] =?UTF-8?q?[fix:18]=20-=20Arrumando=20o=20campo=20ob?= =?UTF-8?q?rigat=C3=B3rio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: @annacbrandao Signed-off-by: Davi Mesquita --- src/Models/supplierFormSchema.js | 17 ---- src/Util/utils.js | 148 +------------------------------ 2 files changed, 1 insertion(+), 164 deletions(-) diff --git a/src/Models/supplierFormSchema.js b/src/Models/supplierFormSchema.js index 72a1ac0..4b39ad7 100644 --- a/src/Models/supplierFormSchema.js +++ b/src/Models/supplierFormSchema.js @@ -12,9 +12,6 @@ const supplierFormSchema = new mongoose.Schema({ }, cpfCnpj: { type: String, - unique: true, - immutable: true, - sparse: true, }, statusFornecedor: { type: String, @@ -26,26 +23,18 @@ const supplierFormSchema = new mongoose.Schema({ }, email: { type: String, - unique: true, - sparse: true, }, nomeContato: { type: String, }, celular: { type: String, - unique: true, - sparse: true, }, telefone: { type: String, - unique: true, - sparse: true, }, cep: { type: String, - unique: true, - sparse: true, }, cidade: { type: String, @@ -97,18 +86,12 @@ const supplierFormSchema = new mongoose.Schema({ }, numeroBanco: { type: String, - unique: true, - sparse: true, }, dv: { type: String, - unique: true, - sparse: true, }, chavePix: { type: String, - unique: true, - sparse: true, }, createdAt: { type: Date, diff --git a/src/Util/utils.js b/src/Util/utils.js index 8ce730a..63af45a 100644 --- a/src/Util/utils.js +++ b/src/Util/utils.js @@ -2,153 +2,7 @@ const validator = (dados) => { if (typeof dados.nome !== "string" || dados.nome === "") { return "Nome ou Razão social inválidos"; } - - if (dados.tipoPessoa !== null) { - const tipoPessoaValidas = ["Jurídica", "Física"]; - if (!tipoPessoaValidas.includes(dados.tipoPessoa)) { - return "Tipo de pessoa inválida"; - } - } - - if (dados.cpfCnpj !== null) { - const cpfValido = /^(\d{3}\.\d{3}\.\d{3}-\d{2})$/; - const cnpjValido = /^(\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2})$/; - if ( - (!cpfValido.test(dados.cpfCnpj) && dados.tipoPessoa === "Física") || - (!cnpjValido.test(dados.cpfCnpj) && dados.tipoPessoa === "Jurídica") - ) { - return "CPF ou CNPJ inválido"; - } - } - - if (dados.statusFornecedor !== null) { - const statusFornecedorValido = ["Ativo", "Inativo"]; - if (!statusFornecedorValido.includes(dados.statusFornecedor)) { - return "Status de fornecedor inválido"; - } - } - - if (dados.naturezaTransacao !== null) { - const tipoTransacaoValida = ["Receita", "Despesa"]; - if (!tipoTransacaoValida.includes(dados.naturezaTransacao)) { - return "Tipo de transação inválida"; - } - } - - if (dados.email !== null) { - const emailValido = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailValido.test(dados.email)) { - return "E-mail inválido"; - } - } - - if (dados.nomeContato !== null) { - if (typeof dados.nomeContato !== "string") { - return "Nome de contato inválido"; - } - } - - if (dados.celular !== null) { - const celularValido = /^\(\d{2}\) \d{5}-\d{4}$/; - if (!celularValido.test(dados.celular)) { - return "Número de celular inválido"; - } - } - - if (dados.telefone !== null) { - const telefoneValido = /^\(\d{2}\) \d{4}-\d{4}$/; - if (!telefoneValido.test(dados.telefone)) { - return "Número de telefone inválido"; - } - } - - if (dados.cep !== null) { - const cepValido = /^\d{5}-\d{3}$/; - if (!cepValido.test(dados.cep)) { - return "Cep inválido"; - } - } - - if (dados.cidade !== null) { - if (typeof dados.cidade !== "string") { - return "Cidade inválida"; - } - } - - if (dados.uf_endereco !== null) { - const ufsValidos = [ - "AC", - "AL", - "AP", - "AM", - "BA", - "CE", - "DF", - "ES", - "GO", - "MA", - "MT", - "MS", - "MG", - "PA", - "PB", - "PR", - "PE", - "PI", - "RJ", - "RN", - "RS", - "RO", - "RR", - "SC", - "SP", - "SE", - "TO", - ]; - if (!ufsValidos.includes(dados.uf_endereco)) { - return "UF inválida"; - } - } - - if (dados.logradouro !== null) { - const logradouro = /^[a-zA-Z0-9\s,.()-]{5,100}$/; - if (!logradouro.test(dados.logradouro)) { - return "Logradouro inválido. Deve conter entre 5 e 100 caracteres."; - } - } - - if (dados.complemento !== null) { - if (typeof dados.complemento !== "string") { - return "Complemento inválido"; - } - } - - if (dados.agencia !== null) { - if (typeof dados.agencia !== "string") { - return "Agência inválida"; - } - } - - if (dados.numeroBanco !== null) { - const numeroValido = /^\d*$/; - if (!numeroValido.test(dados.numeroBanco)) { - return "Número inválido"; - } - } - - if (dados.dv !== null) { - const dvValido = /^\d*$/; - if (!dvValido.test(dados.dv)) { - return "DV inválido"; - } - } - - if (dados.chavePix !== null) { - if (typeof dados.chavePix !== "string") { - return "Chave Pix inválida"; - } - } - + return null; }; From 3501abd07aaf4971558a326affa28f2b4a7296a9 Mon Sep 17 00:00:00 2001 From: saracampss Date: Wed, 14 Aug 2024 04:06:10 -0300 Subject: [PATCH 09/22] [fix:3] - update sonar exclusions Signed-off-by: saracampss --- sonar-project.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index e723098..6aa4188 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -8,8 +8,8 @@ sonar.language=js sonar.sources=src -sonar.exclusions=*/metrics/*.py, jest.config.js, dist/, -sonar.tests=src/__tests__ +sonar.exclusions=**/*.test.jsx, **/*.test.js, **/metrics/*.py, vite.config.ts, .vitest.config.js, dist/ +sonar.tests=src/ sonar.test.inclusions=**/*.test.jsx, **/*.test.js sonar.javascript.lcov.reportPaths=./coverage/lcov.info sonar.testExecutionReportPaths=./coverage/coverage.xml From 9f2399931153d1e8c03cfce1b275a2d0a0147809 Mon Sep 17 00:00:00 2001 From: saracampss Date: Wed, 14 Aug 2024 04:07:23 -0300 Subject: [PATCH 10/22] [fix:3] - update release workflow Signed-off-by: saracampss --- .github/workflows/release.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8bce22c..8cd0390 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,9 +2,14 @@ name: backend-financeiro-release on: push: - branches: [main, devel] + branches: [main] tags: - "v*" + pull_request: + branches: + - main + - devel + types: [closed] jobs: generate-release: From 7cc833d7ee27697740a79c5ec6b0c55254278677 Mon Sep 17 00:00:00 2001 From: Diogo-Barboza Date: Sat, 17 Aug 2024 13:06:08 -0300 Subject: [PATCH 11/22] [fix:18] lint and format validation --- src/Util/utils.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Util/utils.js b/src/Util/utils.js index 63af45a..d6715c4 100644 --- a/src/Util/utils.js +++ b/src/Util/utils.js @@ -2,7 +2,7 @@ const validator = (dados) => { if (typeof dados.nome !== "string" || dados.nome === "") { return "Nome ou Razão social inválidos"; } - + return null; }; From 901e40cbdc61b5f99b20cbe841f681f62313ea25 Mon Sep 17 00:00:00 2001 From: AlGouvea Date: Mon, 19 Aug 2024 17:00:23 -0300 Subject: [PATCH 12/22] [tests:18] Adicionando testes de supplier-form --- .gitignore | 1 + package.json | 10 +- src/__tests__/suppllierFormController.test.js | 99 +++++++++++++++++++ 3 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/suppllierFormController.test.js diff --git a/.gitignore b/.gitignore index 31b1da4..8abdc9c 100644 --- a/.gitignore +++ b/.gitignore @@ -16,5 +16,6 @@ yarn-error.log .idea .vscode .env +package-lock.json /coverage \ No newline at end of file diff --git a/package.json b/package.json index 9a7dea4..f12adef 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,14 @@ "prettier": "^3.3.3" }, "devDependencies": { - "nodemon": "^3.1.0" + "@eslint/js": "^9.8.0", + "eslint": "^9.8.0", + "husky": "^8.0.0", + "jest": "^29.7.0", + "jest-sonar": "^0.2.16", + "mongodb-memory-server": "^10.0.0", + "nodemon": "^3.1.0", + "prettier": "^3.3.3", + "supertest": "^7.0.0" } } diff --git a/src/__tests__/suppllierFormController.test.js b/src/__tests__/suppllierFormController.test.js new file mode 100644 index 0000000..0be58c5 --- /dev/null +++ b/src/__tests__/suppllierFormController.test.js @@ -0,0 +1,99 @@ +const request = require("supertest"); +const express = require("express"); +const mongoose = require("mongoose"); +const cors = require("cors"); +const routes = require("../routes"); +const { MongoMemoryServer } = require("mongodb-memory-server"); + +const app = express(); +let mongoServer; + +const corsOptions = { + origin: "*", + methods: "GET,HEAD,PUT,PATCH,POST,DELETE", +}; + +app.use(cors(corsOptions)); +app.use(express.json()); +app.use(express.urlencoded({ extended: true })); + +app.use("/", routes); + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + const uri = mongoServer.getUri(); + + try { + await mongoose.connect(uri, { + useNewUrlParser: true, + useUnifiedTopology: true, + }); + } catch (err) { + console.error("Error connecting to MongoDB:", err); + process.exit(1); + } +}, 30000); + +afterAll(async () => { + await mongoose.connection.close(); + await mongoServer.stop(); +}, 30000); + +describe("Supplier Form Controller Tests", () => { + let supplierId; + + it("should create a new supplier form", async () => { + const res = await request(app) + .post("/SupplierForm/create") + .send({ + supplierData: { + nome: "Test Supplier", + email: "supplier@test.com", + celular: "123456789", + logradouro: "123 Supplier St", + }, + }); + + expect(res.status).toBe(201); + expect(res.body).toHaveProperty("_id"); + expect(res.body.nome).toBe("Test Supplier"); + + supplierId = res.body._id; + }); + + it("should get all supplier forms", async () => { + const res = await request(app).get("/SupplierForm"); + + expect(res.status).toBe(200); + expect(Array.isArray(res.body)).toBe(true); + }); + + it("should get a supplier form by ID", async () => { + const res = await request(app).get(`/SupplierForm/${supplierId}`); + + expect(res.status).toBe(200); + expect(res.body).toHaveProperty("nome", "Test Supplier"); + }); + + it("should update a supplier form by ID", async () => { + const res = await request(app) + .patch(`/SupplierForm/update/${supplierId}`) + .send({ supplierData: { nome: "Updated Supplier" } }); + + expect(res.status).toBe(200); + expect(res.body).toHaveProperty("nome", "Updated Supplier"); + }); + + it("should delete a supplier form by ID", async () => { + const res = await request(app).delete( + `/SupplierForm/delete/${supplierId}` + ); + + expect(res.status).toBe(200); + + const checkSupplier = await request(app).get( + `/SupplierForm/delete/${supplierId}` + ); + expect(checkSupplier.status).toBe(404); + }); +}); From 66b7607b2c5b06565680a014aa53d903fad00bef Mon Sep 17 00:00:00 2001 From: AlGouvea Date: Tue, 20 Aug 2024 18:13:11 -0300 Subject: [PATCH 13/22] [deploy] Configurando variavel de ambiente --- src/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index edb5aa5..daeb7e2 100644 --- a/src/index.js +++ b/src/index.js @@ -31,7 +31,7 @@ let url; if (NODE_ENV === "development") { url = MONGO_URI; } else { - url = `mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@${DB_HOST}`; + url = OFFICIAL_MONGO_URI; } mongoose From 2d47e8e0d6b2c4e3174762b321dec1432ebac1a3 Mon Sep 17 00:00:00 2001 From: AlGouvea Date: Tue, 20 Aug 2024 18:13:36 -0300 Subject: [PATCH 14/22] [deploy] Configurando variavel de ambiente --- src/index.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/index.js b/src/index.js index daeb7e2..597b109 100644 --- a/src/index.js +++ b/src/index.js @@ -8,10 +8,7 @@ const app = express(); const { NODE_ENV, - MONGO_INITDB_ROOT_USERNAME, - MONGO_INITDB_ROOT_PASSWORD, MONGO_URI, - DB_HOST, PORT, } = process.env; From c5bd8ee2a4c5550830ffc9c90d44a207b99e6409 Mon Sep 17 00:00:00 2001 From: AlGouvea Date: Tue, 20 Aug 2024 18:13:50 -0300 Subject: [PATCH 15/22] [deploy] Configurando variavel de ambiente --- src/index.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index 597b109..8bd2e14 100644 --- a/src/index.js +++ b/src/index.js @@ -6,11 +6,7 @@ const routes = require("./routes"); const app = express(); -const { - NODE_ENV, - MONGO_URI, - PORT, -} = process.env; +const { NODE_ENV, MONGO_URI, PORT } = process.env; const corsOption = { origin: "*", From 7326aa639b9c605c52e4badafb40463dd936253e Mon Sep 17 00:00:00 2001 From: AlGouvea Date: Tue, 20 Aug 2024 18:21:20 -0300 Subject: [PATCH 16/22] [fix:deploy] Importando variavel --- src/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 8bd2e14..f0de6c0 100644 --- a/src/index.js +++ b/src/index.js @@ -6,7 +6,7 @@ const routes = require("./routes"); const app = express(); -const { NODE_ENV, MONGO_URI, PORT } = process.env; +const { NODE_ENV, MONGO_URI, PORT, OFFICIAL_MONGO_URI } = process.env; const corsOption = { origin: "*", From 0bf2e951b6782be242676aa02cb8efe49d5c8080 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Fri, 23 Aug 2024 17:07:01 -0300 Subject: [PATCH 17/22] [test-20] - teste da bankAccountController Co-Authored-by: Diogo-Barboza Signed-off-by: Milena Linda --- package.json | 2 +- src/__tests__/bankAccountController.test.js | 153 ++++++++++++++++++++ 2 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/bankAccountController.test.js diff --git a/package.json b/package.json index f12adef..8a82a1a 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "check-format": "prettier --check .", "format": "prettier --write .", "lint:fix": "eslint --fix .", - "prepare": "husky install" + "postinstall": "npx husky install" }, "keywords": [], "author": "", diff --git a/src/__tests__/bankAccountController.test.js b/src/__tests__/bankAccountController.test.js new file mode 100644 index 0000000..4a9d77b --- /dev/null +++ b/src/__tests__/bankAccountController.test.js @@ -0,0 +1,153 @@ +const request = require("supertest"); +const express = require("express"); +const mongoose = require("mongoose"); +const { MongoMemoryServer } = require("mongodb-memory-server"); +const bankAccountRouter = require("../routes"); // Atualize o caminho para o arquivo de rotas + +let mongoServer; +let app = express(); + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + const uri = mongoServer.getUri(); + await mongoose.connect(uri, { + useNewUrlParser: true, + useUnifiedTopology: true, + }); + + app.use(express.json()); + app.use("/", bankAccountRouter); // Atualize o prefixo da rota para '/finance' +}, 30000); + +afterAll(async () => { + await mongoose.disconnect(); + await mongoServer.stop(); +}); + +describe("BankAccount API", () => { + it("should create a new bank account", async () => { + const response = await request(app) + .post("/finance/createBankAccount") // Atualize o caminho da rota + .send({ + formData: { + name: "Conta Teste", + bank: "Banco Teste", + accountNumber: "12345678", + status: "Ativo", + accountType: "Conta Corrente", + }, + }); + + console.log("Create Response:", response); // Adicione um log para depuração + + expect(response.status).toBe(201); + expect(response.body).toHaveProperty("name", "Conta Teste"); + }); + + it("should not create a bank account with an existing name", async () => { + await request(app) + .post("/finance/createBankAccount") // Atualize o caminho da rota + .send({ + formData: { + name: "Conta Teste", + bank: "Banco Teste", + accountNumber: "12345678", + status: "Ativo", + accountType: "Conta Corrente", + }, + }); + + const response = await request(app) + .post("/finance/createBankAccount") // Atualize o caminho da rota + .send({ + formData: { + name: "Conta Teste", + bank: "Banco Teste", + accountNumber: "87654321", + }, + }); + + console.log("Conflict Response:", response.body); // Adicione um log para depuração + + expect(response.status).toBe(409); + expect(response.body.error).toBe("Nome já cadastrado"); + }); + + it("should fetch all bank accounts", async () => { + const response = await request(app).get("/finance/getBankAccount"); // Atualize o caminho da rota + + console.log("Fetch All Response:", response.body); // Adicione um log para depuração + + expect(response.status).toBe(200); + expect(Array.isArray(response.body)).toBe(true); + }); + + it("should fetch a bank account by ID", async () => { + const newAccount = await request(app) + .post("/finance/createBankAccount") // Atualize o caminho da rota + .send({ + formData: { + name: "Conta Teste ID", + bank: "Banco Teste ID", + accountNumber: "11111111", + status: "Ativo", + accountType: "Conta Corrente", + }, + }); + + const response = await request(app).get( + `/finance/bankAccount/${newAccount.body._id}` + ); // Atualize o caminho da rota + + console.log("Fetch By ID Response:", response.body); // Adicione um log para depuração + + expect(response.status).toBe(200); + expect(response.body.name).toBe("Conta Teste ID"); + }); + + it("should update a bank account", async () => { + const newAccount = await request(app) + .post("/finance/createBankAccount") // Atualize o caminho da rota + .send({ + formData: { + name: "Conta a ser Atualizada", + bank: "Banco Teste Atualização", + accountNumber: "22222222", + status: "Ativo", + accountType: "Conta Corrente", + }, + }); + + const response = await request(app) + .patch(`/finance/updateBankAccount/${newAccount.body._id}`) // Atualize o caminho da rota + .send({ name: "Conta Atualizada" }); + + console.log("Update Response:", response.body); // Adicione um log para depuração + + expect(response.status).toBe(200); + expect(response.body.name).toBe("Conta Atualizada"); + }); + + it("should delete a bank account", async () => { + const newAccount = await request(app) + .post("/finance/createBankAccount") // Atualize o caminho da rota + .send({ + formData: { + name: "Conta a ser Deletada", + bank: "Banco Teste Deletar", + accountNumber: "33333333", + status: "Ativo", + accountType: "Conta Corrente", + }, + }); + + const response = await request(app).delete( + `/finance/deleteBankAccount/${newAccount.body._id}` + ); // Atualize o caminho da rota + + console.log("Delete Response:", response.body); // Adicione um log para depuração + + expect(response.status).toBe(200); + expect(response.body.message).toBe("Conta deletada com sucesso"); + }); +}); From 09496f95fbe33698ed1e29d709180161e00fcfd8 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Fri, 23 Aug 2024 17:17:33 -0300 Subject: [PATCH 18/22] [test-20] - teste da bankAccountController Co-Authored-by: Diogo-Barboza Signed-off-by: Milena Linda --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8a82a1a..90277e2 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "check-format": "prettier --check .", "format": "prettier --write .", "lint:fix": "eslint --fix .", - "postinstall": "npx husky install" + "prepare": "husky install" }, "keywords": [], "author": "", From e526785b280079910be3446601feb47800ca0661 Mon Sep 17 00:00:00 2001 From: saracampss Date: Sun, 25 Aug 2024 21:23:34 -0300 Subject: [PATCH 19/22] [devops:3] - add step to check if branch or tag on sonar metrics Signed-off-by: saracampss --- metrics/sonar-metrics.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/metrics/sonar-metrics.py b/metrics/sonar-metrics.py index d9eb945..906045f 100644 --- a/metrics/sonar-metrics.py +++ b/metrics/sonar-metrics.py @@ -27,14 +27,18 @@ def generate_metrics(): # nome do repositório, vem como argumento no release.yml repository_name = sys.argv[1] # nome da branch onde foi chamada o script, vem de argumento no release.yml - branch = sys.argv[2] + ref_name = sys.argv[2] + # url montada # base url = api do sonar # prefix = id da org da disciplina # repository_name = nome do repositorio (unido com prefix separado por _ é o identificador do projeto no sonar) # o join do metrics une as métricas a serem solicitadas como parâmetros # branch = específica o nome da branch para pegar as métricas daquela branch em específicp - url = f'{base_url}{prefix}_{repository_name}&metricKeys={",".join(metrics)}&branch={branch}' + + # Verifica se a referência é uma branch ou uma tag + url = f'{base_url}{prefix}_{repository_name}&metricKeys={",".join(metrics)}&branch={ref_name}' if 'refs/heads/' in sys.argv[2] else f'{base_url}{prefix}_{repository_name}&metricKeys={",".join(metrics)}&tag={ref_name}' + with urllib.request.urlopen(url) as res: data = json.load(res) @@ -44,7 +48,7 @@ def generate_metrics(): underlined_repo_name = repository_name[:16] + \ repository_name[16:].replace('-', "_") - filename = f"{prefix}-{underlined_repo_name}-{date_padrao_hilmer}-{branch}.json" + filename = f"{prefix}-{underlined_repo_name}-{date_padrao_hilmer}-{ref_name}.json" print(filename) with open(filename, "w") as file: json.dump(data, file) From 41055bd59a4d466f16d9add8fb0c0c01854660cc Mon Sep 17 00:00:00 2001 From: ingridSCarvalho Date: Sat, 24 Aug 2024 23:39:25 -0300 Subject: [PATCH 20/22] [fix] - format Co-authored-by: saracampss --- docker-compose.yml | 64 ++--- src/Controllers/supplierFormController.js | 92 +++---- src/Models/supplierFormSchema.js | 70 ++++-- src/Util/utils.js | 282 ++++++++++++---------- src/index.js | 72 +++--- src/routes.js | 4 +- 6 files changed, 320 insertions(+), 264 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 0ead060..be7d566 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,38 +1,38 @@ -version: '3.8' +version: "3.8" services: - mongodb: - image: mongo:7.0 - container_name: financedb - restart: always - environment: - MONGO_INITDB_ROOT_USERNAME: root - MONGO_INITDB_ROOT_PASSWORD: password - ports: - - "27018:27017" - env_file: .env - volumes: - - mongo-data:/data/db - networks: - - backend_network - command: ["mongod", "--quiet", "--logpath", "/dev/null"] + mongodb: + image: mongo:7.0 + container_name: financedb + restart: always + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: password + ports: + - "27018:27017" + env_file: .env + volumes: + - mongo-data:/data/db + networks: + - backend_network + command: ["mongod", "--quiet", "--logpath", "/dev/null"] - express_backend: - build: . - container_name: express_backend_finances - ports: - - "3002:3002" - env_file: .env - environment: - MONGO_URI: ${MONGO_URI} - depends_on: - - mongodb - networks: - - backend_network - volumes: - - ./:/app + express_backend: + build: . + container_name: express_backend_finances + ports: + - "3002:3002" + env_file: .env + environment: + MONGO_URI: ${MONGO_URI} + depends_on: + - mongodb + networks: + - backend_network + volumes: + - ./:/app volumes: - mongo-data: + mongo-data: networks: - backend_network: + backend_network: diff --git a/src/Controllers/supplierFormController.js b/src/Controllers/supplierFormController.js index 11a6154..96ddef6 100644 --- a/src/Controllers/supplierFormController.js +++ b/src/Controllers/supplierFormController.js @@ -2,68 +2,70 @@ const SupplierForm = require("../Models/supplierFormSchema"); const util = require("../Util/utils"); const createSupplierForm = async (req, res) => { - try { - message = util.validator(req.body.supplierData); + try { + message = util.validator(req.body.supplierData); - if (message) { - return res.status(404).send({ erro: message }); - } + if (message) { + return res.status(404).send({ erro: message }); + } - const supplier = new SupplierForm(req.body.supplierData); + const supplier = new SupplierForm(req.body.supplierData); - await supplier.save(); - return res.status(201).send(supplier); - } catch (error) { - return res.status(400).send(error); - } + await supplier.save(); + return res.status(201).send(supplier); + } catch (error) { + return res.status(400).send(error); + } }; const getSupplierForm = async (req, res) => { - try { - const supplier = await SupplierForm.find({}); - return res.status(200).send(supplier); - } catch (error) { - return res.status(400).send(error); - } + try { + const supplier = await SupplierForm.find({}); + return res.status(200).send(supplier); + } catch (error) { + return res.status(400).send(error); + } }; const getSupplierFormById = async (req, res) => { - try { - const supplier = await SupplierForm.findById(req.params.id); - return res.status(200).send(supplier); - } catch (error) { - return res.status(400).send(error); - } + try { + const supplier = await SupplierForm.findById(req.params.id); + return res.status(200).send(supplier); + } catch (error) { + return res.status(400).send(error); + } }; const deleteSupplierFormById = async (req, res) => { - try { - const deletedSupplier = await SupplierForm.findByIdAndDelete(req.params.id); - return res.status(200).send(deletedSupplier); - } catch (error) { - return res.status(400).send(error); - } + try { + const deletedSupplier = await SupplierForm.findByIdAndDelete( + req.params.id + ); + return res.status(200).send(deletedSupplier); + } catch (error) { + return res.status(400).send(error); + } }; const updateSupplierFormById = async (req, res) => { - try { - const updatedSupplier = await SupplierForm.findById(req.params.id); - if (!updatedSupplier) { - return res.status(404).send(); + try { + const updatedSupplier = await SupplierForm.findById(req.params.id); + if (!updatedSupplier) { + return res.status(404).send(); + } + Object.assign(updatedSupplier, req.body.supplierData); + updatedSupplier.updatedAt = new Date(); + await updatedSupplier.save(); + return res.status(200).send(updatedSupplier); + } catch (error) { + return res.status(400).send(error); } - Object.assign(updatedSupplier, req.body.supplierData); - updatedSupplier.updatedAt = new Date(); - await updatedSupplier.save(); - return res.status(200).send(updatedSupplier); - } catch (error) { - return res.status(400).send(error); - } }; module.exports = { - createSupplierForm, - getSupplierForm, - getSupplierFormById, - deleteSupplierFormById, - updateSupplierFormById, + createSupplierForm, + getSupplierForm, + getSupplierFormById, + deleteSupplierFormById, + updateSupplierFormById, }; diff --git a/src/Models/supplierFormSchema.js b/src/Models/supplierFormSchema.js index cbe642e..f08f922 100644 --- a/src/Models/supplierFormSchema.js +++ b/src/Models/supplierFormSchema.js @@ -1,15 +1,14 @@ -const mongoose = require('mongoose'); +const mongoose = require("mongoose"); const supplierFormSchema = new mongoose.Schema({ - nome: { type: String, required: true, - unique: true + unique: true, }, tipoPessoa: { type: String, - enum: ['Jurídica', 'Física', ''] + enum: ["Jurídica", "Física", ""], }, cpfCnpj: { type: String, @@ -17,53 +16,82 @@ const supplierFormSchema = new mongoose.Schema({ }, statusFornecedor: { type: String, - enum: ['Ativo', 'Inativo', ''] + enum: ["Ativo", "Inativo", ""], }, naturezaTransacao: { type: String, - enum: ['Receita', 'Despesa', ''] + enum: ["Receita", "Despesa", ""], }, email: { type: String, unique: true, - sparse:true + sparse: true, }, nomeContato: { - type: String + type: String, }, celular: { type: String, unique: true, - sparse:true + sparse: true, }, telefone: { type: String, unique: true, - sparse:true + sparse: true, }, cep: { type: String, unique: true, - sparse:true + sparse: true, }, cidade: { - type: String + type: String, }, uf_endereco: { type: String, - enum: ['AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO', ''] + enum: [ + "AC", + "AL", + "AP", + "AM", + "BA", + "CE", + "DF", + "ES", + "GO", + "MA", + "MT", + "MS", + "MG", + "PA", + "PB", + "PR", + "PE", + "PI", + "RJ", + "RN", + "RS", + "RO", + "RR", + "SC", + "SP", + "SE", + "TO", + "", + ], }, logradouro: { - type: String + type: String, }, complemento: { - type: String + type: String, }, nomeBanco: { - type: String + type: String, }, agencia: { - type: String + type: String, }, numeroBanco: { type: String, @@ -76,13 +104,13 @@ const supplierFormSchema = new mongoose.Schema({ }, createdAt: { type: Date, - default: Date.now + default: Date.now, }, updatedAt: { type: Date, - default: Date.now + default: Date.now, }, -}) +}); -const supplierForm = mongoose.model('Supplier', supplierFormSchema); +const supplierForm = mongoose.model("Supplier", supplierFormSchema); module.exports = supplierForm; diff --git a/src/Util/utils.js b/src/Util/utils.js index 40e158a..cf8c8bd 100644 --- a/src/Util/utils.js +++ b/src/Util/utils.js @@ -1,135 +1,159 @@ const validator = (dados) => { - console.log("Validator"); - -<<<<<<< HEAD - return null; -======= - if (typeof dados.nome !== "string" || dados.nome === "") { - return "Nome ou Razão social inválidos"; - } - - if (dados.tipoPessoa !== null) { - const tipoPessoaValidas = ["Jurídica", "Física"]; - if (!tipoPessoaValidas.includes(dados.tipoPessoa)) { - return "Tipo de pessoa inválida"; - } - } - - if (dados.cpfCnpj !== null) { - const cpfValido = /^(\d{3}\.\d{3}\.\d{3}-\d{2})$/; - const cnpjValido = /^(\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2})$/; - if ( - (!cpfValido.test(dados.cpfCnpj) && dados.tipoPessoa === "Física") || - (!cnpjValido.test(dados.cpfCnpj) && dados.tipoPessoa === "Jurídica") - ) { - return "CPF ou CNPJ inválido"; - } - } - - if (dados.statusFornecedor !== null) { - const statusFornecedorValido = ["Ativo", "Inativo"]; - if (!statusFornecedorValido.includes(dados.statusFornecedor)) { - return "Status de fornecedor inválido"; - } - } - - if (dados.naturezaTransacao !== null) { - const tipoTransacaoValida = ["Receita", "Despesa"]; - if (!tipoTransacaoValida.includes(dados.naturezaTransacao)) { - return "Tipo de transação inválida"; - } - } - - if (dados.email !== null) { - const emailValido = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailValido.test(dados.email)) { - return "E-mail inválido"; - } - } - - if (dados.nomeContato !== null) { - if (typeof dados.nomeContato !== "string") { - return "Nome de contato inválido"; - } - } - - if (dados.celular !== null) { - const celularValido = /^\(\d{2}\) \d{5}-\d{4}$/; - if (!celularValido.test(dados.celular)) { - return "Número de celular inválido"; - } - } - - if (dados.telefone !== null) { - const telefoneValido = /^\(\d{2}\) \d{4}-\d{4}$/; - if (!telefoneValido.test(dados.telefone)) { - return "Número de telefone inválido"; - } - } - - if (dados.cep !== null) { - const cepValido = /^\d{5}-\d{3}$/; - if (!cepValido.test(dados.cep)) { - return "Cep inválido"; + console.log("Validator"); + + if (typeof dados.nome !== "string" || dados.nome === "") { + return "Nome ou Razão social inválidos"; + } + + if (dados.tipoPessoa !== null) { + const tipoPessoaValidas = ["Jurídica", "Física"]; + if (!tipoPessoaValidas.includes(dados.tipoPessoa)) { + return "Tipo de pessoa inválida"; + } + } + + if (dados.cpfCnpj !== null) { + const cpfValido = /^(\d{3}\.\d{3}\.\d{3}-\d{2})$/; + const cnpjValido = /^(\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2})$/; + if ( + (!cpfValido.test(dados.cpfCnpj) && dados.tipoPessoa === "Física") || + (!cnpjValido.test(dados.cpfCnpj) && dados.tipoPessoa === "Jurídica") + ) { + return "CPF ou CNPJ inválido"; + } + } + + if (dados.statusFornecedor !== null) { + const statusFornecedorValido = ["Ativo", "Inativo"]; + if (!statusFornecedorValido.includes(dados.statusFornecedor)) { + return "Status de fornecedor inválido"; + } + } + + if (dados.naturezaTransacao !== null) { + const tipoTransacaoValida = ["Receita", "Despesa"]; + if (!tipoTransacaoValida.includes(dados.naturezaTransacao)) { + return "Tipo de transação inválida"; + } + } + + if (dados.email !== null) { + const emailValido = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailValido.test(dados.email)) { + return "E-mail inválido"; + } + } + + if (dados.nomeContato !== null) { + if (typeof dados.nomeContato !== "string") { + return "Nome de contato inválido"; + } + } + + if (dados.celular !== null) { + const celularValido = /^\(\d{2}\) \d{5}-\d{4}$/; + if (!celularValido.test(dados.celular)) { + return "Número de celular inválido"; + } + } + + if (dados.telefone !== null) { + const telefoneValido = /^\(\d{2}\) \d{4}-\d{4}$/; + if (!telefoneValido.test(dados.telefone)) { + return "Número de telefone inválido"; + } + } + + if (dados.cep !== null) { + const cepValido = /^\d{5}-\d{3}$/; + if (!cepValido.test(dados.cep)) { + return "Cep inválido"; + } + } + + if (dados.cidade !== null) { + if (typeof dados.cidade !== "string") { + return "Cidade inválida"; + } + } + + if (dados.uf_endereco !== null) { + const ufsValidos = [ + "AC", + "AL", + "AP", + "AM", + "BA", + "CE", + "DF", + "ES", + "GO", + "MA", + "MT", + "MS", + "MG", + "PA", + "PB", + "PR", + "PE", + "PI", + "RJ", + "RN", + "RS", + "RO", + "RR", + "SC", + "SP", + "SE", + "TO", + ]; + if (!ufsValidos.includes(dados.uf_endereco)) { + return "UF inválida"; + } + } + + if (dados.logradouro !== null) { + const logradouro = /^[a-zA-Z0-9\s,.()-]{5,100}$/; + if (!logradouro.test(dados.logradouro)) { + return "Logradouro inválido. Deve conter entre 5 e 100 caracteres."; + } + } + + if (dados.complemento !== null) { + if (typeof dados.complemento !== "string") { + return "Complemento inválido"; + } + } + + if (dados.agencia !== null) { + if (typeof dados.agencia !== "string") { + return "Agência inválida"; + } + } + + if (dados.numeroBanco !== null) { + const numeroValido = /^\d*$/; + if (!numeroValido.test(dados.numeroBanco)) { + return "Número inválido"; + } + } + + if (dados.dv !== null) { + const dvValido = /^\d*$/; + if (!dvValido.test(dados.dv)) { + return "DV inválido"; + } + } + + if (dados.chavePix !== null) { + if (typeof dados.chavePix !== "string") { + return "Chave Pix inválida"; + } } - } - if (dados.cidade !== null) { - if (typeof dados.cidade !== "string") { - return "Cidade inválida"; - } - } - - if (dados.uf_endereco !== null) { - const ufsValidos = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"]; - if (!ufsValidos.includes(dados.uf_endereco)) { - return "UF inválida"; - } - } - - if (dados.logradouro !== null) { - const logradouro = /^[a-zA-Z0-9\s,.()-]{5,100}$/; - if (!logradouro.test(dados.logradouro)) { - return "Logradouro inválido. Deve conter entre 5 e 100 caracteres."; - } - } - - if (dados.complemento !== null) { - if (typeof dados.complemento !== "string") { - return "Complemento inválido"; - } - } - - if (dados.agencia !== null) { - if (typeof dados.agencia !== "string") { - return "Agência inválida"; - } - } - - if (dados.numeroBanco !== null) { - const numeroValido = /^\d*$/; - if (!numeroValido.test(dados.numeroBanco)) { - return "Número inválido"; - } - } - - if (dados.dv !== null) { - const dvValido = /^\d*$/; - if (!dvValido.test(dados.dv)) { - return "DV inválido"; - } - } - - if (dados.chavePix !== null) { - if (typeof dados.chavePix !== "string") { - return "Chave Pix inválida"; - } - } - - return null; ->>>>>>> 4de0ec915ca3d6f6326531dd0e2bc62257db2d8a + return null; }; module.exports = { - validator, -}; \ No newline at end of file + validator, +}; diff --git a/src/index.js b/src/index.js index a887253..edb5aa5 100644 --- a/src/index.js +++ b/src/index.js @@ -1,24 +1,24 @@ -const express = require('express'); -const bodyParser = require('body-parser'); -const mongoose = require('mongoose'); -const cors = require('cors'); -const routes = require('./routes'); +const express = require("express"); +const bodyParser = require("body-parser"); +const mongoose = require("mongoose"); +const cors = require("cors"); +const routes = require("./routes"); const app = express(); const { - NODE_ENV, - MONGO_INITDB_ROOT_USERNAME, - MONGO_INITDB_ROOT_PASSWORD, - MONGO_URI, - DB_HOST, - PORT + NODE_ENV, + MONGO_INITDB_ROOT_USERNAME, + MONGO_INITDB_ROOT_PASSWORD, + MONGO_URI, + DB_HOST, + PORT, } = process.env; const corsOption = { - origin: "*", - methods: 'GET,HEAD,PUT,PATCH,POST,DELETE' -} + origin: "*", + methods: "GET,HEAD,PUT,PATCH,POST,DELETE", +}; // Aplicar o middleware CORS antes das rotas app.use(cors(corsOption)); @@ -29,30 +29,32 @@ app.use(bodyParser.json()); // Conect to MongoB let url; if (NODE_ENV === "development") { - url = MONGO_URI; + url = MONGO_URI; } else { - url = `mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@${DB_HOST}`; + url = `mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@${DB_HOST}`; } -mongoose.connect(url) - .then(() => { - console.log('Conectado ao MongoDB'); - - // Rotas import - app.use(routes); - - // Route test - app.get('/', (req, res) => { - res.send('Hello, world!'); - }); - - app.listen(PORT, () => { - console.log(`Servidor rodando na porta ${PORT}`); - console.log('NODE_ENV:', NODE_ENV); +mongoose + .connect(url) + .then(() => { + console.log("Conectado ao MongoDB"); + + // Rotas import + app.use(routes); + + // Route test + app.get("/", (req, res) => { + res.send("Hello, world!"); + }); + + app.listen(PORT, () => { + console.log(`Servidor rodando na porta ${PORT}`); + console.log("NODE_ENV:", NODE_ENV); + }); + }) + .catch((err) => { + console.error("Erro ao conectar ao MongoDB", err); + process.exit(1); }); - }).catch((err) => { - console.error('Erro ao conectar ao MongoDB', err); - process.exit(1); - }); module.exports = app; diff --git a/src/routes.js b/src/routes.js index 7d7fc6c..898c81b 100644 --- a/src/routes.js +++ b/src/routes.js @@ -1,4 +1,4 @@ -const express = require('express'); +const express = require("express"); const routes = express.Router(); const newController = require("./Controllers/newController"); const bankAccountController = require("./Controllers/bankAccountController"); @@ -45,4 +45,4 @@ routes.patch( routes.post("/finance/create", newController.createNew); routes.get("/finance", newController.getNews); -module.exports = routes; \ No newline at end of file +module.exports = routes; From b80190a06ae00aca688b08ab9757e5c27d855960 Mon Sep 17 00:00:00 2001 From: ingridSCarvalho Date: Sat, 24 Aug 2024 23:47:49 -0300 Subject: [PATCH 21/22] [fix] - update package.json Co-authored-by: saracampss --- package.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 715f90e..2bb86dd 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,12 @@ "generate-password": "^1.7.1", "jsonwebtoken": "^9.0.2", "mongoose": "^8.3.5", - "nodemailer": "^6.9.14" + "nodemailer": "^6.9.14", + "dotenv": "^16.4.5", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.2.1", + "lint-staged": "^15.2.7" + }, "devDependencies": { "@eslint/js": "^9.8.0", From 295e6f7dad8dcf49188d19459054b6ef7125244d Mon Sep 17 00:00:00 2001 From: AlGouvea Date: Mon, 26 Aug 2024 15:55:41 -0300 Subject: [PATCH 22/22] [hotfix] Corrigindo testes e schema --- src/Models/supplierFormSchema.js | 9 ---- src/Util/utils.js | 43 +++++++++---------- src/__tests__/suppllierFormController.test.js | 21 +++++++-- 3 files changed, 39 insertions(+), 34 deletions(-) diff --git a/src/Models/supplierFormSchema.js b/src/Models/supplierFormSchema.js index f08f922..4b39ad7 100644 --- a/src/Models/supplierFormSchema.js +++ b/src/Models/supplierFormSchema.js @@ -12,7 +12,6 @@ const supplierFormSchema = new mongoose.Schema({ }, cpfCnpj: { type: String, - unique: true, }, statusFornecedor: { type: String, @@ -24,26 +23,18 @@ const supplierFormSchema = new mongoose.Schema({ }, email: { type: String, - unique: true, - sparse: true, }, nomeContato: { type: String, }, celular: { type: String, - unique: true, - sparse: true, }, telefone: { type: String, - unique: true, - sparse: true, }, cep: { type: String, - unique: true, - sparse: true, }, cidade: { type: String, diff --git a/src/Util/utils.js b/src/Util/utils.js index cf8c8bd..827335d 100644 --- a/src/Util/utils.js +++ b/src/Util/utils.js @@ -1,18 +1,17 @@ const validator = (dados) => { - console.log("Validator"); - if (typeof dados.nome !== "string" || dados.nome === "") { return "Nome ou Razão social inválidos"; } - if (dados.tipoPessoa !== null) { - const tipoPessoaValidas = ["Jurídica", "Física"]; + if (dados.tipoPessoa) { + console.log("TipoPessoa"); + const tipoPessoaValidas = ["Jurídica", "Física", ""]; if (!tipoPessoaValidas.includes(dados.tipoPessoa)) { return "Tipo de pessoa inválida"; } } - if (dados.cpfCnpj !== null) { + if (dados.cpfCnpj) { const cpfValido = /^(\d{3}\.\d{3}\.\d{3}-\d{2})$/; const cnpjValido = /^(\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2})$/; if ( @@ -23,61 +22,61 @@ const validator = (dados) => { } } - if (dados.statusFornecedor !== null) { - const statusFornecedorValido = ["Ativo", "Inativo"]; + if (dados.statusFornecedor) { + const statusFornecedorValido = ["Ativo", "Inativo", ""]; if (!statusFornecedorValido.includes(dados.statusFornecedor)) { return "Status de fornecedor inválido"; } } - if (dados.naturezaTransacao !== null) { - const tipoTransacaoValida = ["Receita", "Despesa"]; + if (dados.naturezaTransacao) { + const tipoTransacaoValida = ["Receita", "Despesa", ""]; if (!tipoTransacaoValida.includes(dados.naturezaTransacao)) { return "Tipo de transação inválida"; } } - if (dados.email !== null) { + if (dados.email) { const emailValido = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailValido.test(dados.email)) { return "E-mail inválido"; } } - if (dados.nomeContato !== null) { + if (dados.nomeContato) { if (typeof dados.nomeContato !== "string") { return "Nome de contato inválido"; } } - if (dados.celular !== null) { + if (dados.celular) { const celularValido = /^\(\d{2}\) \d{5}-\d{4}$/; if (!celularValido.test(dados.celular)) { return "Número de celular inválido"; } } - if (dados.telefone !== null) { + if (dados.telefone) { const telefoneValido = /^\(\d{2}\) \d{4}-\d{4}$/; if (!telefoneValido.test(dados.telefone)) { return "Número de telefone inválido"; } } - if (dados.cep !== null) { + if (dados.cep) { const cepValido = /^\d{5}-\d{3}$/; if (!cepValido.test(dados.cep)) { return "Cep inválido"; } } - if (dados.cidade !== null) { + if (dados.cidade) { if (typeof dados.cidade !== "string") { return "Cidade inválida"; } } - if (dados.uf_endereco !== null) { + if (dados.uf_endereco) { const ufsValidos = [ "AC", "AL", @@ -112,40 +111,40 @@ const validator = (dados) => { } } - if (dados.logradouro !== null) { + if (dados.logradouro) { const logradouro = /^[a-zA-Z0-9\s,.()-]{5,100}$/; if (!logradouro.test(dados.logradouro)) { return "Logradouro inválido. Deve conter entre 5 e 100 caracteres."; } } - if (dados.complemento !== null) { + if (dados.complemento) { if (typeof dados.complemento !== "string") { return "Complemento inválido"; } } - if (dados.agencia !== null) { + if (dados.agencia) { if (typeof dados.agencia !== "string") { return "Agência inválida"; } } - if (dados.numeroBanco !== null) { + if (dados.numeroBanco) { const numeroValido = /^\d*$/; if (!numeroValido.test(dados.numeroBanco)) { return "Número inválido"; } } - if (dados.dv !== null) { + if (dados.dv) { const dvValido = /^\d*$/; if (!dvValido.test(dados.dv)) { return "DV inválido"; } } - if (dados.chavePix !== null) { + if (dados.chavePix) { if (typeof dados.chavePix !== "string") { return "Chave Pix inválida"; } diff --git a/src/__tests__/suppllierFormController.test.js b/src/__tests__/suppllierFormController.test.js index 0be58c5..d0069f5 100644 --- a/src/__tests__/suppllierFormController.test.js +++ b/src/__tests__/suppllierFormController.test.js @@ -48,9 +48,24 @@ describe("Supplier Form Controller Tests", () => { .send({ supplierData: { nome: "Test Supplier", - email: "supplier@test.com", - celular: "123456789", - logradouro: "123 Supplier St", + tipoPessoa: "", + cpfCnpj: "", + statusFornecedor: "", + naturezaTransacao: "", + email: "", + nomeContato: "", + celular: "", + telefone: "", + cep: "", + cidade: "", + uf_endereco: "", + logradouro: "", + complemento: "", + nomeBanco: "", + agencia: "", + numeroBanco: "", + dv: "", + chavePix: "", }, });