From 4a0154c039ca0790713f63f696e8d5300956378f Mon Sep 17 00:00:00 2001 From: Breno Gabriel de Melo Lima Date: Tue, 12 Dec 2023 14:56:22 -0300 Subject: [PATCH 01/62] fix(feature/login): removing the 'unsuccessful login due to incorrect information' scenario --- features/login.feature | 7 ------- 1 file changed, 7 deletions(-) diff --git a/features/login.feature b/features/login.feature index c73b8402..73062f88 100644 --- a/features/login.feature +++ b/features/login.feature @@ -9,13 +9,6 @@ When “Gabriel”preenche os campos disponíveis com seu login “gabriel_lopes And seleciona a opção “Login” Then “Gabriel” visualiza a página inicial da plataforma. -Scenario: login mal sucedido devido a informações incorretas -Given “Gabriel” está na página de login -When “Gabriel”preenche os campos disponíveis com seu login “gabriel_lopes123” e senha “12345678abc” -And seleciona a opção “Login” -Then “Gabriel” visualiza a mensagem “e-mail ou senha incorreto” -And permanece na pagina de login - Scenario: Esquecimento de senha Given “Gabriel” está na página de login And “Gabriel” esqueceu a senha de login From c50c111164817e41a93455cdd90ec8a55df38133 Mon Sep 17 00:00:00 2001 From: Breno Gabriel de Melo Lima Date: Tue, 12 Dec 2023 15:03:43 -0300 Subject: [PATCH 02/62] fix(feature/login): 'unsuccessful login due to wrong password 'scenario --- features/login.feature | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/features/login.feature b/features/login.feature index 73062f88..3c8b8b38 100644 --- a/features/login.feature +++ b/features/login.feature @@ -28,12 +28,14 @@ Then “Gabriel” visualiza a mensagem “Cadastro realizado” And “Gabriel” é direcionado para a “página inicial” da plataforma And "Gabriel" visualiza a página "lista de ofertas" -Scenario: login mal-sucedido devido a senha incorreta -Given "Gabriel" está na página "Fazer login" -And "Gabriel" tem o seu nome “Gabriel” , sobrenome “Lopes” , CPF “000000000-00”, endereço: “Rua alameda sempre verde”, CEP “XXXXXXXX”, data de nascimento “20/06/2001” , email “XXXXXXXXXXXX@gmail.com” e a senha “123456yuytre” armazenados no banco de dados. -When "Gabriel" preenche os campos com seu email "XXXXXXXXXXXX@gmail.com" e senha "12345uyureea" -Then "Gabriel" visualiza a mensagem: "Email e/ou senha incorretos" -And permanece na página "fazer login" +Scenario: login mal sucedido devido a senha incorreta +Given 'Gabriel' está na página 'Fazer login' +And 'Gabriel' está cadastrado na plataforma com nome 'Gabriel', sobrenome 'Silva', CPF '111.222.333-44', endereço 'Rua alameda sempre verde', CEP '12345-678', data de nascimento '17/06/2003', email 'usuario@gmail.com' e senha '12345678a'. +When 'Gabriel' preenche os campos disponíveis com o email 'usuario@gmail.com' e senha '12345658b' +And seleciona a opção 'Submeter' +Then 'Gabriel' visualiza a mensagem 'usuário ou senha incorreto' +And permanece na página 'Fazer login' + Scenario: login mal-sucedido devido a email incorreto Given "Gabriel" está na página "Fazer login" From b2e400651a72687a50ff8160280c02a5eff6c1f2 Mon Sep 17 00:00:00 2001 From: Breno Gabriel de Melo Lima Date: Tue, 12 Dec 2023 15:06:40 -0300 Subject: [PATCH 03/62] fix(feature/login): fixing the 'unsuccessful login due to wrong email'scenario --- features/login.feature | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/features/login.feature b/features/login.feature index 3c8b8b38..3b33421f 100644 --- a/features/login.feature +++ b/features/login.feature @@ -37,12 +37,13 @@ Then 'Gabriel' visualiza a mensagem 'usuário ou senha incorreto' And permanece na página 'Fazer login' -Scenario: login mal-sucedido devido a email incorreto -Given "Gabriel" está na página "Fazer login" -And "Gabriel" tem o seu nome “Gabriel” , sobrenome “Lopes” , CPF “000000000-00”, endereço: “Rua alameda sempre verde”, CEP “XXXXXXXX”, data de nascimento “20/06/2001” , email “teste@gmail.com” e a senha “123456yuytre” armazenados no banco de dados. -When "Gabriel" preenche os campos com seu email "teste_errado@gmail.com" e senha "123456yuytre" -And "Gabriel" seleciona a opção "Continuar" -Then "Gabriel" visualiza a mensagem: "Email e/ou senha incorretos" -And permanece na página "fazer login" +Scenario: login mal sucedido devido a email incorreto +Given 'Gabriel' está na página 'Fazer login' +And 'Gabriel' está cadastrado na plataforma com nome 'Gabriel', sobrenome 'Silva', CPF '111.222.333-44', endereço 'Rua alameda sempre verde', CEP '12345-678', data de nascimento '17/06/2003', email 'usuario@gmail.com' e senha '12345678a'. +When 'Gabriel' preenche os campos disponíveis com o email 'usuario@gmail.com' e senha '12345658b' +And seleciona a opção 'Submeter' +Then 'Gabriel' visualiza a mensagem 'usuário ou senha incorreto' +And permanece na página 'Fazer login' + From 13e46e0215c12e2f33ab60c5dccc6ccf918976ab Mon Sep 17 00:00:00 2001 From: Breno Gabriel de Melo Lima Date: Tue, 12 Dec 2023 15:14:17 -0300 Subject: [PATCH 04/62] fix(feature/login): fixing the problems with parameters and lack of information in 'successful login' scenario --- features/login.feature | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/features/login.feature b/features/login.feature index 3b33421f..0ded7650 100644 --- a/features/login.feature +++ b/features/login.feature @@ -3,11 +3,13 @@ As a usuário da plataforma de e-commerce I want to preencher os campos com email e senha So that eu posso acessar os serviços da plataforma -Scenario: login bem sucedido -Given “Gabriel” está na página de login -When “Gabriel”preenche os campos disponíveis com seu login “gabriel_lopes123” e senha “12345678abc” -And seleciona a opção “Login” -Then “Gabriel” visualiza a página inicial da plataforma. +Cenário: login bem sucedido +Given o usuário 'Gabriel' está na página 'Fazer login' +And 'Gabriel' está cadastrado na plataforma com nome 'Gabriel', sobrenome 'Silva', CPF '111.222.333-44', endereço 'Rua alameda sempre verde', CEP '12345-678', data de nascimento '17/06/2003', email 'usuario@gmail.com' e senha '12345678a'. +When 'Gabriel' preenche os campos disponíveis com o email 'usuario@gmail.com' e senha '12345658b' +And seleciona a opção 'Submeter' +Then “Gabriel” visualiza a página inicial da plataforma. + Scenario: Esquecimento de senha Given “Gabriel” está na página de login From d41678235bfd861f053034b55dd3dc407b62fb1d Mon Sep 17 00:00:00 2001 From: Breno Date: Tue, 6 Feb 2024 22:20:00 -0300 Subject: [PATCH 05/62] feat(features): adding the payment_method.feature --- features/payment_method.feature | 108 ++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 features/payment_method.feature diff --git a/features/payment_method.feature b/features/payment_method.feature new file mode 100644 index 00000000..051ba485 --- /dev/null +++ b/features/payment_method.feature @@ -0,0 +1,108 @@ +Feature: Cadastro e manutenção de métodos de pagamento (inserir, remover, atualizar) +As a usuário cadastrado +I want inserir, remover ou atualizar os métodos de pagamento +So that eu posso realizar o pagamento de minhas compras + +Scenario: Inserção bem-sucedida de boleto como método de pagamento +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Boleto" +And preencher o campo "Nome completo" com "Breno Gabriel de Melo Lima" +And preencher o campo "CPF" com "925.830.910-34" +And o usuário clica em "Confirmar" +Then o método de pagamento será cadastrado no sistema + +Scenario: Inserção bem-sucedida de Pix como método de pagamento +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Pix" +And preencher o campo "Nome completo" com "Breno Gabriel de Melo Lima" +And preencher o campo "CPF" com "925.830.910-34" +And o usuário clica em "Confirmar" +Then o método de pagamento será cadastrado no sistema + +Scenario: Inserção bem-sucedida de cartão como método de pagamento +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Cartão" +And preencher o campo "Nome do cartão" com "Nubank" +And preencher o campo "CPF" com "925.830.910-34" +And preencher o campo "CVV" com "1234" +And preencher o campo "Número do cartão" com "12345678" +And preencher o campo "Validade" com "06/2028" +And o usuário clica em "Confirmar" +Then o método de pagamento será cadastrado no sistema + +Scenario: Inserção mal-sucedida de boleto como método de pagamento +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Boleto" +And preencher o campo "Nome completo" com "Breno Gabriel de Melo Lima" +And preencher o campo "CPF" com "925.830.910" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações inválidas" + +Scenario: Inserção mal-sucedida de Pix como método de pagamento +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Boleto" +And preencher o campo "Nome completo" com "Breno Gabriel de Melo Lima" +And preencher o campo "CPF" com "925.830.910" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações inválidas" + +Scenario: Inserção mal-sucedida de cartão como método de pagamento devido a CPF inválido +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Cartão" +And preencher o campo "Nome do cartão" com "Nubank" +And preencher o campo "CPF" com "925.830.910" +And preencher o campo "CVV" com "1234" +And preencher o campo "Número do cartão" com "12345678" +And preencher o campo "Validade" com "06/2028" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações inválidas" + +Scenario: Inserção mal-sucedida de cartão como método de pagamento devido a CVV inválido +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Cartão" +And preencher o campo "Nome do cartão" com "Nubank" +And preencher o campo "CPF" com "925.830.910-34" +And preencher o campo "CVV" com "123" +And preencher o campo "Número do cartão" com "12345678" +And preencher o campo "Validade" com "06/2028" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações inválidas" + +Scenario: Inserção mal-sucedida de cartão como método de pagamento devido a número de cartão inválido +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Cartão" +And preencher o campo "Nome do cartão" com "Nubank" +And preencher o campo "CPF" com "925.830.910" +And preencher o campo "CVV" com "1234" +And preencher o campo "Número do cartão" com "123456" +And preencher o campo "Validade" com "06/2028" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações inválidas" + +Scenario: Inserção mal-sucedida de cartão como método de pagamento devido a data de validade inválida +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "inserir método de pagamento" +And seleciona o a opção "Cartão" +And preencher o campo "Nome do cartão" com "Nubank" +And preencher o campo "CPF" com "925.830.910" +And preencher o campo "CVV" com "1234" +And preencher o campo "Número do cartão" com "12345678" +And preencher o campo "Validade" com "06/2020" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações inválidas" + +Scenario: Atualização bem-sucedida de informações do cartão +Given o usuário de email "usuário@gmail.com" está na página "Métodos de pagamento" +When usuário clicar na opção "atualizar método de pagamento" +And selecionar a opção "nubank" +And atualizar o campo "Nome completo" com "Maria Alvez da Cunha" +And o usuário clica em "Confirmar" +Then o usuário visualiza a mensagem "Informações atualizadas" From 08d382173d67b3eb80035d87b6e640ceb6068ac1 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 7 Feb 2024 23:14:29 -0300 Subject: [PATCH 06/62] add: adding the paymemt_methods_schemas, and some payment methods routes --- .python-version | 1 + backend/src/api/payment_method.py | 28 +++++++++++++++++++ backend/src/schemas/payment_method_schemas.py | 20 +++++++++++++ .../service/impl/payment_method_service.py | 0 4 files changed, 49 insertions(+) create mode 100644 .python-version create mode 100644 backend/src/api/payment_method.py create mode 100644 backend/src/schemas/payment_method_schemas.py create mode 100644 backend/src/service/impl/payment_method_service.py diff --git a/.python-version b/.python-version new file mode 100644 index 00000000..0833a98f --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.7.4 diff --git a/backend/src/api/payment_method.py b/backend/src/api/payment_method.py new file mode 100644 index 00000000..55d8e719 --- /dev/null +++ b/backend/src/api/payment_method.py @@ -0,0 +1,28 @@ +from fastapi import APIRouter, status, Response +from src.schemas.response import HttpResponseModel +from src.schemas.payment_method_schemas import Pix, Boleto, Cartao + +router = APIRouter() + +@router.post( + "/register_payment_method/pix", + response_model=HttpResponseModel, + status_code=status.HTTP_201_CREATED, + description="Payment_method insertion", + responses={ + status.HTTP_201_CREATED: { + "model": HttpResponseModel, + "description": "payment method inserted", + }, + status.HTTP_401_UNAUTHORIZED: { + "model": HttpResponseModel, + "description": "Fail in payment method insertion", + }, + status.HTTP_400_BAD_REQUEST: { + "model": HttpResponseModel, + "description": "Bad Request", + }, + }, +) +def payment_method_insertion(pix: Pix, response: Response) -> HttpResponseModel: + pass diff --git a/backend/src/schemas/payment_method_schemas.py b/backend/src/schemas/payment_method_schemas.py new file mode 100644 index 00000000..39530152 --- /dev/null +++ b/backend/src/schemas/payment_method_schemas.py @@ -0,0 +1,20 @@ +from pydantic import typing, BaseModel +import datetime + +class Pix(BaseModel): + nome_completo: str + cpf: str + +class Boleto(BaseModel): + nome_completo: str + cpf: str + +class Cartao(BaseModel): + nome_completo: str + nome_cartao: str + numero_cartao: str + cvv: str + validade: datetime.date + + + diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py new file mode 100644 index 00000000..e69de29b From 9dcd2793a744bbf09ba845b4cce91bc74e3476c2 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 10:28:37 -0300 Subject: [PATCH 07/62] feat(database;py): adding a add function in the database.py file --- .idea/.gitignore | 8 ++++++ .idea/Projeto-ESS2.iml | 12 ++++++++ .../inspectionProfiles/profiles_settings.xml | 6 ++++ .idea/misc.xml | 4 +++ .idea/modules.xml | 8 ++++++ .idea/vcs.xml | 6 ++++ .python-version | 1 - "backend/Usu\303\241rios teste.json" | 1 + "backend/Usu\303\241rios.json" | 1 + backend/src/api/payment_method.py | 28 ------------------- backend/src/db/database.py | 25 ++++++++++++++++- backend/src/schemas/payment_method_schemas.py | 20 ------------- .../service/impl/payment_method_service.py | 0 13 files changed, 70 insertions(+), 50 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/Projeto-ESS2.iml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml delete mode 100644 .python-version create mode 100644 "backend/Usu\303\241rios teste.json" create mode 100644 "backend/Usu\303\241rios.json" delete mode 100644 backend/src/api/payment_method.py delete mode 100644 backend/src/schemas/payment_method_schemas.py delete mode 100644 backend/src/service/impl/payment_method_service.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/Projeto-ESS2.iml b/.idea/Projeto-ESS2.iml new file mode 100644 index 00000000..8b8c3954 --- /dev/null +++ b/.idea/Projeto-ESS2.iml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 00000000..105ce2da --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..a971a2c9 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 00000000..3f42b946 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..35eb1ddf --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.python-version b/.python-version deleted file mode 100644 index 0833a98f..00000000 --- a/.python-version +++ /dev/null @@ -1 +0,0 @@ -3.7.4 diff --git "a/backend/Usu\303\241rios teste.json" "b/backend/Usu\303\241rios teste.json" new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ "b/backend/Usu\303\241rios teste.json" @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git "a/backend/Usu\303\241rios.json" "b/backend/Usu\303\241rios.json" new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ "b/backend/Usu\303\241rios.json" @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/backend/src/api/payment_method.py b/backend/src/api/payment_method.py deleted file mode 100644 index 55d8e719..00000000 --- a/backend/src/api/payment_method.py +++ /dev/null @@ -1,28 +0,0 @@ -from fastapi import APIRouter, status, Response -from src.schemas.response import HttpResponseModel -from src.schemas.payment_method_schemas import Pix, Boleto, Cartao - -router = APIRouter() - -@router.post( - "/register_payment_method/pix", - response_model=HttpResponseModel, - status_code=status.HTTP_201_CREATED, - description="Payment_method insertion", - responses={ - status.HTTP_201_CREATED: { - "model": HttpResponseModel, - "description": "payment method inserted", - }, - status.HTTP_401_UNAUTHORIZED: { - "model": HttpResponseModel, - "description": "Fail in payment method insertion", - }, - status.HTTP_400_BAD_REQUEST: { - "model": HttpResponseModel, - "description": "Bad Request", - }, - }, -) -def payment_method_insertion(pix: Pix, response: Response) -> HttpResponseModel: - pass diff --git a/backend/src/db/database.py b/backend/src/db/database.py index b1488324..f4e8c332 100644 --- a/backend/src/db/database.py +++ b/backend/src/db/database.py @@ -208,4 +208,27 @@ def insert_item(self, collection_name: str, item: dict) -> dict: - list: A list of all items in the collection. - """ \ No newline at end of file + """ + + def add(self, collection_name: Collection, item: dict) -> dict: + + #Insert a item in a collection. + + #Args: + #collection_name (Collection) --> name of the collection. + #item (dict) --> the item in form of a dict. + + #Process: + #acessing the collection of the item. + #storing the item in the collection. + + #Outuput: + #A document containing: + #A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled. + #A field insertedId with the _id value of the inserted document. + + collection: Collection = self.db[collection_name] + + result = collection.insert_one(item) + + return result diff --git a/backend/src/schemas/payment_method_schemas.py b/backend/src/schemas/payment_method_schemas.py deleted file mode 100644 index 39530152..00000000 --- a/backend/src/schemas/payment_method_schemas.py +++ /dev/null @@ -1,20 +0,0 @@ -from pydantic import typing, BaseModel -import datetime - -class Pix(BaseModel): - nome_completo: str - cpf: str - -class Boleto(BaseModel): - nome_completo: str - cpf: str - -class Cartao(BaseModel): - nome_completo: str - nome_cartao: str - numero_cartao: str - cvv: str - validade: datetime.date - - - diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py deleted file mode 100644 index e69de29b..00000000 From c88976e78c5317fa04fc64000803ca7c174ce989 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 11:04:12 -0300 Subject: [PATCH 08/62] feat: adding the pyament methods schemas --- backend/src/schemas/payment_schema.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 backend/src/schemas/payment_schema.py diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py new file mode 100644 index 00000000..ecea0abf --- /dev/null +++ b/backend/src/schemas/payment_schema.py @@ -0,0 +1,20 @@ +from pydantic import BaseModel +import datetime + +class Boleto(BaseModel): + type: str + nome_completo: str + cpf: str + +class Pix(BaseModel): + type: str + nome_completo: str + cpf: str + +class Cartao(Boleto): + cvv: str + nome_cartao: str + num_cartao: str + validade: datetime.date + + From ef72c5af00718c3a5a6b52b66e1e876c885de0a8 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 11:06:31 -0300 Subject: [PATCH 09/62] fix: removing the Pix schema and renaming the Boleto schema --- backend/src/schemas/payment_schema.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index ecea0abf..f5cc1781 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -1,17 +1,12 @@ from pydantic import BaseModel import datetime -class Boleto(BaseModel): +class Boleto_pix(BaseModel): type: str nome_completo: str cpf: str -class Pix(BaseModel): - type: str - nome_completo: str - cpf: str - -class Cartao(Boleto): +class Cartao(Boleto_pix): cvv: str nome_cartao: str num_cartao: str From 29092bfe08aeb472a8a6eed36388c1a90997f0f9 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 11:22:38 -0300 Subject: [PATCH 10/62] feat: adding the payment methods service --- backend/src/service/impl/payment_method_service.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 backend/src/service/impl/payment_method_service.py diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py new file mode 100644 index 00000000..94d58160 --- /dev/null +++ b/backend/src/service/impl/payment_method_service.py @@ -0,0 +1,10 @@ +from src.db.__init__ import database as db +from src.schemas.payment_schema import Boleto_pix + + +class payment_service: + + @staticmethod + def inserting_method(boleto: Boleto_pix): + result = db.add("payments", boleto) + return result From 8ad1b55118150dbff5dd858f8767dc39bea2ef75 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 13:06:28 -0300 Subject: [PATCH 11/62] fix: Improving the payment methods schemas --- backend/src/schemas/payment_schema.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index f5cc1781..ba95b637 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -1,12 +1,17 @@ from pydantic import BaseModel import datetime -class Boleto_pix(BaseModel): - type: str +class PaymentBase(BaseModel): nome_completo: str cpf: str -class Cartao(Boleto_pix): +class Pix(PaymentBase): + pass + +class Boleto(PaymentBase): + pass + +class Cartao(PaymentBase): cvv: str nome_cartao: str num_cartao: str From bdb83473ddca44583bf84df5dee0c8ebae9465ab Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 13:57:08 -0300 Subject: [PATCH 12/62] fix: fixing the dict problem in the database --- backend/src/db/database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/db/database.py b/backend/src/db/database.py index f4e8c332..ec78c669 100644 --- a/backend/src/db/database.py +++ b/backend/src/db/database.py @@ -229,6 +229,6 @@ def add(self, collection_name: Collection, item: dict) -> dict: collection: Collection = self.db[collection_name] - result = collection.insert_one(item) + result = collection.insert_one(dict(item)) return result From bf834e733b7e1b5aebcdead84ee5bf2875ea8534 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 14:00:02 -0300 Subject: [PATCH 13/62] feat: adding the inserting method route --- backend/src/api/payment_methods.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 backend/src/api/payment_methods.py diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py new file mode 100644 index 00000000..491ba81c --- /dev/null +++ b/backend/src/api/payment_methods.py @@ -0,0 +1,27 @@ +from fastapi import APIRouter, status, HTTPException +from src.service.impl.payment_method_service import PaymentService +from src.schemas.payment_schema import Boleto +from src.schemas.response import HTTPResponses, HttpResponseModel +from fastapi.responses import JSONResponse + + +router = APIRouter() + +@router.post( + '/inserting', + response_model=HttpResponseModel, + status_code=status.HTTP_200_OK, + description="Create a new payment method", + ) +def insert_payment(boleto: Boleto) -> HttpResponseModel: + response = PaymentService.inserting_method(boleto) + return JSONResponse(content="se loko", status_code=200) + +# @router.get( +# "/payment", +# response_model=HttpResponseModel, +# status_code=status.HTTP_200_OK, +# description="Getting a payment method", +# ) +# def get_payment() -> HttpResponseModel: +# pass \ No newline at end of file From bf0ae2b19b925b7f4593dea59d58afa8a39b6bbc Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 9 Feb 2024 14:01:22 -0300 Subject: [PATCH 14/62] feat: adding the route of the payment method feature --- backend/src/api/router.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/src/api/router.py b/backend/src/api/router.py index 7f5ebe6e..811aa158 100644 --- a/backend/src/api/router.py +++ b/backend/src/api/router.py @@ -1,5 +1,6 @@ from fastapi import APIRouter -from src.api import items +from src.api import items, payment_methods api_router = APIRouter() -api_router.include_router(items.router, prefix="/items", tags=["items"]) \ No newline at end of file +api_router.include_router(items.router, prefix="/items", tags=["items"]) +api_router.include_router(payment_methods.router, prefix="/payment") \ No newline at end of file From 2ecba2cab76ec589d69f7bd567e61cc3ee273fc6 Mon Sep 17 00:00:00 2001 From: Breno Date: Tue, 13 Feb 2024 21:22:04 -0300 Subject: [PATCH 15/62] =?UTF-8?q?feat(payment=5Fmethods.py)=20Adicionando?= =?UTF-8?q?=20uma=20base=20de=20dados=20para=20os=20m=C3=A9todos=20de=20pa?= =?UTF-8?q?gamento?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/db/payment_database.py | 37 ++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 backend/src/db/payment_database.py diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py new file mode 100644 index 00000000..4fe2a195 --- /dev/null +++ b/backend/src/db/payment_database.py @@ -0,0 +1,37 @@ +import json +import datetime +import re + +cpf_pattern = re.compile(r"^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2}$") +cartao_pattern = re.compile(r"^5[1-5][0-9]{14}$") + +database = {} + +def escrever_arquivo(database): + with open("payment_database.json", "w") as f: + json.dump(database, f, default=str, indent=4) + +def ler_arquivo(database): + with open("payment_database.json", "r") as f: + return json.load(f) + +def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date): + #if not cpf_pattern.match(cpf): + #raise ValueError("CPF inválido") + + #if not cartao_pattern.match(numero_cartao): + #raise ValueError("Número de cartão inválido") + + if cpf not in database: + database[cpf] = [] + + cartao = { + "nome_cartao": nome_cartao, + "numero_cartao": numero_cartao, + "cvv": cvv, + "validade": validade.strftime("%Y-%m-%d"), + "cpf": cpf + } + + database[cpf].append(cartao) + escrever_arquivo(database) From d78128eb1c36c5541b35d9936777453b76beddf0 Mon Sep 17 00:00:00 2001 From: Breno Date: Tue, 13 Feb 2024 21:32:02 -0300 Subject: [PATCH 16/62] feat(schemas) Adicionando um schema para o cartao --- backend/src/schemas/payment_schema.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index ba95b637..90c3f760 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -1,20 +1,14 @@ from pydantic import BaseModel import datetime -class PaymentBase(BaseModel): - nome_completo: str - cpf: str +class cartao(BaseModel): + cpf: str + nome_cartao: str + numero_cartao: str + cvv: str + validade: datetime.date -class Pix(PaymentBase): - pass -class Boleto(PaymentBase): - pass -class Cartao(PaymentBase): - cvv: str - nome_cartao: str - num_cartao: str - validade: datetime.date From 9f0fd543228871974e6d63cc80a60d2b0e439192 Mon Sep 17 00:00:00 2001 From: Breno Date: Tue, 13 Feb 2024 21:42:15 -0300 Subject: [PATCH 17/62] fix(service): fixing the inserting_method of the PaymentService class --- .../src/service/impl/payment_method_service.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 94d58160..1b055595 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,10 +1,13 @@ -from src.db.__init__ import database as db -from src.schemas.payment_schema import Boleto_pix +from src.db.payment_database import Adicionar_cartao +from src.schemas.payment_schema import Cartao +from src.schemas.response import HTTPResponses, HttpResponseModel - -class payment_service: +class PaymentService: @staticmethod - def inserting_method(boleto: Boleto_pix): - result = db.add("payments", boleto) - return result + def inserting_method(cartao: Cartao) -> HttpResponseModel: + + consulta = Adicionar_cartao(*cartao.model_dump().values()) + + if consulta: + return HTTPResponses.ITEM_CREATED From 03b3abbb0f99f892577c41188e5fa96ddec7ac48 Mon Sep 17 00:00:00 2001 From: Breno Date: Tue, 13 Feb 2024 23:13:33 -0300 Subject: [PATCH 18/62] fix: commitando alguns pequenos ajustes no codigo --- backend/payment_database.json | 11 +++++++++++ backend/src/api/payment_methods.py | 28 +++++++++++++-------------- backend/src/db/database.py | 2 +- backend/src/db/payment_database.py | 18 ++++++++++++++--- backend/src/schemas/payment_schema.py | 4 ++-- 5 files changed, 43 insertions(+), 20 deletions(-) create mode 100644 backend/payment_database.json diff --git a/backend/payment_database.json b/backend/payment_database.json new file mode 100644 index 00000000..c3b93017 --- /dev/null +++ b/backend/payment_database.json @@ -0,0 +1,11 @@ +{ + "string": [ + { + "nome_cartao": "string", + "numero_cartao": "string", + "cvv": "string", + "validade": "2024-02-14", + "cpf": "string" + } + ] +} \ No newline at end of file diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index 491ba81c..dd948442 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, status, HTTPException from src.service.impl.payment_method_service import PaymentService -from src.schemas.payment_schema import Boleto +from src.schemas.payment_schema import Cartao from src.schemas.response import HTTPResponses, HttpResponseModel from fastapi.responses import JSONResponse @@ -8,20 +8,20 @@ router = APIRouter() @router.post( - '/inserting', + '/inserting/cartao', response_model=HttpResponseModel, - status_code=status.HTTP_200_OK, + status_code=status.HTTP_201_CREATED, description="Create a new payment method", ) -def insert_payment(boleto: Boleto) -> HttpResponseModel: - response = PaymentService.inserting_method(boleto) - return JSONResponse(content="se loko", status_code=200) +def insert_payment(cartao: Cartao) -> HttpResponseModel: + response = PaymentService.inserting_method(cartao) + return JSONResponse(content="Método inserido!", status_code=201) -# @router.get( -# "/payment", -# response_model=HttpResponseModel, -# status_code=status.HTTP_200_OK, -# description="Getting a payment method", -# ) -# def get_payment() -> HttpResponseModel: -# pass \ No newline at end of file +@router.get( + "/payment", + response_model=HttpResponseModel, + status_code=status.HTTP_200_OK, + description="Getting a payment method", +) +def get_payment() -> HttpResponseModel: + pass \ No newline at end of file diff --git a/backend/src/db/database.py b/backend/src/db/database.py index ec78c669..d4945195 100644 --- a/backend/src/db/database.py +++ b/backend/src/db/database.py @@ -22,7 +22,7 @@ def connect(self): logger.setLevel(INFO) - self.db = mongo_connection[env.DB_NAME] + self.db = mongo_connection[str(env.DB_NAME)] print("--------------------") logger.info("MongoDB connected!") diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 4fe2a195..56eead78 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -1,6 +1,16 @@ +from typing import List, Dict +from uuid import uuid4 +from pymongo import MongoClient, errors +from pymongo.collection import Collection, IndexModel +#from src.config.config import env +from logging import INFO, WARNING, getLogger +import datetime +import hmac +import hashlib +import re import json -import datetime -import re + +logger = getLogger('uvicorn') cpf_pattern = re.compile(r"^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2}$") cartao_pattern = re.compile(r"^5[1-5][0-9]{14}$") @@ -15,7 +25,7 @@ def ler_arquivo(database): with open("payment_database.json", "r") as f: return json.load(f) -def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date): +def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: #if not cpf_pattern.match(cpf): #raise ValueError("CPF inválido") @@ -35,3 +45,5 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v database[cpf].append(cartao) escrever_arquivo(database) + + return True diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index 90c3f760..f1d140c3 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -1,11 +1,11 @@ from pydantic import BaseModel import datetime -class cartao(BaseModel): - cpf: str +class Cartao(BaseModel): nome_cartao: str numero_cartao: str cvv: str + cpf: str validade: datetime.date From c6d4f47f436fc0f4ab346294c8f99455d65a3bee Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 10:04:41 -0300 Subject: [PATCH 19/62] feat(schemas): adding the Boleto and Pix schemas --- backend/src/schemas/payment_schema.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index f1d140c3..2df9c0dc 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -8,6 +8,12 @@ class Cartao(BaseModel): cpf: str validade: datetime.date +class Pix(BaseModel): + nome_completo: str + cpf: str + +class Boleto(Pix): + pass From 4d638d74ba11ec75a6b2e57eeb723c43e7498c80 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 10:41:17 -0300 Subject: [PATCH 20/62] feat(router): adding a new endpoint for inserting a new payment method --- backend/src/schemas/payment_response.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 backend/src/schemas/payment_response.py diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py new file mode 100644 index 00000000..04a1659c --- /dev/null +++ b/backend/src/schemas/payment_response.py @@ -0,0 +1,7 @@ +from typing import Optional +from pydantic import BaseModel +from .response import HttpResponseModel + +class HTTPPaymentResponse: + + pass \ No newline at end of file From 1286fd04b787160d861486da0d18cba45793a4bd Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 10:43:23 -0300 Subject: [PATCH 21/62] feat: adding a new endpoint --- backend/src/api/payment_methods.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index dd948442..0fbdaa43 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, status, HTTPException from src.service.impl.payment_method_service import PaymentService -from src.schemas.payment_schema import Cartao +from src.schemas.payment_schema import Cartao, Boleto, Pix from src.schemas.response import HTTPResponses, HttpResponseModel from fastapi.responses import JSONResponse @@ -17,11 +17,9 @@ def insert_payment(cartao: Cartao) -> HttpResponseModel: response = PaymentService.inserting_method(cartao) return JSONResponse(content="Método inserido!", status_code=201) -@router.get( - "/payment", - response_model=HttpResponseModel, - status_code=status.HTTP_200_OK, - description="Getting a payment method", +@router.post( + "/inserting/{method_name}", + summary="Inserting a new payment method" ) -def get_payment() -> HttpResponseModel: - pass \ No newline at end of file +def insert_payment_method(method_name: str, cartao: Cartao, pix: Pix, boleto: Boleto) -> HttpResponseModel: + pass \ No newline at end of file From 11963a1c7820c39ac7f9110895180fbedd53b898 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 12:13:43 -0300 Subject: [PATCH 22/62] feat: adding a response function to the payment method feature --- backend/src/schemas/payment_response.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 04a1659c..2908ddf0 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -4,4 +4,9 @@ class HTTPPaymentResponse: - pass \ No newline at end of file + @staticmethod + def INSERTION_SUCESSFULLY() -> HttpResponseModel: + return HttpResponseModel ( + message="Payment method has been inserted sucessfully", + status_code=201 + ) \ No newline at end of file From f04e5d4b446f64089cb561faeeec47b0f82532ac Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 13:24:12 -0300 Subject: [PATCH 23/62] fix: some adjusts in /inserting/cartao endpoint --- backend/src/api/payment_methods.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index 0fbdaa43..280311ea 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -11,11 +11,11 @@ '/inserting/cartao', response_model=HttpResponseModel, status_code=status.HTTP_201_CREATED, - description="Create a new payment method", + summary="Create a new payment method", ) def insert_payment(cartao: Cartao) -> HttpResponseModel: response = PaymentService.inserting_method(cartao) - return JSONResponse(content="Método inserido!", status_code=201) + return response @router.post( "/inserting/{method_name}", From 9c61adef3b2477fbce5df12a6e6d31aa24738794 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 13:33:41 -0300 Subject: [PATCH 24/62] fix: adding a () in the HttpPaymentResponse.INSERTION_SUCESSFULLY --- backend/src/service/impl/payment_method_service.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 1b055595..a86cceb0 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,6 +1,7 @@ from src.db.payment_database import Adicionar_cartao from src.schemas.payment_schema import Cartao from src.schemas.response import HTTPResponses, HttpResponseModel +from src.schemas.payment_response import HTTPPaymentResponse class PaymentService: @@ -10,4 +11,4 @@ def inserting_method(cartao: Cartao) -> HttpResponseModel: consulta = Adicionar_cartao(*cartao.model_dump().values()) if consulta: - return HTTPResponses.ITEM_CREATED + return HTTPPaymentResponse.INSERTION_SUCESSFULLY() From 1be38c3e58d6d30146dd4dd8cf0799ee9c9d18f0 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 14:28:52 -0300 Subject: [PATCH 25/62] feat: adding the validity and CPF validation --- backend/src/db/payment_database.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 56eead78..60b1f7ce 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -26,11 +26,22 @@ def ler_arquivo(database): return json.load(f) def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: - #if not cpf_pattern.match(cpf): - #raise ValueError("CPF inválido") - #if not cartao_pattern.match(numero_cartao): - #raise ValueError("Número de cartão inválido") + problemas = [] + + if not cpf_pattern.match(cpf): + problemas.append("CPF") + + if not validade >= datetime.date.today(): + problemas.append("VALIDADE") + + # if not cartao_pattern.match(numero_cartao): + # problemas.append("CARD_NUMBER") + + print(len(problemas)) + + if len(problemas) > 0: + return (False, problemas) if cpf not in database: database[cpf] = [] @@ -46,4 +57,4 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v database[cpf].append(cartao) escrever_arquivo(database) - return True + return (True, problemas) From 7ec86e07452e673afef3dd48c5659bdc4e92c1b9 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 14:31:19 -0300 Subject: [PATCH 26/62] feat: adding the HTTPPaymentResponse.INSERTION_SUCESSFULLY fot validation of data --- backend/src/service/impl/payment_method_service.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index a86cceb0..261b821c 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -8,7 +8,13 @@ class PaymentService: @staticmethod def inserting_method(cartao: Cartao) -> HttpResponseModel: - consulta = Adicionar_cartao(*cartao.model_dump().values()) + sucesso, problemas = Adicionar_cartao(*cartao.model_dump().values()) - if consulta: + if sucesso: return HTTPPaymentResponse.INSERTION_SUCESSFULLY() + elif "CPF" in problemas or "VALIDADE" in problemas or "CARD_NUMBER" in problemas: + return HTTPPaymentResponse.BAD_REQUEST(problemas) + # elif "VALIDADE" in problemas: + # return HTTPPaymentResponse.EXPIRED_DATA() + # elif "CARD_NUMBER" in problemas: + # return HTTPPaymentResponse.INVALID_NUMBER() From 95eaaa9c83daede9ffe2376a4c6835d04c27d384 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 14:32:42 -0300 Subject: [PATCH 27/62] feat: adding the BAD_REQUEST method --- backend/src/schemas/payment_response.py | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 2908ddf0..5587d270 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -9,4 +9,34 @@ def INSERTION_SUCESSFULLY() -> HttpResponseModel: return HttpResponseModel ( message="Payment method has been inserted sucessfully", status_code=201 + ) + + # @staticmethod + # def INVALID_CPF() -> HttpResponseModel: + # return HttpResponseModel ( + # message="Invalid CPF", + # status_code=400 + # ) + + # @staticmethod + # def EXPIRED_DATA() -> HttpResponseModel: + # return HttpResponseModel ( + # message="The card is expired", + # status_code=400 + # ) + + # @staticmethod + # def INVALID_NUMBER() -> HttpResponseModel: + # return HttpResponseModel ( + # message="The card number is invalid", + # status_code=400 + # ) + + @staticmethod + def BAD_REQUEST(problemas) -> HttpResponseModel: + + return HttpResponseModel ( + message="Os campos a seguir estão preenchidos incorretamente", + status_code=400, + data= problemas ) \ No newline at end of file From 8229a83c506468314d487634f436a5a08757949b Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:34:20 -0300 Subject: [PATCH 28/62] fix: adding a tag to payment methods --- backend/src/api/router.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/api/router.py b/backend/src/api/router.py index 811aa158..01882d62 100644 --- a/backend/src/api/router.py +++ b/backend/src/api/router.py @@ -3,4 +3,4 @@ api_router = APIRouter() api_router.include_router(items.router, prefix="/items", tags=["items"]) -api_router.include_router(payment_methods.router, prefix="/payment") \ No newline at end of file +api_router.include_router(payment_methods.router, prefix="/backend/src/api/payment", tags=["Payment"]) \ No newline at end of file From 1ac7aefa06f55491d82f666b5540edfc561414b8 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:35:33 -0300 Subject: [PATCH 29/62] feat: adding the Adicionar_boleto and Adicionar_pix methods --- backend/src/db/payment_database.py | 31 +++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 60b1f7ce..efe7ee73 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -36,9 +36,7 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v problemas.append("VALIDADE") # if not cartao_pattern.match(numero_cartao): - # problemas.append("CARD_NUMBER") - - print(len(problemas)) + # problemas.append("CARD_NUMBER")cx if len(problemas) > 0: return (False, problemas) @@ -58,3 +56,30 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v escrever_arquivo(database) return (True, problemas) + +def Adicionar_pix(nome_completo: str, cpf: str): + if cpf not in database: + database[cpf] = [] + + pix = { + "tipo": "pix", + "nome_completo": nome_completo, + "cpf": cpf + } + + database[cpf].append(pix) + escrever_arquivo(database) + +def Adicionar_boleto(nome_completo: str, cpf: str): + if cpf not in database: + database[cpf] = [] + + pix = { + "tipo": "boleto", + "nome_completo": nome_completo, + "cpf": cpf + } + + database[cpf].append(pix) + escrever_arquivo(database) + From 2458ab9b32652b329930109258e71c168d95b8f4 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:36:54 -0300 Subject: [PATCH 30/62] feat: adding the insertion_boleto and insertion_pix methods --- .../service/impl/payment_method_service.py | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 261b821c..079b7313 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,12 +1,12 @@ -from src.db.payment_database import Adicionar_cartao -from src.schemas.payment_schema import Cartao +from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto +from src.schemas.payment_schema import Cartao, Pix, Boleto from src.schemas.response import HTTPResponses, HttpResponseModel from src.schemas.payment_response import HTTPPaymentResponse class PaymentService: @staticmethod - def inserting_method(cartao: Cartao) -> HttpResponseModel: + def inserting_cartao(cartao: Cartao) -> HttpResponseModel: sucesso, problemas = Adicionar_cartao(*cartao.model_dump().values()) @@ -18,3 +18,17 @@ def inserting_method(cartao: Cartao) -> HttpResponseModel: # return HTTPPaymentResponse.EXPIRED_DATA() # elif "CARD_NUMBER" in problemas: # return HTTPPaymentResponse.INVALID_NUMBER() + + @staticmethod + def insertion_pix(pix: Pix) -> HttpResponseModel: + + Adicionar_pix(*pix.model_dump().values()) + + return HTTPPaymentResponse.PIX_INSERTED_SUCESSFULLY() + + @staticmethod + def insertion_boleto(boleto: Boleto) -> HttpResponseModel: + + Adicionar_boleto(*boleto.model_dump().values()) + + return HTTPPaymentResponse.BOLETO_INSERTED_SUCESSFULLY() From 737632bc2da33cbda4d08a739375d272dc3debed Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:38:48 -0300 Subject: [PATCH 31/62] feat: adding the PIX_INSERTED_SUCESSFULLY and BOLETO_INSERTED_SUCESSFULLY requests --- backend/src/schemas/payment_response.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 5587d270..2822d225 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -39,4 +39,20 @@ def BAD_REQUEST(problemas) -> HttpResponseModel: message="Os campos a seguir estão preenchidos incorretamente", status_code=400, data= problemas - ) \ No newline at end of file + ) + + @staticmethod + def PIX_INSERTED_SUCESSFULLY() -> HttpResponseModel: + + return HttpResponseModel ( + message="pix inserido com sucesso", + status_code=201 + ) + + @staticmethod + def BOLETO_INSERTED_SUCESSFULLY() -> HttpResponseModel: + + return HttpResponseModel ( + message="boleto inserido com sucesso", + status_code=201 + ) \ No newline at end of file From 369a5d393ffd81bb9889cfe566754186f58c1176 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:39:35 -0300 Subject: [PATCH 32/62] feat: adding the Boleto and Pix schemas --- backend/src/schemas/payment_schema.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index 2df9c0dc..c1a9a708 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -12,8 +12,9 @@ class Pix(BaseModel): nome_completo: str cpf: str -class Boleto(Pix): - pass +class Boleto(BaseModel): + nome_completo: str + cpf: str From a5876ff5bce48e31979309e9ff4672078a84d6f6 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:40:42 -0300 Subject: [PATCH 33/62] feat: adding the '/inserting/pix' and '/inserting/boleto' endpoints --- backend/src/api/payment_methods.py | 40 ++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index 280311ea..a36ae446 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -10,16 +10,42 @@ @router.post( '/inserting/cartao', response_model=HttpResponseModel, - status_code=status.HTTP_201_CREATED, summary="Create a new payment method", ) def insert_payment(cartao: Cartao) -> HttpResponseModel: - response = PaymentService.inserting_method(cartao) + response = PaymentService.inserting_cartao(cartao) return response @router.post( - "/inserting/{method_name}", - summary="Inserting a new payment method" -) -def insert_payment_method(method_name: str, cartao: Cartao, pix: Pix, boleto: Boleto) -> HttpResponseModel: - pass \ No newline at end of file + '/inserting/pix', + response_model=HttpResponseModel, + summary="Create a new payment method", + ) +def insert_payment(pix: Pix) -> HttpResponseModel: + response = PaymentService.insertion_pix(pix) + return response + +@router.post( + '/inserting/boleto', + response_model=HttpResponseModel, + summary="Create a new payment method", + ) +def insert_payment(boleto: Boleto) -> HttpResponseModel: + response = PaymentService.insertion_boleto(boleto) + return response + +# @router.post( +# "/inserting/{method_name}", +# response_model=HttpResponseModel, +# summary="Create a new payment method" +# ) +# def insert_payment_method(method_name: str, cartao: Cartao, pix: Pix, boleto: Boleto) -> HttpResponseModel: +# if method_name == "boleto": +# response = PaymentService.inserting_cartao(boleto) +# return response +# elif method_name == "pix": +# response = PaymentService.insertion_pix(pix) +# return response +# elif method_name == "cartao": +# response = PaymentService.inserting_cartao(cartao) +# return response \ No newline at end of file From 3217788ff3cae7279820db398ffdb52e02d9ab68 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 15:46:41 -0300 Subject: [PATCH 34/62] fix: switching the summary for a description --- backend/src/api/payment_methods.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index a36ae446..99b239fa 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -10,7 +10,7 @@ @router.post( '/inserting/cartao', response_model=HttpResponseModel, - summary="Create a new payment method", + description="Insert a new card", ) def insert_payment(cartao: Cartao) -> HttpResponseModel: response = PaymentService.inserting_cartao(cartao) @@ -19,7 +19,7 @@ def insert_payment(cartao: Cartao) -> HttpResponseModel: @router.post( '/inserting/pix', response_model=HttpResponseModel, - summary="Create a new payment method", + description="Insert a new pix acount", ) def insert_payment(pix: Pix) -> HttpResponseModel: response = PaymentService.insertion_pix(pix) @@ -28,7 +28,7 @@ def insert_payment(pix: Pix) -> HttpResponseModel: @router.post( '/inserting/boleto', response_model=HttpResponseModel, - summary="Create a new payment method", + description="Insert a new boleto acount", ) def insert_payment(boleto: Boleto) -> HttpResponseModel: response = PaymentService.insertion_boleto(boleto) From 3a0514fea758f9de0fc37b7da8c478ca6e953f47 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 18:31:36 -0300 Subject: [PATCH 35/62] feat: changing the user identifier from CPF to username --- backend/src/schemas/payment_schema.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index c1a9a708..9ab9ec1d 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -2,6 +2,7 @@ import datetime class Cartao(BaseModel): + user_name: str nome_cartao: str numero_cartao: str cvv: str @@ -9,10 +10,12 @@ class Cartao(BaseModel): validade: datetime.date class Pix(BaseModel): + user_name: str nome_completo: str cpf: str class Boleto(BaseModel): + user_name: str nome_completo: str cpf: str From 623cbd849d97ca07c69375ad75690fd73b14ac30 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 18:34:55 -0300 Subject: [PATCH 36/62] feat: Changing the CPF for username in the insertion of information im the database --- backend/src/db/payment_database.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index efe7ee73..21763de9 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -25,7 +25,7 @@ def ler_arquivo(database): with open("payment_database.json", "r") as f: return json.load(f) -def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: +def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: problemas = [] @@ -41,8 +41,8 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v if len(problemas) > 0: return (False, problemas) - if cpf not in database: - database[cpf] = [] + if user_name not in database: + database[user_name] = [] cartao = { "nome_cartao": nome_cartao, @@ -52,13 +52,14 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v "cpf": cpf } - database[cpf].append(cartao) + database[user_name].append(cartao) escrever_arquivo(database) return (True, problemas) -def Adicionar_pix(nome_completo: str, cpf: str): - if cpf not in database: +def Adicionar_pix(user_name: str, nome_completo: str, cpf: str): + + if user_name not in database: database[cpf] = [] pix = { @@ -67,11 +68,12 @@ def Adicionar_pix(nome_completo: str, cpf: str): "cpf": cpf } - database[cpf].append(pix) + database[user_name].append(pix) escrever_arquivo(database) -def Adicionar_boleto(nome_completo: str, cpf: str): - if cpf not in database: +def Adicionar_boleto(user_name:str, nome_completo: str, cpf: str): + + if user_name not in database: database[cpf] = [] pix = { @@ -80,6 +82,6 @@ def Adicionar_boleto(nome_completo: str, cpf: str): "cpf": cpf } - database[cpf].append(pix) + database[user_name].append(pix) escrever_arquivo(database) From e4d00032bd460ba6d959c0c08e1e7ab9bb329908 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:01:14 -0300 Subject: [PATCH 37/62] =?UTF-8?q?feat:=20adicionando=20o=20m=C3=A9todo=20'?= =?UTF-8?q?obter=5Flista=5Fde=5Fmetodos=5Fpagamento'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/db/payment_database.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 21763de9..cce3cc1d 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -45,6 +45,7 @@ def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: database[user_name] = [] cartao = { + "tipo": "cartao", "nome_cartao": nome_cartao, "numero_cartao": numero_cartao, "cvv": cvv, @@ -85,3 +86,14 @@ def Adicionar_boleto(user_name:str, nome_completo: str, cpf: str): database[user_name].append(pix) escrever_arquivo(database) +def obter_lista_de_metodos_pagamento(user_name: str): + + dados = ler_arquivo(database) + + metodos_usuario = dados[user_name.strip()] + + return metodos_usuario + + + + From 846bc1201ad2c35951c536e3999b8250dac27438 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:03:01 -0300 Subject: [PATCH 38/62] feat: adding the method 'get_payment_methods' --- backend/src/service/impl/payment_method_service.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 079b7313..f9528ba2 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,4 +1,4 @@ -from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto +from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto, obter_lista_de_metodos_pagamento from src.schemas.payment_schema import Cartao, Pix, Boleto from src.schemas.response import HTTPResponses, HttpResponseModel from src.schemas.payment_response import HTTPPaymentResponse @@ -32,3 +32,7 @@ def insertion_boleto(boleto: Boleto) -> HttpResponseModel: Adicionar_boleto(*boleto.model_dump().values()) return HTTPPaymentResponse.BOLETO_INSERTED_SUCESSFULLY() + + def get_payment_methods(user_name: str): + + return obter_lista_de_metodos_pagamento(user_name) From 7431e0d2313cddfed9b1fa52914021ccca5e45ee Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:04:13 -0300 Subject: [PATCH 39/62] feat: adding a get request method --- backend/src/api/payment_methods.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index 99b239fa..dc2e0420 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -34,6 +34,16 @@ def insert_payment(boleto: Boleto) -> HttpResponseModel: response = PaymentService.insertion_boleto(boleto) return response +@router.get( + "/get/payment_methods", + description="Get the payments methods of a especific user" +) +def get_payment_methods(username:str): + + request = PaymentService.get_payment_methods(username) + + return request + # @router.post( # "/inserting/{method_name}", # response_model=HttpResponseModel, From 797d5b8196de54e7b3cdda3a65dffdbc6dea3c9f Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:28:33 -0300 Subject: [PATCH 40/62] feat: adding a key existence verifier to the 'obter_lista_de_pagamentos_metodo' function --- backend/src/db/payment_database.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index cce3cc1d..20a38d4e 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -61,7 +61,7 @@ def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: def Adicionar_pix(user_name: str, nome_completo: str, cpf: str): if user_name not in database: - database[cpf] = [] + database[user_name] = [] pix = { "tipo": "pix", @@ -90,8 +90,11 @@ def obter_lista_de_metodos_pagamento(user_name: str): dados = ler_arquivo(database) - metodos_usuario = dados[user_name.strip()] - + if user_name.strip() in dados: + metodos_usuario = dados[user_name.strip()] + else: + metodos_usuario = None + return metodos_usuario From d6cd28d6515fd4063f54254ecbe68ba9e96e86f2 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:30:00 -0300 Subject: [PATCH 41/62] feat: adding the 'ger_payment_methods' function --- backend/src/service/impl/payment_method_service.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index f9528ba2..39f3bdb5 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -35,4 +35,9 @@ def insertion_boleto(boleto: Boleto) -> HttpResponseModel: def get_payment_methods(user_name: str): - return obter_lista_de_metodos_pagamento(user_name) + resultado = obter_lista_de_metodos_pagamento(user_name) + + if resultado is None: + return HTTPPaymentResponse.INEXISTENT_USER() + else: + return resultado \ No newline at end of file From 0e62ce72e82c79368e3f2cf97181fbfc4374fa11 Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:32:31 -0300 Subject: [PATCH 42/62] feat: adding the 'INEXISTENT_USER' response --- backend/src/schemas/payment_response.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 2822d225..cce3a789 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -55,4 +55,13 @@ def BOLETO_INSERTED_SUCESSFULLY() -> HttpResponseModel: return HttpResponseModel ( message="boleto inserido com sucesso", status_code=201 - ) \ No newline at end of file + ) + + @staticmethod + def INEXISTENT_USER() -> HttpResponseModel: + + return HttpResponseModel ( + message="O usuário não está registrado na base de dados", + status_code=400 + ) + \ No newline at end of file From 6f85562181181ce6c7c117ef939a96a5efa297dc Mon Sep 17 00:00:00 2001 From: Breno Date: Wed, 14 Feb 2024 19:40:23 -0300 Subject: [PATCH 43/62] fix: changing the user_name for CPF --- backend/payment_database.json | 18 ++++++++++----- backend/src/db/feature_payment_method | 0 backend/src/db/payment_database.py | 22 +++++++++---------- backend/src/schemas/payment_schema.py | 6 ++--- .../service/impl/payment_method_service.py | 4 ++-- 5 files changed, 28 insertions(+), 22 deletions(-) create mode 100644 backend/src/db/feature_payment_method diff --git a/backend/payment_database.json b/backend/payment_database.json index c3b93017..66f7cfae 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,11 +1,17 @@ { - "string": [ + "bgml": [ { - "nome_cartao": "string", - "numero_cartao": "string", - "cvv": "string", - "validade": "2024-02-14", - "cpf": "string" + "tipo": "pix", + "nome_completo": "Breno Gabriel de Melo Lima", + "cpf": "222.2222.222-22" + }, + { + "tipo": "cartao", + "nome_cartao": "nubank", + "numero_cartao": "3343 5545 3542 5456", + "cvv": "433", + "validade": "2028-02-14", + "cpf": "777.777.777-77" } ] } \ No newline at end of file diff --git a/backend/src/db/feature_payment_method b/backend/src/db/feature_payment_method new file mode 100644 index 00000000..e69de29b diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 20a38d4e..4404a9dc 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -41,8 +41,8 @@ def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: if len(problemas) > 0: return (False, problemas) - if user_name not in database: - database[user_name] = [] + if cpf not in database: + database[cpf] = [] cartao = { "tipo": "cartao", @@ -53,15 +53,15 @@ def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: "cpf": cpf } - database[user_name].append(cartao) + database[cpf].append(cartao) escrever_arquivo(database) return (True, problemas) def Adicionar_pix(user_name: str, nome_completo: str, cpf: str): - if user_name not in database: - database[user_name] = [] + if cpf not in database: + database[cpf] = [] pix = { "tipo": "pix", @@ -69,12 +69,12 @@ def Adicionar_pix(user_name: str, nome_completo: str, cpf: str): "cpf": cpf } - database[user_name].append(pix) + database[cpf].append(pix) escrever_arquivo(database) def Adicionar_boleto(user_name:str, nome_completo: str, cpf: str): - if user_name not in database: + if cpf not in database: database[cpf] = [] pix = { @@ -83,15 +83,15 @@ def Adicionar_boleto(user_name:str, nome_completo: str, cpf: str): "cpf": cpf } - database[user_name].append(pix) + database[cpf].append(pix) escrever_arquivo(database) -def obter_lista_de_metodos_pagamento(user_name: str): +def obter_lista_de_metodos_pagamento(cpf: str): dados = ler_arquivo(database) - if user_name.strip() in dados: - metodos_usuario = dados[user_name.strip()] + if cpf in dados: + metodos_usuario = dados[cpf] else: metodos_usuario = None diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index 9ab9ec1d..752e85f6 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -2,7 +2,7 @@ import datetime class Cartao(BaseModel): - user_name: str + nome_cartao: str numero_cartao: str cvv: str @@ -10,12 +10,12 @@ class Cartao(BaseModel): validade: datetime.date class Pix(BaseModel): - user_name: str + nome_completo: str cpf: str class Boleto(BaseModel): - user_name: str + nome_completo: str cpf: str diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 39f3bdb5..b283d1f3 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -33,9 +33,9 @@ def insertion_boleto(boleto: Boleto) -> HttpResponseModel: return HTTPPaymentResponse.BOLETO_INSERTED_SUCESSFULLY() - def get_payment_methods(user_name: str): + def get_payment_methods(cpf: str): - resultado = obter_lista_de_metodos_pagamento(user_name) + resultado = obter_lista_de_metodos_pagamento(cpf) if resultado is None: return HTTPPaymentResponse.INEXISTENT_USER() From 3e8cf7eba8153d92f768d9f92c721d14baabd7ca Mon Sep 17 00:00:00 2001 From: Breno Date: Thu, 15 Feb 2024 02:30:16 -0300 Subject: [PATCH 44/62] feat: adding the update payment --- backend/payment_database.json | 15 ++---- backend/src/api/payment_methods.py | 41 +++++++++++++- backend/src/db/feature_payment_method | 0 backend/src/db/payment_database.py | 53 +++++++++++++++++-- backend/src/schemas/payment_response.py | 16 ++++++ backend/src/schemas/payment_schema.py | 10 ++++ .../service/impl/payment_method_service.py | 44 +++++++++++++-- 7 files changed, 161 insertions(+), 18 deletions(-) delete mode 100644 backend/src/db/feature_payment_method diff --git a/backend/payment_database.json b/backend/payment_database.json index 66f7cfae..32573ce9 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,17 +1,10 @@ { - "bgml": [ + "111.111.111-11": [ { + "id": 290598277920648421, "tipo": "pix", - "nome_completo": "Breno Gabriel de Melo Lima", - "cpf": "222.2222.222-22" - }, - { - "tipo": "cartao", - "nome_cartao": "nubank", - "numero_cartao": "3343 5545 3542 5456", - "cvv": "433", - "validade": "2028-02-14", - "cpf": "777.777.777-77" + "nome_completo": "ZOro", + "cpf": "111.111.111-11" } ] } \ No newline at end of file diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index dc2e0420..bf26eb22 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, status, HTTPException from src.service.impl.payment_method_service import PaymentService -from src.schemas.payment_schema import Cartao, Boleto, Pix +from src.schemas.payment_schema import Cartao, Boleto, Pix, CartaoUpdate, PixUpdate, BoletoUpdate from src.schemas.response import HTTPResponses, HttpResponseModel from fastapi.responses import JSONResponse @@ -10,6 +10,7 @@ @router.post( '/inserting/cartao', response_model=HttpResponseModel, + status_code=201, description="Insert a new card", ) def insert_payment(cartao: Cartao) -> HttpResponseModel: @@ -19,6 +20,7 @@ def insert_payment(cartao: Cartao) -> HttpResponseModel: @router.post( '/inserting/pix', response_model=HttpResponseModel, + status_code=201, description="Insert a new pix acount", ) def insert_payment(pix: Pix) -> HttpResponseModel: @@ -28,6 +30,7 @@ def insert_payment(pix: Pix) -> HttpResponseModel: @router.post( '/inserting/boleto', response_model=HttpResponseModel, + status_code=201, description="Insert a new boleto acount", ) def insert_payment(boleto: Boleto) -> HttpResponseModel: @@ -44,6 +47,42 @@ def get_payment_methods(username:str): return request +@router.put( + "update/cartao/{card_id}", + response_model=HttpResponseModel, + status_code=200, + description="Update the card payment method" +) +def update_payment(card_id: int, cartao: CartaoUpdate): + + response = PaymentService.update_cartao(card_id, cartao) + + return response + +@router.put( + "/update/pix/{card_id}", + response_model=HttpResponseModel, + status_code=200, + description="Update the pix payment method" +) +def update_payment(card_id: int, pix: PixUpdate): + + response = PaymentService.update_pix(card_id, pix) + + return response + +@router.put( + "/update/boleto/{card_id}", + response_model=HttpResponseModel, + status_code=200, + description="Update the boleto payment method" +) +def update_payment(card_id: int, boleto: BoletoUpdate): + + response = PaymentService.update_boleto(card_id, boleto) + + return response + # @router.post( # "/inserting/{method_name}", # response_model=HttpResponseModel, diff --git a/backend/src/db/feature_payment_method b/backend/src/db/feature_payment_method deleted file mode 100644 index e69de29b..00000000 diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 4404a9dc..e1004125 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -25,7 +25,7 @@ def ler_arquivo(database): with open("payment_database.json", "r") as f: return json.load(f) -def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: +def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: problemas = [] @@ -45,6 +45,7 @@ def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: database[cpf] = [] cartao = { + "id" : abs(hash((datetime.datetime.now(), cpf))), "tipo": "cartao", "nome_cartao": nome_cartao, "numero_cartao": numero_cartao, @@ -58,12 +59,13 @@ def Adicionar_cartao(user_name: str, nome_cartao: str, numero_cartao: str, cvv: return (True, problemas) -def Adicionar_pix(user_name: str, nome_completo: str, cpf: str): +def Adicionar_pix(nome_completo: str, cpf: str): if cpf not in database: database[cpf] = [] pix = { + "id" : abs(hash((datetime.datetime.now(), cpf))), "tipo": "pix", "nome_completo": nome_completo, "cpf": cpf @@ -72,12 +74,13 @@ def Adicionar_pix(user_name: str, nome_completo: str, cpf: str): database[cpf].append(pix) escrever_arquivo(database) -def Adicionar_boleto(user_name:str, nome_completo: str, cpf: str): +def Adicionar_boleto(nome_completo: str, cpf: str): if cpf not in database: database[cpf] = [] pix = { + "id" : abs(hash((datetime.datetime.now(), cpf))), "tipo": "boleto", "nome_completo": nome_completo, "cpf": cpf @@ -97,6 +100,50 @@ def obter_lista_de_metodos_pagamento(cpf: str): return metodos_usuario +def atualizar_cartao(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validade: datetime.date): + + dados = ler_arquivo(database) + + problemas = [] + + for chave in dados: + for valor in dados[chave]: + if valor["id"] == id: + + if not validade >= datetime.date.today(): + problemas.append("VALIDADE") + + # if not cartao_pattern.match(numero_cartao): + # problemas.append("CARD_NUMBER")cx + + if len(problemas) > 0: + return (False, problemas) + + valor["nome_cartao"] = nome_cartao + valor["numero_cartao"] = numero_cartao + valor["cvv"] = cvv + valor["validade"] = validade + + escrever_arquivo(dados) + + return (True, ["SUCESS"]) + else: + problemas.append("ID_NOT_FOUND") + return (False, problemas) + +def atualizar_boleto_pix(id: int, nome_completo: str): + + dados = ler_arquivo(database) + + for chave in dados: + for valor in dados[chave]: + if valor["id"] == id: + valor["nome_completo"] = nome_completo + escrever_arquivo(dados) + return True + else: + return False + diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index cce3a789..153ae17a 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -64,4 +64,20 @@ def INEXISTENT_USER() -> HttpResponseModel: message="O usuário não está registrado na base de dados", status_code=400 ) + + @staticmethod + def INEXISTENT_ID() -> HttpResponseModel: + + return HttpResponseModel ( + message="ID não encontrado na base de dados", + status_code=400 + ) + + @staticmethod + def UPDATE_SUCESSFULLY() -> HttpResponseModel: + + return HttpResponseModel ( + message="Dados atualizados com sucesso", + status_code=200 + ) \ No newline at end of file diff --git a/backend/src/schemas/payment_schema.py b/backend/src/schemas/payment_schema.py index 752e85f6..ad72e28b 100644 --- a/backend/src/schemas/payment_schema.py +++ b/backend/src/schemas/payment_schema.py @@ -19,6 +19,16 @@ class Boleto(BaseModel): nome_completo: str cpf: str +class CartaoUpdate(BaseModel): + nome_cartao: str + numero_cartao: str + cvv: str + validade: datetime.date + +class PixUpdate(BaseModel): + nome_completo: str +class BoletoUpdate(PixUpdate): + pass diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index b283d1f3..40bf17d6 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,5 +1,5 @@ -from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto, obter_lista_de_metodos_pagamento -from src.schemas.payment_schema import Cartao, Pix, Boleto +from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto, atualizar_boleto_pix, obter_lista_de_metodos_pagamento, atualizar_cartao +from src.schemas.payment_schema import Cartao, Pix, Boleto, CartaoUpdate, PixUpdate, BoletoUpdate from src.schemas.response import HTTPResponses, HttpResponseModel from src.schemas.payment_response import HTTPPaymentResponse @@ -33,6 +33,7 @@ def insertion_boleto(boleto: Boleto) -> HttpResponseModel: return HTTPPaymentResponse.BOLETO_INSERTED_SUCESSFULLY() + @staticmethod def get_payment_methods(cpf: str): resultado = obter_lista_de_metodos_pagamento(cpf) @@ -40,4 +41,41 @@ def get_payment_methods(cpf: str): if resultado is None: return HTTPPaymentResponse.INEXISTENT_USER() else: - return resultado \ No newline at end of file + return resultado + + @staticmethod + def update_cartao(id: int, cartao: CartaoUpdate): + + sucesso, problemas = atualizar_cartao(id, *cartao.model_dump().values()) + + if not sucesso: + + if "VALIDADE" in problemas: + return HTTPPaymentResponse.BAD_REQUEST() + + if "ID_NOT_FOUND" in problemas: + return HTTPPaymentResponse.INEXISTENT_ID() + + return HTTPPaymentResponse.UPDATE_SUCESSFULLY() + + @staticmethod + def update_pix(id:int, pix: PixUpdate): + + sucesso = atualizar_boleto_pix(id, *pix.model_dump().values()) + + if not sucesso: + + return HTTPPaymentResponse.INEXISTENT_ID() + + return HTTPPaymentResponse.UPDATE_SUCESSFULLY() + + @staticmethod + def update_boleto(id:int, boleto: BoletoUpdate): + + sucesso = atualizar_boleto_pix(id, *boleto.model_dump().values()) + + if not sucesso: + + return HTTPPaymentResponse.INEXISTENT_ID() + + return HTTPPaymentResponse.UPDATE_SUCESSFULLY() \ No newline at end of file From 4c2e5c5199d20d261831cf5f54b3c5301f074222 Mon Sep 17 00:00:00 2001 From: Breno Date: Thu, 15 Feb 2024 02:50:53 -0300 Subject: [PATCH 45/62] feat: adding the deletion methods --- backend/payment_database.json | 4 ++-- backend/src/api/payment_methods.py | 12 +++++++++++ backend/src/db/payment_database.py | 21 +++++++++++++++++++ backend/src/schemas/payment_response.py | 8 +++++++ .../service/impl/payment_method_service.py | 15 +++++++++++-- 5 files changed, 56 insertions(+), 4 deletions(-) diff --git a/backend/payment_database.json b/backend/payment_database.json index 32573ce9..ea9d3ce2 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,9 +1,9 @@ { "111.111.111-11": [ { - "id": 290598277920648421, + "id": 1140908644383793786, "tipo": "pix", - "nome_completo": "ZOro", + "nome_completo": "Maria Alvez", "cpf": "111.111.111-11" } ] diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index bf26eb22..833ab9ba 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -83,6 +83,18 @@ def update_payment(card_id: int, boleto: BoletoUpdate): return response +@router.delete( + "/delete/{method_id}", + response_model=HttpResponseModel, + status_code=200, + description="Delete a payment method" +) +def delete_method(method_id: int): + + response = PaymentService.delete_method(method_id) + + return response + # @router.post( # "/inserting/{method_name}", # response_model=HttpResponseModel, diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index e1004125..a8567942 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -144,6 +144,27 @@ def atualizar_boleto_pix(id: int, nome_completo: str): else: return False +def deletar_metodo(id: int): + + dados = ler_arquivo(database) + + for chave in dados: + for valor in dados[chave]: + if valor["id"] == id: + + index = dados[chave].index(valor) + + del dados[chave][index] + + escrever_arquivo(dados) + + return True + + else: + return False + + + diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 153ae17a..2d60723b 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -80,4 +80,12 @@ def UPDATE_SUCESSFULLY() -> HttpResponseModel: message="Dados atualizados com sucesso", status_code=200 ) + + @staticmethod + def DELETE_SUCESSFULLY() -> HttpResponseModel: + + return HttpResponseModel ( + message="Deleção realizada com sucesso", + status_code=200 + ) \ No newline at end of file diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 40bf17d6..78ff5d21 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,4 +1,4 @@ -from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto, atualizar_boleto_pix, obter_lista_de_metodos_pagamento, atualizar_cartao +from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto, atualizar_boleto_pix, obter_lista_de_metodos_pagamento, atualizar_cartao, deletar_metodo from src.schemas.payment_schema import Cartao, Pix, Boleto, CartaoUpdate, PixUpdate, BoletoUpdate from src.schemas.response import HTTPResponses, HttpResponseModel from src.schemas.payment_response import HTTPPaymentResponse @@ -78,4 +78,15 @@ def update_boleto(id:int, boleto: BoletoUpdate): return HTTPPaymentResponse.INEXISTENT_ID() - return HTTPPaymentResponse.UPDATE_SUCESSFULLY() \ No newline at end of file + return HTTPPaymentResponse.UPDATE_SUCESSFULLY() + + @staticmethod + def delete_method(id: int): + + sucesso = deletar_metodo(id) + + if not sucesso: + + return HTTPPaymentResponse.INEXISTENT_ID() + + return HTTPPaymentResponse.DELETE_SUCESSFULLY() From 3c50c53db75c0c5a4c0729d0faf9fa66469848d0 Mon Sep 17 00:00:00 2001 From: Breno Date: Thu, 15 Feb 2024 02:59:14 -0300 Subject: [PATCH 46/62] fix: some ajusts --- backend/src/api/payment_methods.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index 833ab9ba..cb1e6f7d 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -48,38 +48,38 @@ def get_payment_methods(username:str): return request @router.put( - "update/cartao/{card_id}", + "update/cartao/{id}", response_model=HttpResponseModel, status_code=200, description="Update the card payment method" ) -def update_payment(card_id: int, cartao: CartaoUpdate): +def update_payment(id: int, cartao: CartaoUpdate): - response = PaymentService.update_cartao(card_id, cartao) + response = PaymentService.update_cartao(id, cartao) return response @router.put( - "/update/pix/{card_id}", + "/update/pix/{id}", response_model=HttpResponseModel, status_code=200, description="Update the pix payment method" ) -def update_payment(card_id: int, pix: PixUpdate): +def update_payment(id: int, pix: PixUpdate): - response = PaymentService.update_pix(card_id, pix) + response = PaymentService.update_pix(id, pix) return response @router.put( - "/update/boleto/{card_id}", + "/update/boleto/{id}", response_model=HttpResponseModel, status_code=200, description="Update the boleto payment method" ) -def update_payment(card_id: int, boleto: BoletoUpdate): +def update_payment(id: int, boleto: BoletoUpdate): - response = PaymentService.update_boleto(card_id, boleto) + response = PaymentService.update_boleto(id, boleto) return response From b085c37ea46660a7770c8cc5c6de9868b14ed5c5 Mon Sep 17 00:00:00 2001 From: Breno Date: Thu, 15 Feb 2024 10:34:47 -0300 Subject: [PATCH 47/62] refactor: unifying the 'InSERTION_SUCESSFULYY' method --- backend/src/service/impl/payment_method_service.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 78ff5d21..0277551c 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -11,7 +11,7 @@ def inserting_cartao(cartao: Cartao) -> HttpResponseModel: sucesso, problemas = Adicionar_cartao(*cartao.model_dump().values()) if sucesso: - return HTTPPaymentResponse.INSERTION_SUCESSFULLY() + return HTTPPaymentResponse.INSERTION_SUCESSFULLY("cartao") elif "CPF" in problemas or "VALIDADE" in problemas or "CARD_NUMBER" in problemas: return HTTPPaymentResponse.BAD_REQUEST(problemas) # elif "VALIDADE" in problemas: @@ -24,14 +24,14 @@ def insertion_pix(pix: Pix) -> HttpResponseModel: Adicionar_pix(*pix.model_dump().values()) - return HTTPPaymentResponse.PIX_INSERTED_SUCESSFULLY() + return HTTPPaymentResponse.INSERTION_SUCESSFULLY("pix") @staticmethod def insertion_boleto(boleto: Boleto) -> HttpResponseModel: Adicionar_boleto(*boleto.model_dump().values()) - return HTTPPaymentResponse.BOLETO_INSERTED_SUCESSFULLY() + return HTTPPaymentResponse.INSERTION_SUCESSFULLY("boleto") @staticmethod def get_payment_methods(cpf: str): From 66b0288944e48f7cb7c22eb82290e8ca570d3643 Mon Sep 17 00:00:00 2001 From: Breno Date: Thu, 15 Feb 2024 11:10:55 -0300 Subject: [PATCH 48/62] feat: adding the card number validation --- backend/payment_database.json | 27 ++++++++++++++++--- backend/src/db/payment_database.py | 6 ++--- backend/src/schemas/payment_response.py | 10 +++---- .../service/impl/payment_method_service.py | 6 +---- 4 files changed, 33 insertions(+), 16 deletions(-) diff --git a/backend/payment_database.json b/backend/payment_database.json index ea9d3ce2..8f973138 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,9 +1,30 @@ { "111.111.111-11": [ { - "id": 1140908644383793786, - "tipo": "pix", - "nome_completo": "Maria Alvez", + "id": 3658846314118992311, + "tipo": "cartao", + "nome_cartao": "MasterCard", + "numero_cartao": "4916538421959382", + "cvv": "493", + "validade": "2026-02-15", + "cpf": "111.111.111-11" + }, + { + "id": 7240078092176620861, + "tipo": "cartao", + "nome_cartao": "MasterCard", + "numero_cartao": "30568901234567", + "cvv": "493", + "validade": "2026-02-15", + "cpf": "111.111.111-11" + }, + { + "id": 7552644434137195974, + "tipo": "cartao", + "nome_cartao": "MasterCard", + "numero_cartao": "30568901234567", + "cvv": "493", + "validade": "2026-02-15", "cpf": "111.111.111-11" } ] diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index a8567942..4f462098 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -13,7 +13,7 @@ logger = getLogger('uvicorn') cpf_pattern = re.compile(r"^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2}$") -cartao_pattern = re.compile(r"^5[1-5][0-9]{14}$") +cartao_pattern = re.compile(r"^(4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9]{2})[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])?[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$") database = {} @@ -35,8 +35,8 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v if not validade >= datetime.date.today(): problemas.append("VALIDADE") - # if not cartao_pattern.match(numero_cartao): - # problemas.append("CARD_NUMBER")cx + if not cartao_pattern.match(numero_cartao): + problemas.append("CARD_NUMBER") if len(problemas) > 0: return (False, problemas) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 2d60723b..d2a633c4 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -5,9 +5,9 @@ class HTTPPaymentResponse: @staticmethod - def INSERTION_SUCESSFULLY() -> HttpResponseModel: + def INSERTION_SUCESSFULLY(metodo_pagamento) -> HttpResponseModel: return HttpResponseModel ( - message="Payment method has been inserted sucessfully", + message=f"{metodo_pagamento} foi cadastrado com sucesso", status_code=201 ) @@ -36,9 +36,9 @@ def INSERTION_SUCESSFULLY() -> HttpResponseModel: def BAD_REQUEST(problemas) -> HttpResponseModel: return HttpResponseModel ( - message="Os campos a seguir estão preenchidos incorretamente", - status_code=400, - data= problemas + message=f" informações inválidas", + status_code=400, + data= problemas ) @staticmethod diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 0277551c..f59e83bc 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -12,12 +12,8 @@ def inserting_cartao(cartao: Cartao) -> HttpResponseModel: if sucesso: return HTTPPaymentResponse.INSERTION_SUCESSFULLY("cartao") - elif "CPF" in problemas or "VALIDADE" in problemas or "CARD_NUMBER" in problemas: + else: return HTTPPaymentResponse.BAD_REQUEST(problemas) - # elif "VALIDADE" in problemas: - # return HTTPPaymentResponse.EXPIRED_DATA() - # elif "CARD_NUMBER" in problemas: - # return HTTPPaymentResponse.INVALID_NUMBER() @staticmethod def insertion_pix(pix: Pix) -> HttpResponseModel: From e4ea717ca51e7a08218bb787f5fdd7f26167e02f Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 16 Feb 2024 10:11:52 -0300 Subject: [PATCH 49/62] feat: adding a CPF validator for pix and ticket --- backend/payment_database.json | 31 +++---------------- backend/src/api/payment_methods.py | 4 +-- backend/src/db/payment_database.py | 18 ++++++++++- backend/src/schemas/payment_response.py | 4 +-- .../service/impl/payment_method_service.py | 20 +++++++----- 5 files changed, 39 insertions(+), 38 deletions(-) diff --git a/backend/payment_database.json b/backend/payment_database.json index 8f973138..09c77e09 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,31 +1,10 @@ { - "111.111.111-11": [ + "331.704.260-52": [ { - "id": 3658846314118992311, - "tipo": "cartao", - "nome_cartao": "MasterCard", - "numero_cartao": "4916538421959382", - "cvv": "493", - "validade": "2026-02-15", - "cpf": "111.111.111-11" - }, - { - "id": 7240078092176620861, - "tipo": "cartao", - "nome_cartao": "MasterCard", - "numero_cartao": "30568901234567", - "cvv": "493", - "validade": "2026-02-15", - "cpf": "111.111.111-11" - }, - { - "id": 7552644434137195974, - "tipo": "cartao", - "nome_cartao": "MasterCard", - "numero_cartao": "30568901234567", - "cvv": "493", - "validade": "2026-02-15", - "cpf": "111.111.111-11" + "id": 739609097065126675, + "tipo": "pix", + "nome_completo": "Breno Gabriel de Melo Lima", + "cpf": "331.704.260-52" } ] } \ No newline at end of file diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index cb1e6f7d..26f98150 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -14,7 +14,7 @@ description="Insert a new card", ) def insert_payment(cartao: Cartao) -> HttpResponseModel: - response = PaymentService.inserting_cartao(cartao) + response = PaymentService.inserting_card(cartao) return response @router.post( @@ -34,7 +34,7 @@ def insert_payment(pix: Pix) -> HttpResponseModel: description="Insert a new boleto acount", ) def insert_payment(boleto: Boleto) -> HttpResponseModel: - response = PaymentService.insertion_boleto(boleto) + response = PaymentService.insertion_ticket(boleto) return response @router.get( diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index 4f462098..e1cc05c9 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -61,6 +61,14 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v def Adicionar_pix(nome_completo: str, cpf: str): + problemas = [] + + if not cpf_pattern.match(cpf): + problemas.append("CPF") + + if len(problemas) > 0: + return (False, problemas) + if cpf not in database: database[cpf] = [] @@ -74,7 +82,15 @@ def Adicionar_pix(nome_completo: str, cpf: str): database[cpf].append(pix) escrever_arquivo(database) -def Adicionar_boleto(nome_completo: str, cpf: str): +def Adicionar_boleto(nome_completo: str, cpf: str): + + problemas = [] + + if not cpf_pattern.match(cpf): + problemas.append("CPF") + + if len(problemas) > 0: + return (False, problemas) if cpf not in database: database[cpf] = [] diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index d2a633c4..64169a14 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -5,9 +5,9 @@ class HTTPPaymentResponse: @staticmethod - def INSERTION_SUCESSFULLY(metodo_pagamento) -> HttpResponseModel: + def INSERTION_SUCESSFULLY() -> HttpResponseModel: return HttpResponseModel ( - message=f"{metodo_pagamento} foi cadastrado com sucesso", + message="metodo de pagamento cadastrado com sucesso", status_code=201 ) diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index f59e83bc..91089cf2 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -6,28 +6,34 @@ class PaymentService: @staticmethod - def inserting_cartao(cartao: Cartao) -> HttpResponseModel: + def inserting_card(cartao: Cartao) -> HttpResponseModel: sucesso, problemas = Adicionar_cartao(*cartao.model_dump().values()) if sucesso: - return HTTPPaymentResponse.INSERTION_SUCESSFULLY("cartao") + return HTTPPaymentResponse.INSERTION_SUCESSFULLY() else: return HTTPPaymentResponse.BAD_REQUEST(problemas) @staticmethod def insertion_pix(pix: Pix) -> HttpResponseModel: - Adicionar_pix(*pix.model_dump().values()) + sucesso, problemas = Adicionar_pix(*pix.model_dump().values()) - return HTTPPaymentResponse.INSERTION_SUCESSFULLY("pix") + if not sucesso: + return HTTPPaymentResponse.BAD_REQUEST(problemas) + + return HTTPPaymentResponse.INSERTION_SUCESSFULLY() @staticmethod - def insertion_boleto(boleto: Boleto) -> HttpResponseModel: + def insertion_ticket(boleto: Boleto) -> HttpResponseModel: - Adicionar_boleto(*boleto.model_dump().values()) + sucesso, problemas = Adicionar_pix(*boleto.model_dump().values()) + + if not sucesso: + return HTTPPaymentResponse.BAD_REQUEST(problemas) - return HTTPPaymentResponse.INSERTION_SUCESSFULLY("boleto") + return HTTPPaymentResponse.INSERTION_SUCESSFULLY() @staticmethod def get_payment_methods(cpf: str): From 1704a9bdba099aeeea4a2aed43b7a4b1b4a18522 Mon Sep 17 00:00:00 2001 From: Breno Date: Fri, 16 Feb 2024 21:37:27 -0300 Subject: [PATCH 50/62] refactor: Adding some comments and translating functions and variables from Portuguese to English. --- backend/payment_database.json | 20 +- backend/src/api/payment_methods.py | 18 +- backend/src/db/payment_database.py | 223 ++++++++++++------ .../service/impl/payment_method_service.py | 58 ++--- 4 files changed, 209 insertions(+), 110 deletions(-) diff --git a/backend/payment_database.json b/backend/payment_database.json index 09c77e09..2568cc1d 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,10 +1,24 @@ { "331.704.260-52": [ { - "id": 739609097065126675, - "tipo": "pix", - "nome_completo": "Breno Gabriel de Melo Lima", + "id": 2117535573691622482, + "tipo": "cartao", + "nome_cartao": "American Express", + "numero_cartao": "371449635398431", + "cvv": "764", + "validade": "2028-02-16", "cpf": "331.704.260-52" } + ], + "111.111.111-11": [ + { + "id": 4696510612940182689, + "tipo": "cartao", + "nome_cartao": "masterCard", + "numero_cartao": "4916123456789012", + "cvv": "242", + "validade": "2024-02-16", + "cpf": "111.111.111-11" + } ] } \ No newline at end of file diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index 26f98150..b9869d16 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -37,15 +37,15 @@ def insert_payment(boleto: Boleto) -> HttpResponseModel: response = PaymentService.insertion_ticket(boleto) return response -@router.get( - "/get/payment_methods", - description="Get the payments methods of a especific user" -) -def get_payment_methods(username:str): +# @router.get( +# "/get/payment_methods", +# description="Get the payments methods of a especific user" +# ) +# def get_payment_methods(username:str): - request = PaymentService.get_payment_methods(username) +# request = PaymentService.get_payment_methods(username) - return request +# return request @router.put( "update/cartao/{id}", @@ -55,7 +55,7 @@ def get_payment_methods(username:str): ) def update_payment(id: int, cartao: CartaoUpdate): - response = PaymentService.update_cartao(id, cartao) + response = PaymentService.update_card(id, cartao) return response @@ -79,7 +79,7 @@ def update_payment(id: int, pix: PixUpdate): ) def update_payment(id: int, boleto: BoletoUpdate): - response = PaymentService.update_boleto(id, boleto) + response = PaymentService.update_ticket(id, boleto) return response diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index e1cc05c9..bf67066c 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -12,34 +12,98 @@ logger = getLogger('uvicorn') +#Regex for CPF and card number. cpf_pattern = re.compile(r"^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2}$") cartao_pattern = re.compile(r"^(4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9]{2})[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])?[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$") database = {} -def escrever_arquivo(database): +def write_file(database): + + """Write the content of a dict in a JSON. + + Input: database: dict. + + Process: Open the JSON file and overwrite it's content. + + Output: JSON file overwrited. """ + with open("payment_database.json", "w") as f: json.dump(database, f, default=str, indent=4) -def ler_arquivo(database): - with open("payment_database.json", "r") as f: - return json.load(f) +# def read_file(database): +# with open("payment_database.json", "r") as f: +# return json.load(f) + +def validate_CPF(cpf: str) -> bool: -def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> bool: + """Validate a CPF number. - problemas = [] + Input: a CPF number. + + Process: verify the validity of a CPF number using a regex. + + Outuput: A boolean indicating the validity or not of the CPF number. """ if not cpf_pattern.match(cpf): - problemas.append("CPF") + return False + + return True + +def validate_date(validade: datetime.date) -> bool: + + """Validate a validity date. + + Input: a date. + + Process: compare the input date with the today date. + + Outuput: A boolean indicating the validity or not of the input date. """ if not validade >= datetime.date.today(): - problemas.append("VALIDADE") + return False + + return True + +def validate_card_number(numero_cartao: str) -> bool: + + """Validate a card number. + + Input: a card number. + + Process: verify the validity of the card number using a regex. + + Outuput: A boolean indicating the validity or not of the card number. """ if not cartao_pattern.match(numero_cartao): - problemas.append("CARD_NUMBER") + return False + + return True + +def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> tuple[bool, List]: + + """Validate and insert or not a card. + + Input: the card information pass by the service layer. - if len(problemas) > 0: - return (False, problemas) + Process: use the "validate_cpf", "validate_date" and "validate_card_number" for verify the validity of the card informations. + if the informations is valid, the card is insert in a dict and writted in the JSON file. + + Output: A tuple contain the sucess (bool) of the insertion and the problems (List) in case of validation problem. """ + + problems = [] + + if not validate_CPF(cpf): + problems.append("CPF") + + if not validate_date(validade): + problems.append("VALIDADE") + + if not validate_card_number(numero_cartao): + problems.append("CARD_NUMBER") + + if len(problems) > 0: + return (False, problems) if cpf not in database: database[cpf] = [] @@ -55,20 +119,26 @@ def Adicionar_cartao(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, v } database[cpf].append(cartao) - escrever_arquivo(database) + write_file(database) - return (True, problemas) + return (True, problems) -def Adicionar_pix(nome_completo: str, cpf: str): +def insert_pix(nome_completo: str, cpf: str): - problemas = [] + """Validate and insert or not a pix. - if not cpf_pattern.match(cpf): - problemas.append("CPF") - - if len(problemas) > 0: - return (False, problemas) + Input: the pix information pass by the service layer. + + Process: use the "validate_cpf" for verify the validity of the pix informations. + if the informations is valid, the pix is insert in a dict and writted in the JSON file. + Output: A tuple contain the sucess (bool) of the insertion. """ + + result = validate_CPF(cpf) + + if not result: + return False + if cpf not in database: database[cpf] = [] @@ -80,18 +150,26 @@ def Adicionar_pix(nome_completo: str, cpf: str): } database[cpf].append(pix) - escrever_arquivo(database) + write_file(database) -def Adicionar_boleto(nome_completo: str, cpf: str): + return True - problemas = [] +def insert_ticket(nome_completo: str, cpf: str): - if not cpf_pattern.match(cpf): - problemas.append("CPF") - - if len(problemas) > 0: - return (False, problemas) + """Validate and insert or not a ticket. + + Input: the ticket information pass by the service layer. + + Process: use the "validate_cpf" for verify the validity of the ticket informations. + if the informations is valid, the ticket is insert in a dict and writted in the JSON file. + + Output: A tuple contain the sucess (bool) of the insertion. """ + + result = validate_CPF(cpf) + if not result: + return False + if cpf not in database: database[cpf] = [] @@ -103,76 +181,83 @@ def Adicionar_boleto(nome_completo: str, cpf: str): } database[cpf].append(pix) - escrever_arquivo(database) + write_file(database) + + return True -def obter_lista_de_metodos_pagamento(cpf: str): +# def obter_lista_de_metodos_pagamento(cpf: str): - dados = ler_arquivo(database) +# database = ler_arquivo(database) - if cpf in dados: - metodos_usuario = dados[cpf] - else: - metodos_usuario = None +# if cpf in database: +# metodos_usuario = database[cpf] +# else: +# metodos_usuario = None - return metodos_usuario +# return metodos_usuario + +def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validade: datetime.date): -def atualizar_cartao(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validade: datetime.date): + """Update the nome_cartao, numero_cartao, cvv and validade fields. - dados = ler_arquivo(database) + #Input: the card informations (id, nome_cartao, numero_cartao, cvv and validade). - problemas = [] + #Process: Verify if the card is in the database (using the ID). If the card is in database, + make the validation of card number and validity date. If the validation is sucessfull, + update the card information in the database and write in the JSON file + + Output: a tuple with the result and a array with the problems""" + + problems = [] - for chave in dados: - for valor in dados[chave]: - if valor["id"] == id: + for key in database: + for val in database[key]: + if val["id"] == id: if not validade >= datetime.date.today(): - problemas.append("VALIDADE") + problems.append("VALIDADE") # if not cartao_pattern.match(numero_cartao): - # problemas.append("CARD_NUMBER")cx + # problems.append("CARD_NUMBER")cx - if len(problemas) > 0: - return (False, problemas) + if len(problems) > 0: + return (False, problems) - valor["nome_cartao"] = nome_cartao - valor["numero_cartao"] = numero_cartao - valor["cvv"] = cvv - valor["validade"] = validade + val["nome_cartao"] = nome_cartao + val["numero_cartao"] = numero_cartao + val["cvv"] = cvv + val["validade"] = validade - escrever_arquivo(dados) + write_file(database) return (True, ["SUCESS"]) else: - problemas.append("ID_NOT_FOUND") - return (False, problemas) + problems.append("ID_NOT_FOUND") + return (False, problems) -def atualizar_boleto_pix(id: int, nome_completo: str): - dados = ler_arquivo(database) +def update_pix_or_ticket(id: int, nome_completo: str): - for chave in dados: - for valor in dados[chave]: - if valor["id"] == id: - valor["nome_completo"] = nome_completo - escrever_arquivo(dados) + for key in database: + for val in database[key]: + if val["id"] == id: + val["nome_completo"] = nome_completo + write_file(database) return True else: return False -def deletar_metodo(id: int): - - dados = ler_arquivo(database) +def delete_method(id: int): - for chave in dados: - for valor in dados[chave]: - if valor["id"] == id: + for key in database: + for val in database[key]: + if val["id"] == id: - index = dados[chave].index(valor) + index = database[key].index(val) - del dados[chave][index] + del database[key][index] - escrever_arquivo(dados) + write_file(database) return True diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 91089cf2..3965bfc9 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -1,4 +1,4 @@ -from src.db.payment_database import Adicionar_cartao, Adicionar_pix, Adicionar_boleto, atualizar_boleto_pix, obter_lista_de_metodos_pagamento, atualizar_cartao, deletar_metodo +from src.db.payment_database import * from src.schemas.payment_schema import Cartao, Pix, Boleto, CartaoUpdate, PixUpdate, BoletoUpdate from src.schemas.response import HTTPResponses, HttpResponseModel from src.schemas.payment_response import HTTPPaymentResponse @@ -8,54 +8,54 @@ class PaymentService: @staticmethod def inserting_card(cartao: Cartao) -> HttpResponseModel: - sucesso, problemas = Adicionar_cartao(*cartao.model_dump().values()) + sucess, problems = insert_card(*cartao.model_dump().values()) - if sucesso: + if sucess: return HTTPPaymentResponse.INSERTION_SUCESSFULLY() else: - return HTTPPaymentResponse.BAD_REQUEST(problemas) + return HTTPPaymentResponse.BAD_REQUEST(problems) @staticmethod def insertion_pix(pix: Pix) -> HttpResponseModel: - sucesso, problemas = Adicionar_pix(*pix.model_dump().values()) + sucess, problems = insert_pix(*pix.model_dump().values()) - if not sucesso: - return HTTPPaymentResponse.BAD_REQUEST(problemas) + if not sucess: + return HTTPPaymentResponse.BAD_REQUEST(problems) return HTTPPaymentResponse.INSERTION_SUCESSFULLY() @staticmethod def insertion_ticket(boleto: Boleto) -> HttpResponseModel: - sucesso, problemas = Adicionar_pix(*boleto.model_dump().values()) + sucess, problems = insert_ticket(*boleto.model_dump().values()) - if not sucesso: - return HTTPPaymentResponse.BAD_REQUEST(problemas) + if not sucess: + return HTTPPaymentResponse.BAD_REQUEST(problems) return HTTPPaymentResponse.INSERTION_SUCESSFULLY() - @staticmethod - def get_payment_methods(cpf: str): + # @staticmethod + # def get_payment_methods(cpf: str): - resultado = obter_lista_de_metodos_pagamento(cpf) + # resultado = obter_lista_de_metodos_pagamento(cpf) - if resultado is None: - return HTTPPaymentResponse.INEXISTENT_USER() - else: - return resultado + # if resultado is None: + # return HTTPPaymentResponse.INEXISTENT_USER() + # else: + # return resultado @staticmethod - def update_cartao(id: int, cartao: CartaoUpdate): + def update_card(id: int, cartao: CartaoUpdate): - sucesso, problemas = atualizar_cartao(id, *cartao.model_dump().values()) + sucess, problems = update_card(id, *cartao.model_dump().values()) - if not sucesso: + if not sucess: - if "VALIDADE" in problemas: + if "VALIDADE" in problems: return HTTPPaymentResponse.BAD_REQUEST() - if "ID_NOT_FOUND" in problemas: + if "ID_NOT_FOUND" in problems: return HTTPPaymentResponse.INEXISTENT_ID() return HTTPPaymentResponse.UPDATE_SUCESSFULLY() @@ -63,20 +63,20 @@ def update_cartao(id: int, cartao: CartaoUpdate): @staticmethod def update_pix(id:int, pix: PixUpdate): - sucesso = atualizar_boleto_pix(id, *pix.model_dump().values()) + sucess = update_pix_or_ticket(id, *pix.model_dump().values()) - if not sucesso: + if not sucess: return HTTPPaymentResponse.INEXISTENT_ID() return HTTPPaymentResponse.UPDATE_SUCESSFULLY() @staticmethod - def update_boleto(id:int, boleto: BoletoUpdate): + def update_ticket(id:int, boleto: BoletoUpdate): - sucesso = atualizar_boleto_pix(id, *boleto.model_dump().values()) + sucess = update_pix_or_ticket(id, *boleto.model_dump().values()) - if not sucesso: + if not sucess: return HTTPPaymentResponse.INEXISTENT_ID() @@ -85,9 +85,9 @@ def update_boleto(id:int, boleto: BoletoUpdate): @staticmethod def delete_method(id: int): - sucesso = deletar_metodo(id) + sucess = delete_method(id) - if not sucesso: + if not sucess: return HTTPPaymentResponse.INEXISTENT_ID() From 1d5ad24896461ae0bbfe4cba61cc6dc1d4009398 Mon Sep 17 00:00:00 2001 From: Breno Date: Sun, 18 Feb 2024 11:42:02 -0300 Subject: [PATCH 51/62] feat: adding a already exist pix or boleto verifier --- backend/src/db/payment_database.py | 101 ++++++++++-------- .../service/impl/payment_method_service.py | 18 ++-- 2 files changed, 69 insertions(+), 50 deletions(-) diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index bf67066c..ddd40a1d 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -1,5 +1,7 @@ +import os from typing import List, Dict from uuid import uuid4 +import jsonpickle from pymongo import MongoClient, errors from pymongo.collection import Collection, IndexModel #from src.config.config import env @@ -9,15 +11,15 @@ import hashlib import re import json +import datetime + logger = getLogger('uvicorn') #Regex for CPF and card number. cpf_pattern = re.compile(r"^[0-9]{3}\.[0-9]{3}\.[0-9]{3}\-[0-9]{2}$") cartao_pattern = re.compile(r"^(4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9]{2})[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])?[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$") - -database = {} - + def write_file(database): """Write the content of a dict in a JSON. @@ -31,9 +33,11 @@ def write_file(database): with open("payment_database.json", "w") as f: json.dump(database, f, default=str, indent=4) -# def read_file(database): -# with open("payment_database.json", "r") as f: -# return json.load(f) +def read_file(): + with open("payment_database.json", "r") as f: + return json.load(f) + +database = read_file() def validate_CPF(cpf: str) -> bool: @@ -49,7 +53,7 @@ def validate_CPF(cpf: str) -> bool: return False return True - + def validate_date(validade: datetime.date) -> bool: """Validate a validity date. @@ -60,6 +64,7 @@ def validate_date(validade: datetime.date) -> bool: Outuput: A boolean indicating the validity or not of the input date. """ + if not validade >= datetime.date.today(): return False @@ -80,7 +85,7 @@ def validate_card_number(numero_cartao: str) -> bool: return True -def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date) -> tuple[bool, List]: +def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, validade: datetime.date): """Validate and insert or not a card. @@ -109,7 +114,7 @@ def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, valida database[cpf] = [] cartao = { - "id" : abs(hash((datetime.datetime.now(), cpf))), + "id" : abs(hash((datetime.date.today(), cpf))), "tipo": "cartao", "nome_cartao": nome_cartao, "numero_cartao": numero_cartao, @@ -121,9 +126,9 @@ def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, valida database[cpf].append(cartao) write_file(database) - return (True, problems) + return (True, []) -def insert_pix(nome_completo: str, cpf: str): +def insert_pix(nome_completo: str, cpf: str) -> str: """Validate and insert or not a pix. @@ -137,11 +142,16 @@ def insert_pix(nome_completo: str, cpf: str): result = validate_CPF(cpf) if not result: - return False + return "CPF" if cpf not in database: database[cpf] = [] + for key in database: + for val in database[key]: + if val["tipo"] == "boleto": + return "ALREADY_EXIST" + pix = { "id" : abs(hash((datetime.datetime.now(), cpf))), "tipo": "pix", @@ -152,9 +162,11 @@ def insert_pix(nome_completo: str, cpf: str): database[cpf].append(pix) write_file(database) - return True + print(database) -def insert_ticket(nome_completo: str, cpf: str): + return "OK" + +def insert_ticket(nome_completo: str, cpf: str) -> str: """Validate and insert or not a ticket. @@ -168,11 +180,16 @@ def insert_ticket(nome_completo: str, cpf: str): result = validate_CPF(cpf) if not result: - return False + return "INVALID_CPF" if cpf not in database: database[cpf] = [] + for key in database: + for val in database[key]: + if val["tipo"] == "boleto": + return "ALREADY_EXIST" + pix = { "id" : abs(hash((datetime.datetime.now(), cpf))), "tipo": "boleto", @@ -183,18 +200,7 @@ def insert_ticket(nome_completo: str, cpf: str): database[cpf].append(pix) write_file(database) - return True - -# def obter_lista_de_metodos_pagamento(cpf: str): - -# database = ler_arquivo(database) - -# if cpf in database: -# metodos_usuario = database[cpf] -# else: -# metodos_usuario = None - -# return metodos_usuario + return "OK" def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validade: datetime.date): @@ -210,6 +216,7 @@ def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validad problems = [] + for key in database: for val in database[key]: if val["id"] == id: @@ -217,8 +224,8 @@ def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validad if not validade >= datetime.date.today(): problems.append("VALIDADE") - # if not cartao_pattern.match(numero_cartao): - # problems.append("CARD_NUMBER")cx + if not cartao_pattern.match(numero_cartao): + problems.append("CARD_NUMBER") if len(problems) > 0: return (False, problems) @@ -230,27 +237,30 @@ def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validad write_file(database) - return (True, ["SUCESS"]) - else: - problems.append("ID_NOT_FOUND") - return (False, problems) + print(database) + return (True, ["SUCESS"]) + + problems.append("ID_NOT_FOUND") + return (False, problems) -def update_pix_or_ticket(id: int, nome_completo: str): +def update_pix_or_ticket(id: int, nome_completo: str) -> bool: + for key in database: for val in database[key]: if val["id"] == id: val["nome_completo"] = nome_completo write_file(database) return True - else: - return False + + return False -def delete_method(id: int): +def delete_method(id: int) -> bool: for key in database: for val in database[key]: + if val["id"] == id: index = database[key].index(val) @@ -260,12 +270,17 @@ def delete_method(id: int): write_file(database) return True + + return False - else: - return False - - - - +def get_by_number(numero_cartao: str): + for key in database: + for val in database[key]: + if val["tipo"] == "cartao": + if val["numero_cartao"] == numero_cartao: + + return val + + return None diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 3965bfc9..69084811 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -18,20 +18,24 @@ def inserting_card(cartao: Cartao) -> HttpResponseModel: @staticmethod def insertion_pix(pix: Pix) -> HttpResponseModel: - sucess, problems = insert_pix(*pix.model_dump().values()) + result = insert_pix(*pix.model_dump().values()) - if not sucess: - return HTTPPaymentResponse.BAD_REQUEST(problems) + if result == "CPF": + return HTTPPaymentResponse.BAD_REQUEST(["CPF"]) + elif result == "ALREADY_EXIST": + return HTTPPaymentResponse.PIX_ALREADY_EXIST() return HTTPPaymentResponse.INSERTION_SUCESSFULLY() @staticmethod def insertion_ticket(boleto: Boleto) -> HttpResponseModel: - sucess, problems = insert_ticket(*boleto.model_dump().values()) + result = insert_ticket(*boleto.model_dump().values()) - if not sucess: - return HTTPPaymentResponse.BAD_REQUEST(problems) + if result == "CPF": + return HTTPPaymentResponse.BAD_REQUEST(["CPF"]) + elif result == "ALREADY_EXIST": + return HTTPPaymentResponse.BOLETO_ALREADY_EXIST() return HTTPPaymentResponse.INSERTION_SUCESSFULLY() @@ -91,4 +95,4 @@ def delete_method(id: int): return HTTPPaymentResponse.INEXISTENT_ID() - return HTTPPaymentResponse.DELETE_SUCESSFULLY() + return HTTPPaymentResponse.DELETE_SUCESSFULLY() \ No newline at end of file From b00e8d4b40166bef89efeafeb647da89c8bc2fea Mon Sep 17 00:00:00 2001 From: Breno Date: Sun, 18 Feb 2024 11:43:14 -0300 Subject: [PATCH 52/62] feat: adding the PIX_AREADY_EXIST and BOLETO_ALREADY_EXIST functions --- backend/src/schemas/payment_response.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 64169a14..5485421f 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -88,4 +88,20 @@ def DELETE_SUCESSFULLY() -> HttpResponseModel: message="Deleção realizada com sucesso", status_code=200 ) + + @staticmethod + def PIX_ALREADY_EXIST() -> HttpResponseModel: + + return HttpResponseModel ( + message="Já existe um pix cadastrado no sistema", + status_code=400 + ) + + @staticmethod + def BOLETO_ALREADY_EXIST() -> HttpResponseModel: + + return HttpResponseModel ( + message="Já existe um boleto cadastrado no sistema", + status_code=400 + ) \ No newline at end of file From 1da408a2dc8f357a35b6b0ee2c1e47ebf9bd4c5d Mon Sep 17 00:00:00 2001 From: Breno Date: Sun, 18 Feb 2024 13:45:49 -0300 Subject: [PATCH 53/62] feat: adding some final adjusts --- backend/src/schemas/payment_response.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/backend/src/schemas/payment_response.py b/backend/src/schemas/payment_response.py index 5485421f..c63ac2dc 100644 --- a/backend/src/schemas/payment_response.py +++ b/backend/src/schemas/payment_response.py @@ -5,10 +5,13 @@ class HTTPPaymentResponse: @staticmethod - def INSERTION_SUCESSFULLY() -> HttpResponseModel: + def INSERTION_SUCESSFULLY(id: str) -> HttpResponseModel: return HttpResponseModel ( message="metodo de pagamento cadastrado com sucesso", - status_code=201 + status_code=201, + data = { + "ID": id + } ) # @staticmethod From 0ea3a7373b01450dd8c934c390758b1cd4e7e28f Mon Sep 17 00:00:00 2001 From: Breno Date: Sun, 18 Feb 2024 14:26:37 -0300 Subject: [PATCH 54/62] adding some final adjusts --- backend/payment_database.json | 24 +- backend/src/api/items.py | 10 +- backend/src/api/payment_methods.py | 8 +- backend/src/db/__init__.py | 3 - backend/src/db/payment_database.py | 81 ++++--- backend/src/service/impl/item_service.py | 66 +++--- .../service/impl/payment_method_service.py | 10 +- .../tests/api/step_definitions/test_items.py | 220 +++++++++--------- .../service/features/items-service.feature | 20 +- .../features/payment_methods-service.feature | 26 +++ .../step_definitions/test_items_service.py | 134 +++++------ .../test_payment_methods_service.py | 96 ++++++++ 12 files changed, 410 insertions(+), 288 deletions(-) create mode 100644 backend/src/tests/service/features/payment_methods-service.feature create mode 100644 backend/src/tests/service/step_definitions/test_payment_methods_service.py diff --git a/backend/payment_database.json b/backend/payment_database.json index 2568cc1d..3aef39c4 100644 --- a/backend/payment_database.json +++ b/backend/payment_database.json @@ -1,24 +1,10 @@ { - "331.704.260-52": [ + "111.111.111-10": [ { - "id": 2117535573691622482, - "tipo": "cartao", - "nome_cartao": "American Express", - "numero_cartao": "371449635398431", - "cvv": "764", - "validade": "2028-02-16", - "cpf": "331.704.260-52" - } - ], - "111.111.111-11": [ - { - "id": 4696510612940182689, - "tipo": "cartao", - "nome_cartao": "masterCard", - "numero_cartao": "4916123456789012", - "cvv": "242", - "validade": "2024-02-16", - "cpf": "111.111.111-11" + "id": "2616058799231613355", + "tipo": "pix", + "nome_completo": "Breno gabriel de Melo Lima", + "cpf": "111.111.111-10" } ] } \ No newline at end of file diff --git a/backend/src/api/items.py b/backend/src/api/items.py index 635e5f45..e50a350f 100644 --- a/backend/src/api/items.py +++ b/backend/src/api/items.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, status from src.schemas.response import HttpResponseModel -from src.service.impl.item_service import ItemService +# from src.service.impl.item_service import ItemService router = APIRouter() @@ -34,8 +34,8 @@ def get_item(item_id: str) -> HttpResponseModel: - HTTPException 404: If the item is not found. """ - item_get_response = ItemService.get_item(item_id) - return item_get_response + # item_get_response = ItemService.get_item(item_id) + # return item_get_response @router.get( @@ -60,9 +60,9 @@ def get_items() -> HttpResponseModel: """ - item_list_response = ItemService.get_items() + # item_list_response = ItemService.get_items() - return item_list_response + # return item_list_response # TODO: Add POST, PUT, DELETE endpoints \ No newline at end of file diff --git a/backend/src/api/payment_methods.py b/backend/src/api/payment_methods.py index b9869d16..ee4490a7 100644 --- a/backend/src/api/payment_methods.py +++ b/backend/src/api/payment_methods.py @@ -53,7 +53,7 @@ def insert_payment(boleto: Boleto) -> HttpResponseModel: status_code=200, description="Update the card payment method" ) -def update_payment(id: int, cartao: CartaoUpdate): +def update_payment(id: str, cartao: CartaoUpdate): response = PaymentService.update_card(id, cartao) @@ -65,7 +65,7 @@ def update_payment(id: int, cartao: CartaoUpdate): status_code=200, description="Update the pix payment method" ) -def update_payment(id: int, pix: PixUpdate): +def update_payment(id: str, pix: PixUpdate): response = PaymentService.update_pix(id, pix) @@ -77,7 +77,7 @@ def update_payment(id: int, pix: PixUpdate): status_code=200, description="Update the boleto payment method" ) -def update_payment(id: int, boleto: BoletoUpdate): +def update_payment(id: str, boleto: BoletoUpdate): response = PaymentService.update_ticket(id, boleto) @@ -89,7 +89,7 @@ def update_payment(id: int, boleto: BoletoUpdate): status_code=200, description="Delete a payment method" ) -def delete_method(method_id: int): +def delete_method(method_id: str): response = PaymentService.delete_method(method_id) diff --git a/backend/src/db/__init__.py b/backend/src/db/__init__.py index d8f0a8e8..b10be505 100644 --- a/backend/src/db/__init__.py +++ b/backend/src/db/__init__.py @@ -1,6 +1,3 @@ from .database import Database from .config.create_collections import create_collections -database = Database() - -create_collections(database) \ No newline at end of file diff --git a/backend/src/db/payment_database.py b/backend/src/db/payment_database.py index ddd40a1d..99ab7bb5 100644 --- a/backend/src/db/payment_database.py +++ b/backend/src/db/payment_database.py @@ -12,6 +12,7 @@ import re import json import datetime +import uuid logger = getLogger('uvicorn') @@ -36,7 +37,8 @@ def write_file(database): def read_file(): with open("payment_database.json", "r") as f: return json.load(f) - + +database = {} database = read_file() def validate_CPF(cpf: str) -> bool: @@ -96,6 +98,7 @@ def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, valida Output: A tuple contain the sucess (bool) of the insertion and the problems (List) in case of validation problem. """ + problems = [] if not validate_CPF(cpf): @@ -113,8 +116,10 @@ def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, valida if cpf not in database: database[cpf] = [] + id_value = str(abs(hash((datetime.date.today(), cpf)))) + cartao = { - "id" : abs(hash((datetime.date.today(), cpf))), + "id" : id_value, "tipo": "cartao", "nome_cartao": nome_cartao, "numero_cartao": numero_cartao, @@ -126,9 +131,9 @@ def insert_card(nome_cartao: str, numero_cartao: str, cvv: str, cpf: str, valida database[cpf].append(cartao) write_file(database) - return (True, []) + return (True, id_value) -def insert_pix(nome_completo: str, cpf: str) -> str: +def insert_pix(nome_completo: str, cpf: str) : """Validate and insert or not a pix. @@ -142,18 +147,19 @@ def insert_pix(nome_completo: str, cpf: str) -> str: result = validate_CPF(cpf) if not result: - return "CPF" + return ("CPF", None) if cpf not in database: - database[cpf] = [] - - for key in database: - for val in database[key]: - if val["tipo"] == "boleto": - return "ALREADY_EXIST" + database[cpf] = [] + for val in database[cpf]: + if val["tipo"] == "pix": + return ("ALREADY_EXIST", None) + + id_value = str(abs(hash((datetime.date.today(), cpf)))) + pix = { - "id" : abs(hash((datetime.datetime.now(), cpf))), + "id" : id_value, "tipo": "pix", "nome_completo": nome_completo, "cpf": cpf @@ -164,10 +170,11 @@ def insert_pix(nome_completo: str, cpf: str) -> str: print(database) - return "OK" + return ("OK", id_value) def insert_ticket(nome_completo: str, cpf: str) -> str: + """Validate and insert or not a ticket. Input: the ticket information pass by the service layer. @@ -180,29 +187,32 @@ def insert_ticket(nome_completo: str, cpf: str) -> str: result = validate_CPF(cpf) if not result: - return "INVALID_CPF" + return ("INVALID_CPF", None) if cpf not in database: database[cpf] = [] - for key in database: - for val in database[key]: - if val["tipo"] == "boleto": - return "ALREADY_EXIST" + for val in database[cpf]: + if val["tipo"] == "boleto": + return ("ALREADY_EXIST", None) + + id_value = str(abs(hash((datetime.date.today(), cpf)))) - pix = { - "id" : abs(hash((datetime.datetime.now(), cpf))), + boleto = { + "id" : id_value, "tipo": "boleto", "nome_completo": nome_completo, "cpf": cpf } - database[cpf].append(pix) + database[cpf].append(boleto) write_file(database) - return "OK" + return ("OK", id_value) + +def update_card(id: str, nome_cartao: str, numero_cartao: str, cvv: str, validade: datetime.date): -def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validade: datetime.date): + database = read_file() """Update the nome_cartao, numero_cartao, cvv and validade fields. @@ -245,18 +255,22 @@ def update_card(id: int, nome_cartao: str, numero_cartao: str, cvv: str, validad return (False, problems) -def update_pix_or_ticket(id: int, nome_completo: str) -> bool: +def update_pix_or_ticket(id: str, nome_completo: str) -> bool: + + - for key in database: - for val in database[key]: - if val["id"] == id: - val["nome_completo"] = nome_completo - write_file(database) - return True + for key in database: + for val in database[key]: + if val["id"] == id: + val["nome_completo"] = nome_completo + write_file(database) + return True return False -def delete_method(id: int) -> bool: +def delete_method(id: str) -> bool: + + for key in database: for val in database[key]: @@ -267,6 +281,9 @@ def delete_method(id: int) -> bool: del database[key][index] + if len(database[key]) == 0: + del database[key] + write_file(database) return True @@ -283,4 +300,4 @@ def get_by_number(numero_cartao: str): return val - return None + return None \ No newline at end of file diff --git a/backend/src/service/impl/item_service.py b/backend/src/service/impl/item_service.py index 762ea8bf..5f571947 100644 --- a/backend/src/service/impl/item_service.py +++ b/backend/src/service/impl/item_service.py @@ -1,38 +1,38 @@ -from src.schemas.response import HTTPResponses, HttpResponseModel -from src.service.meta.item_service_meta import ItemServiceMeta -from src.db.__init__ import database as db +# # from src.schemas.response import HTTPResponses, HttpResponseModel +# # from src.service.meta.item_service_meta import ItemServiceMeta +# # from src.db.__init__ import database as db -class ItemService(ItemServiceMeta): +# class ItemService(ItemServiceMeta): - @staticmethod - def get_item(item_id: str) -> HttpResponseModel: - """Get item by id method implementation""" - item = db.get_item_by_id('items', item_id) - if not item: - return HttpResponseModel( - message=HTTPResponses.ITEM_NOT_FOUND().message, - status_code=HTTPResponses.ITEM_NOT_FOUND().status_code, - ) - return HttpResponseModel( - message=HTTPResponses.ITEM_FOUND().message, - status_code=HTTPResponses.ITEM_FOUND().status_code, - data=item, - ) +# @staticmethod +# def get_item(item_id: str) -> HttpResponseModel: +# """Get item by id method implementation""" +# item = db.get_item_by_id('items', item_id) +# if not item: +# return HttpResponseModel( +# message=HTTPResponses.ITEM_NOT_FOUND().message, +# status_code=HTTPResponses.ITEM_NOT_FOUND().status_code, +# ) +# return HttpResponseModel( +# message=HTTPResponses.ITEM_FOUND().message, +# status_code=HTTPResponses.ITEM_FOUND().status_code, +# data=item, +# ) - @staticmethod - def get_items(): - """Get items method implementation""" - items = db.get_all_items('items') - if not items: - return HttpResponseModel( - message=HTTPResponses.ITEM_NOT_FOUND().message, - status_code=HTTPResponses.ITEM_NOT_FOUND().status_code, - ) +# @staticmethod +# def get_items(): +# """Get items method implementation""" +# items = db.get_all_items('items') +# if not items: +# return HttpResponseModel( +# message=HTTPResponses.ITEM_NOT_FOUND().message, +# status_code=HTTPResponses.ITEM_NOT_FOUND().status_code, +# ) - return HttpResponseModel( - message=HTTPResponses.ITEM_FOUND().message, - status_code=HTTPResponses.ITEM_FOUND().status_code, - data=items, - ) +# return HttpResponseModel( +# message=HTTPResponses.ITEM_FOUND().message, +# status_code=HTTPResponses.ITEM_FOUND().status_code, +# data=items, +# ) - # TODO: implement other methods (create, update, delete) \ No newline at end of file +# # TODO: implement other methods (create, update, delete) \ No newline at end of file diff --git a/backend/src/service/impl/payment_method_service.py b/backend/src/service/impl/payment_method_service.py index 69084811..cf002c41 100644 --- a/backend/src/service/impl/payment_method_service.py +++ b/backend/src/service/impl/payment_method_service.py @@ -11,33 +11,33 @@ def inserting_card(cartao: Cartao) -> HttpResponseModel: sucess, problems = insert_card(*cartao.model_dump().values()) if sucess: - return HTTPPaymentResponse.INSERTION_SUCESSFULLY() + return HTTPPaymentResponse.INSERTION_SUCESSFULLY(problems) else: return HTTPPaymentResponse.BAD_REQUEST(problems) @staticmethod def insertion_pix(pix: Pix) -> HttpResponseModel: - result = insert_pix(*pix.model_dump().values()) + result, id = insert_pix(*pix.model_dump().values()) if result == "CPF": return HTTPPaymentResponse.BAD_REQUEST(["CPF"]) elif result == "ALREADY_EXIST": return HTTPPaymentResponse.PIX_ALREADY_EXIST() - return HTTPPaymentResponse.INSERTION_SUCESSFULLY() + return HTTPPaymentResponse.INSERTION_SUCESSFULLY(id) @staticmethod def insertion_ticket(boleto: Boleto) -> HttpResponseModel: - result = insert_ticket(*boleto.model_dump().values()) + result, id = insert_ticket(*boleto.model_dump().values()) if result == "CPF": return HTTPPaymentResponse.BAD_REQUEST(["CPF"]) elif result == "ALREADY_EXIST": return HTTPPaymentResponse.BOLETO_ALREADY_EXIST() - return HTTPPaymentResponse.INSERTION_SUCESSFULLY() + return HTTPPaymentResponse.INSERTION_SUCESSFULLY(id) # @staticmethod # def get_payment_methods(cpf: str): diff --git a/backend/src/tests/api/step_definitions/test_items.py b/backend/src/tests/api/step_definitions/test_items.py index d10d720a..c345d13e 100644 --- a/backend/src/tests/api/step_definitions/test_items.py +++ b/backend/src/tests/api/step_definitions/test_items.py @@ -1,110 +1,110 @@ -from src.schemas.response import HTTPResponses, HttpResponseModel -from pytest_bdd import parsers, given, when, then, scenario -from src.service.impl.item_service import ItemService -from src.tests.api.utils.utils import get_response_items_list, req_type_to_function - -""" Scenario: Obter item por ID """ -# This method is used to define the scenario name and feature file path -@scenario(scenario_name="Obter item por ID", feature_name="../features/items.feature") -def test_get_item(): - """ Get item by id """ - -# Step definitions for the "Obter item por ID" scenario -@given(parsers.cfparse('o ItemService retorna um item com id "{item_id}" e nome "{item_name}"')) -def mock_item_service_response(item_id: str, item_name: str): - """ - Mock the ItemService.get_item() method to return an item with the given id and name - """ - - ItemService.get_item = lambda id : HttpResponseModel( - message=HTTPResponses.ITEM_FOUND().message, - status_code=HTTPResponses.ITEM_FOUND().status_code, - data={"id": item_id, "name": item_name} - ) - -@when( - parsers.cfparse('uma requisição "{req_type}" for enviada para "{req_url}"'), - target_fixture="context" -) -def send_get_item_request(client, context, req_type: str, req_url: str): - """ - Send a request to the given URL using the given request type - """ - - response = req_type_to_function(client, req_type)(req_url) - context["response"] = response - return context - -@then(parsers.cfparse('o status da resposta deve ser "{status_code}"'), target_fixture="context") -def check_response_status_code(context, status_code: str): - """ - Check if the response status code is the expected - """ - - assert context["response"].status_code == int(status_code) - return context - -@then( - parsers.cfparse('o JSON da resposta deve conter id "{item_id}" e nome "{item_name}"'), - target_fixture="context" -) -def check_response_json_contains_item_data(context, item_id: str, item_name: str): - """ - Check if the response JSON contains the item id and name - """ - - expected_data = { "id": item_id, "name": item_name } - assert context["response"].json()["data"] == expected_data - return context - - -""" Scenario: Obter todos os itens """ - -@scenario(scenario_name="Obter todos os itens", feature_name="../features/items.feature") -def test_get_items(): - """ Get all items """ - -# Step definitions for the "Obter todos os itens" scenario -@given(parsers.cfparse('o ItemService retorna uma lista de itens')) -def mock_item_service_response_list(): - """ - Mock the ItemService.get_items() method to return a list of items - """ - ItemService.get_items = lambda: HttpResponseModel( - message=HTTPResponses.ITEM_FOUND().message, - status_code=HTTPResponses.ITEM_FOUND().status_code, - data={ - 'items': [ - {"id": "123", "name": "Exemplo de Item"}, - {"id": "456", "name": "Outro Item"} - ] - } - ) - -@then(parsers.cfparse('o item com id "{item_id}" e nome "{item_name}" está na lista'), target_fixture="context") -@given(parsers.cfparse('o item com id "{item_id}" e nome "{item_name}" está na lista'), target_fixture="context") -def check_item_is_in_list(context, item_id: str, item_name: str): - """ - Check if the item with the given id and name is in the response list - """ - items = get_response_items_list(context["response"]) - - assert {"id": item_id, "name": item_name} in items - - return context - -@then(parsers.cfparse('o JSON da resposta deve ser uma lista de itens'), target_fixture="context") -def check_response_json_is_an_item_list(context): - """ - Check if the response JSON is a list of items - """ - - items = get_response_items_list(context["response"]) - - assert isinstance(items, list) - for item in items: - assert isinstance(item, dict) - assert "name" in item and isinstance(item["name"], str) - assert "id" in item and isinstance(item["id"], str) - - return context \ No newline at end of file +# from src.schemas.response import HTTPResponses, HttpResponseModel +# from pytest_bdd import parsers, given, when, then, scenario +# from src.service.impl.item_service import ItemService +# from src.tests.api.utils.utils import get_response_items_list, req_type_to_function + +# """ Scenario: Obter item por ID """ +# # This method is used to define the scenario name and feature file path +# @scenario(scenario_name="Obter item por ID", feature_name="../features/items.feature") +# def test_get_item(): +# """ Get item by id """ + +# # Step definitions for the "Obter item por ID" scenario +# @given(parsers.cfparse('o ItemService retorna um item com id "{item_id}" e nome "{item_name}"')) +# def mock_item_service_response(item_id: str, item_name: str): +# """ +# Mock the ItemService.get_item() method to return an item with the given id and name +# """ + +# ItemService.get_item = lambda id : HttpResponseModel( +# message=HTTPResponses.ITEM_FOUND().message, +# status_code=HTTPResponses.ITEM_FOUND().status_code, +# data={"id": item_id, "name": item_name} +# ) + +# @when( +# parsers.cfparse('uma requisição "{req_type}" for enviada para "{req_url}"'), +# target_fixture="context" +# ) +# def send_get_item_request(client, context, req_type: str, req_url: str): +# """ +# Send a request to the given URL using the given request type +# """ + +# response = req_type_to_function(client, req_type)(req_url) +# context["response"] = response +# return context + +# @then(parsers.cfparse('o status da resposta deve ser "{status_code}"'), target_fixture="context") +# def check_response_status_code(context, status_code: str): +# """ +# Check if the response status code is the expected +# """ + +# assert context["response"].status_code == int(status_code) +# return context + +# @then( +# parsers.cfparse('o JSON da resposta deve conter id "{item_id}" e nome "{item_name}"'), +# target_fixture="context" +# ) +# def check_response_json_contains_item_data(context, item_id: str, item_name: str): +# """ +# Check if the response JSON contains the item id and name +# """ + +# expected_data = { "id": item_id, "name": item_name } +# assert context["response"].json()["data"] == expected_data +# return context + + +# """ Scenario: Obter todos os itens """ + +# @scenario(scenario_name="Obter todos os itens", feature_name="../features/items.feature") +# def test_get_items(): +# """ Get all items """ + +# # Step definitions for the "Obter todos os itens" scenario +# @given(parsers.cfparse('o ItemService retorna uma lista de itens')) +# def mock_item_service_response_list(): +# """ +# Mock the ItemService.get_items() method to return a list of items +# """ +# ItemService.get_items = lambda: HttpResponseModel( +# message=HTTPResponses.ITEM_FOUND().message, +# status_code=HTTPResponses.ITEM_FOUND().status_code, +# data={ +# 'items': [ +# {"id": "123", "name": "Exemplo de Item"}, +# {"id": "456", "name": "Outro Item"} +# ] +# } +# ) + +# @then(parsers.cfparse('o item com id "{item_id}" e nome "{item_name}" está na lista'), target_fixture="context") +# @given(parsers.cfparse('o item com id "{item_id}" e nome "{item_name}" está na lista'), target_fixture="context") +# def check_item_is_in_list(context, item_id: str, item_name: str): +# """ +# Check if the item with the given id and name is in the response list +# """ +# items = get_response_items_list(context["response"]) + +# assert {"id": item_id, "name": item_name} in items + +# return context + +# @then(parsers.cfparse('o JSON da resposta deve ser uma lista de itens'), target_fixture="context") +# def check_response_json_is_an_item_list(context): +# """ +# Check if the response JSON is a list of items +# """ + +# items = get_response_items_list(context["response"]) + +# assert isinstance(items, list) +# for item in items: +# assert isinstance(item, dict) +# assert "name" in item and isinstance(item["name"], str) +# assert "id" in item and isinstance(item["id"], str) + +# return context \ No newline at end of file diff --git a/backend/src/tests/service/features/items-service.feature b/backend/src/tests/service/features/items-service.feature index 50735a2f..aaaa9236 100644 --- a/backend/src/tests/service/features/items-service.feature +++ b/backend/src/tests/service/features/items-service.feature @@ -1,12 +1,12 @@ -Feature: Items Service +# Feature: Items Service -# Service -Scenario: Obter todos os itens - Given o método getItems do ItemService retorna um array com o item de nome "item" e id "123" - When o método getItems do ItemService for chamado - Then o array retornado deve conter o item de nome "item" e id "123" +# # Service +# Scenario: Obter todos os itens +# Given o método getItems do ItemService retorna um array com o item de nome "item" e id "123" +# When o método getItems do ItemService for chamado +# Then o array retornado deve conter o item de nome "item" e id "123" -Scenario: Obter item por ID - Given o método getItem do ItemService retorna um item de nome "item" e id "123" - When o método getItem do ItemService for chamado com o id "123" - Then o item retornado deve ter o nome "item" e id "123" \ No newline at end of file +# Scenario: Obter item por ID +# Given o método getItem do ItemService retorna um item de nome "item" e id "123" +# When o método getItem do ItemService for chamado com o id "123" +# Then o item retornado deve ter o nome "item" e id "123" \ No newline at end of file diff --git a/backend/src/tests/service/features/payment_methods-service.feature b/backend/src/tests/service/features/payment_methods-service.feature new file mode 100644 index 00000000..68a20b08 --- /dev/null +++ b/backend/src/tests/service/features/payment_methods-service.feature @@ -0,0 +1,26 @@ +Feature: Payment Methods Service + +#Service +Scenario: Inserir cartão + # Given o cartao de nome "masterCard", número "4916123456789012", cvv "847", cpf "111.111.11-11" e validade "2024-02-17" não existe no banco de dados + Given o método inserting_card do PaymentMethodService retorna um json com message "método cadastrado com sucesso" e status_code = "201" + And o cartao "cartao" nao existe no banco de dados + When o método inserting_card do PaymentMethodService for chamado com cartao "cartao" + Then o cartao "cartao" for criado com sucesso + + +Scenario: Inserir cartão com cpf inválido + Given o cartao de nome "masterCard", número "4916123456789012", cvv "847", cpf "111.111.11" e validade "2024-02-17" não existe no banco de dados + When o método insert_card do PaymentDatabase for chamado com nome "masterCard", número "4916123456789012", cvv "847", cpf "111.111.111" e validade "2024-02-17" + Then o método insert_card do PaymentDatabase retorna sucess "True" e problemas = "[CPF]" + +Scenario: Inserir pix + Given o pix de nome "Breno Gabriel de Melo Lima" e cpf "222.222.222-22" não existe no banco de dados + When o método insert_pix do PaymentDatabase for chamado com nome "Breno Gabriel de Melo Lima" e cpf "222.222.222-22" + Then o pix de nome "Breno Gabriel de Melo Lima" e cpf "222.222.222-22" foi criado com sucesso + And o método insert_pix do PaymentDatabase retorna sucess "True" + +Scenario: Inserir pix com cpf incorreto + Given o pix de nome "Breno Gabriel de Melo Lima" e cpf "222.222.222" não existe no banco de dados + When o método insert_pix do PaymentDatabase for chamado com nome "Breno Gabriel de Melo Lima" e cpf "222.222.222" + Then o método insert_pix do PaymentDatabase retorna sucess "False" diff --git a/backend/src/tests/service/step_definitions/test_items_service.py b/backend/src/tests/service/step_definitions/test_items_service.py index 262c7723..71466055 100644 --- a/backend/src/tests/service/step_definitions/test_items_service.py +++ b/backend/src/tests/service/step_definitions/test_items_service.py @@ -1,81 +1,81 @@ -from src.schemas.response import HTTPResponses, HttpResponseModel -from pytest_bdd import parsers, given, when, then, scenario -from src.service.impl.item_service import ItemService +# from src.schemas.response import HTTPResponses, HttpResponseModel +# from pytest_bdd import parsers, given, when, then, scenario +# from src.service.impl.item_service import ItemService -""" Scenario: Obter item por ID """ -# This method is used to define the scenario name and feature file path -@scenario(scenario_name="Obter item por ID", feature_name="../features/items-service.feature") -def test_service_get_item(): - """ Get item by id """ +# """ Scenario: Obter item por ID """ +# # This method is used to define the scenario name and feature file path +# @scenario(scenario_name="Obter item por ID", feature_name="../features/items-service.feature") +# def test_service_get_item(): +# """ Get item by id """ -# Step definitions for the "Obter item por ID" scenario -@given(parsers.cfparse( - 'o método getItem do ItemService retorna um item de nome "{item_name}" e id "{item_id}"')) -def mock_item_service(item_id: str, item_name: str): - """ - Mock the ItemService.get_item() method to return an item with the given id and name - """ +# # Step definitions for the "Obter item por ID" scenario +# @given(parsers.cfparse( +# 'o método getItem do ItemService retorna um item de nome "{item_name}" e id "{item_id}"')) +# def mock_item_service(item_id: str, item_name: str): +# """ +# Mock the ItemService.get_item() method to return an item with the given id and name +# """ - ItemService.get_item = lambda id : HttpResponseModel( - message=HTTPResponses.ITEM_FOUND().message, - status_code=HTTPResponses.ITEM_FOUND().status_code, - data={"id": item_id, "name": item_name} - ) +# ItemService.get_item = lambda id : HttpResponseModel( +# message=HTTPResponses.ITEM_FOUND().message, +# status_code=HTTPResponses.ITEM_FOUND().status_code, +# data={"id": item_id, "name": item_name} +# ) -@when( - parsers.cfparse('o método getItem do ItemService for chamado com o id "{item_id}"'), - target_fixture="context" -) -def get_item(context, item_id: str): - context['item'] = ItemService.get_item(item_id) - return context +# @when( +# parsers.cfparse('o método getItem do ItemService for chamado com o id "{item_id}"'), +# target_fixture="context" +# ) +# def get_item(context, item_id: str): +# context['item'] = ItemService.get_item(item_id) +# return context -@then( - parsers.cfparse('o item retornado deve ter o nome "{item_name}" e id "{item_id}"'), - target_fixture="context" -) -def check_received_item(context, item_name: str, item_id: str): - assert context['item'].data.name == item_name - assert context['item'].data.id == item_id +# @then( +# parsers.cfparse('o item retornado deve ter o nome "{item_name}" e id "{item_id}"'), +# target_fixture="context" +# ) +# def check_received_item(context, item_name: str, item_id: str): +# assert context['item'].data.name == item_name +# assert context['item'].data.id == item_id - return context +# return context -""" Scenario: Obter todos os itens """ +# """ Scenario: Obter todos os itens """ -@scenario(scenario_name="Obter todos os itens", feature_name="../features/items-service.feature") -def test_service_get_items(): - """ Get all items """ +# @scenario(scenario_name="Obter todos os itens", feature_name="../features/items-service.feature") +# def test_service_get_items(): +# """ Get all items """ -# Step definitions for the "Obter todos os itens" scenario -@given(parsers.cfparse( - 'o método getItems do ItemService retorna um array com o item de nome "{item_name}" e id "{item_id}"')) -def mock_item_service_list(item_name: str, item_id: str): +# # Step definitions for the "Obter todos os itens" scenario +# @given(parsers.cfparse( +# 'o método getItems do ItemService retorna um array com o item de nome "{item_name}" e id "{item_id}"')) +# def mock_item_service_list(item_name: str, item_id: str): - ItemService.get_items = lambda: HttpResponseModel( - message=HTTPResponses.ITEM_FOUND().message, - status_code=HTTPResponses.ITEM_FOUND().status_code, - data={ - 'items': [{"id": item_id, "name": item_name}] - } - ) +# ItemService.get_items = lambda: HttpResponseModel( +# message=HTTPResponses.ITEM_FOUND().message, +# status_code=HTTPResponses.ITEM_FOUND().status_code, +# data={ +# 'items': [{"id": item_id, "name": item_name}] +# } +# ) -@when( - parsers.cfparse('o método getItems do ItemService for chamado'), - target_fixture="context" -) -def get_service_items(context): - context['items'] = ItemService.get_items() - return context +# @when( +# parsers.cfparse('o método getItems do ItemService for chamado'), +# target_fixture="context" +# ) +# def get_service_items(context): +# context['items'] = ItemService.get_items() +# return context -@then( - parsers.cfparse('o item retornado deve ter o nome "{item_name}" e id "{item_id}"'), - target_fixture="context" -) -def check_service_list(context, item_id: str, item_name: str): - """ - Check if the item with the given id and name is in the response list - """ +# @then( +# parsers.cfparse('o item retornado deve ter o nome "{item_name}" e id "{item_id}"'), +# target_fixture="context" +# ) +# def check_service_list(context, item_id: str, item_name: str): +# """ +# Check if the item with the given id and name is in the response list +# """ - assert [{"id": item_id, "name": item_name}] == context['items'].data['items'] +# assert [{"id": item_id, "name": item_name}] == context['items'].data['items'] - return context \ No newline at end of file +# return context \ No newline at end of file diff --git a/backend/src/tests/service/step_definitions/test_payment_methods_service.py b/backend/src/tests/service/step_definitions/test_payment_methods_service.py new file mode 100644 index 00000000..daf49af9 --- /dev/null +++ b/backend/src/tests/service/step_definitions/test_payment_methods_service.py @@ -0,0 +1,96 @@ + +# from pytest_bdd import parsers, given, when, then, scenario +# from src.db.payment_database import * +# from src.service.impl.payment_method_service import PaymentService +# from src.schemas.response import HttpResponseModel, HTTPResponses +# from src.schemas.payment_schema import * +# import typing +# import datetime + + +# @scenario(feature_name="../features/payment_methods-service.feature", +# scenario_name="Inserir cartão") + +# def test_payment_method_service(): +# pass + +# # @given(parsers.cfparse( +# # 'o cartao de nome {nome}, número {numero}, cvv {cvv}, cpf {cpf} e validade {validade} não existe no banco de dados' +# # )) + +# # def checar_nao_existencia(numero): + + + +# @given(parsers.cfparse( +# 'o método inserting_card do PaymentMethodService retorna um json com message {mensagem} e status_code = {status}' +# )) + +# def mock_insert_service(mensagem: str, status: int ): + +# PaymentService.inserting_card = lambda id: HttpResponseModel( +# message=mensagem, +# status_code=status +# ) + +# @when(parsers.cfparse( +# 'o método inserting_card do PaymentMethodService for chamado com cartao {cartao}' +# ), target_fixture = "context") + +# def insertion_card(context, cartao: Cartao): +# context["result"] = PaymentService.inserting_card(cartao) +# print(context) +# return context + +# @then(parsers.cfparse( +# 'o método inserting_card do PaymentMethodService retorna um json com message "método cadastrado com sucesso" e status_code = "201"', +# ), target_fixture = "context") +# def check_response(context, sucesso_esperado: bool, problemas_esperados: List[str]): + +# sucesso_retornado, problemas_retornados = context["result"] + +# sucesso_retornado = str(sucesso_retornado) +# problemas_esperados = str(problemas_esperados) + +# assert bool(sucesso_retornado) == bool(sucesso_esperado) +# assert problemas_retornados == json.loads(problemas_esperados.replace("'", '"')) + +# return context + +from src.main import app +from unittest.mock import MagicMock +from unittest.mock import patch +from fastapi.testclient import TestClient +from src.db import database as db +from datetime import datetime, timezone +from unittest.mock import patch, MagicMock +from src.service.impl.payment_method_service import PaymentService +from src.schemas.payment_schema import * + +def test_add_card(client: TestClient): + + mock_json = { + "message": "metodo de pagamento cadastrado com sucesso", + "status_code": 201, + "data": None + } + + body = { + "nome_cartao": "MasterCard", + "numero_cartao": "6011234567890123", + "cvv": "456", + "cpf": "111.111.111-11", + "validade": "2024-02-18" + } + + PaymentService.inserting_card = MagicMock(return_value = mock_json) + + response = client.post("/backend/src/api/payment/inserting/cartao", json=body) + + assert response.status_code == 201 + assert response.json() == { + "message": "metodo de pagamento cadastrado com sucesso", + "status_code": 201, + "data": None + } + From d65e90b53df67cf004d65d345d9cdd9d935be4ad Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:30:44 -0300 Subject: [PATCH 55/62] Delete .idea/.gitignore --- .idea/.gitignore | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b81..00000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml From 7f621cd3bd3b9af7e31514860f4261826a36c473 Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:30:57 -0300 Subject: [PATCH 56/62] Delete .idea/Projeto-ESS2.iml --- .idea/Projeto-ESS2.iml | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 .idea/Projeto-ESS2.iml diff --git a/.idea/Projeto-ESS2.iml b/.idea/Projeto-ESS2.iml deleted file mode 100644 index 8b8c3954..00000000 --- a/.idea/Projeto-ESS2.iml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file From 3b27c4a2714991a8c75abb7782779746e1721a03 Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:31:07 -0300 Subject: [PATCH 57/62] Delete .idea/inspectionProfiles/profiles_settings.xml --- .idea/inspectionProfiles/profiles_settings.xml | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 .idea/inspectionProfiles/profiles_settings.xml diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2da..00000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file From 2d9a374a61f74304f8a8b93eeb1c6853ef397737 Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:31:18 -0300 Subject: [PATCH 58/62] Delete .idea/misc.xml --- .idea/misc.xml | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 .idea/misc.xml diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index a971a2c9..00000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file From 5364dfe558ea255818c0eb09b53984c3fcb3de65 Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:31:27 -0300 Subject: [PATCH 59/62] Delete .idea/modules.xml --- .idea/modules.xml | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .idea/modules.xml diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 3f42b946..00000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file From 8529625868320196bd6eb47e203e5c607d05735c Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:31:38 -0300 Subject: [PATCH 60/62] Delete .idea/vcs.xml --- .idea/vcs.xml | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 .idea/vcs.xml diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1ddf..00000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 78ed9938b75a46284bdda462f6972a3149fc37a9 Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:32:13 -0300 Subject: [PATCH 61/62] =?UTF-8?q?Delete=20backend/Usu=C3=A1rios=20teste.js?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "backend/Usu\303\241rios teste.json" | 1 - 1 file changed, 1 deletion(-) delete mode 100644 "backend/Usu\303\241rios teste.json" diff --git "a/backend/Usu\303\241rios teste.json" "b/backend/Usu\303\241rios teste.json" deleted file mode 100644 index 9e26dfee..00000000 --- "a/backend/Usu\303\241rios teste.json" +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file From ac3531bb14f43b0f799470350744264838813873 Mon Sep 17 00:00:00 2001 From: Diego <108680465+Diego-djaar@users.noreply.github.com> Date: Mon, 19 Feb 2024 00:32:22 -0300 Subject: [PATCH 62/62] =?UTF-8?q?Delete=20backend/Usu=C3=A1rios.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "backend/Usu\303\241rios.json" | 1 - 1 file changed, 1 deletion(-) delete mode 100644 "backend/Usu\303\241rios.json" diff --git "a/backend/Usu\303\241rios.json" "b/backend/Usu\303\241rios.json" deleted file mode 100644 index 9e26dfee..00000000 --- "a/backend/Usu\303\241rios.json" +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file