From 30b30d46b17786aed6cee7ca2834a360c336cbe9 Mon Sep 17 00:00:00 2001 From: Milena Linda Date: Wed, 24 Jul 2024 00:12:45 -0300 Subject: [PATCH 1/7] =?UTF-8?q?[fix:20]=20-Cria=C3=A7=C3=A3o=20do=20banco?= =?UTF-8?q?=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 2/7] [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 3/7] =?UTF-8?q?[feat:20]=20-=20Ajuste=20para=20m=C3=A9todo?= =?UTF-8?q?=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 4/7] =?UTF-8?q?[feat:20]=20-=20Ajuste=20para=20m=C3=A9todo?= =?UTF-8?q?=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 5/7] [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 6/7] [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 7/7] [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