From 737bc7d9369c56ad64cd89cb4252d27c017605c9 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 01:27:30 -0300
Subject: [PATCH 01/13] Update CI workflow to use JDK 21 and develop branch
---
.github/workflows/ci-develop.yml | 33 ++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
create mode 100644 .github/workflows/ci-develop.yml
diff --git a/.github/workflows/ci-develop.yml b/.github/workflows/ci-develop.yml
new file mode 100644
index 0000000..3fbfeb4
--- /dev/null
+++ b/.github/workflows/ci-develop.yml
@@ -0,0 +1,33 @@
+# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
+# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
+
+# This workflow uses actions that are not certified by GitHub.
+# They are provided by a third-party and are governed by
+# separate terms of service, privacy policy, and support
+# documentation.
+
+name: CI Develop
+
+on:
+ push:
+ branches: [ "develop" ]
+ pull_request:
+ branches: [ "develop" ]
+
+jobs:
+ build:
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Set up JDK 21
+ uses: actions/setup-java@v4
+ with:
+ java-version: '21'
+ distribution: 'temurin'
+ cache: maven
+ - name: Run Maven verify (tests + Spotless + SpotBugs)
+ run: mvn -B clean verifyl
From 5e97d220268c9ea9e6fb5ef58c578ac5e97c545c Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 02:42:52 -0300
Subject: [PATCH 02/13] Add CD workflow for main branch with Docker build
---
.github/workflows/cd-main.yml | 37 +++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
create mode 100644 .github/workflows/cd-main.yml
diff --git a/.github/workflows/cd-main.yml b/.github/workflows/cd-main.yml
new file mode 100644
index 0000000..30dcacd
--- /dev/null
+++ b/.github/workflows/cd-main.yml
@@ -0,0 +1,37 @@
+name: CD main (Prod)
+
+on:
+ push:
+ branches: [ "main" ]
+ pull_request:
+ branches: [ "main" ]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Set up JDK 21
+ uses: actions/setup-java@v4
+ with:
+ java-version: '21'
+ distribution: 'temurin'
+ cache: maven
+
+ - name: Run Maven verify (tests + Spotless + SpotBugs)
+ run: mvn -B clean verify
+
+ docker:
+ runs-on: ubuntu-latest
+ needs: build
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Build Docker image
+ run: docker build -t vemprofut-api:latest .
+
+
From 4bf034a5da9b1b57309353b7563cb80ea327b891 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 03:04:22 -0300
Subject: [PATCH 03/13] Rename cd-main.yml to cicd-main.yml
adicionei as secrets
---
.github/workflows/{cd-main.yml => cicd-main.yml} | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)
rename .github/workflows/{cd-main.yml => cicd-main.yml} (61%)
diff --git a/.github/workflows/cd-main.yml b/.github/workflows/cicd-main.yml
similarity index 61%
rename from .github/workflows/cd-main.yml
rename to .github/workflows/cicd-main.yml
index 30dcacd..e76da07 100644
--- a/.github/workflows/cd-main.yml
+++ b/.github/workflows/cicd-main.yml
@@ -1,4 +1,4 @@
-name: CD main (Prod)
+name: CI/CD Main (Prod)
on:
push:
@@ -31,7 +31,16 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
+ - name: Log in to Docker Hub
+ run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin
+
- name: Build Docker image
run: docker build -t vemprofut-api:latest .
-
+ - name: Tag Docker image
+ run: docker tag vemprofut-api:latest ${{ secrets.DOCKER_USERNAME }}/vemprofut-api:latest
+
+ - name: Push Docker image
+ run: docker push ${{ secrets.DOCKER_USERNAME }}/vemprofut-api:latest
+
+
From 69738fe112714fbc3cbb7a278edacf9a99164538 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 03:17:22 -0300
Subject: [PATCH 04/13] Specify working directory for Maven verify
Set working directory for Maven verify step.
---
.github/workflows/cicd-main.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/workflows/cicd-main.yml b/.github/workflows/cicd-main.yml
index e76da07..bb8800a 100644
--- a/.github/workflows/cicd-main.yml
+++ b/.github/workflows/cicd-main.yml
@@ -23,6 +23,7 @@ jobs:
- name: Run Maven verify (tests + Spotless + SpotBugs)
run: mvn -B clean verify
+ working-directory: ./VemProFutApi
docker:
runs-on: ubuntu-latest
From dc5851f817d78809717fa2f7fe7b9a8ac6898c29 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 21:59:16 -0300
Subject: [PATCH 05/13] Change Docker build context to VemProFutApi directory
(#7)
---
.github/workflows/cicd-main.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/cicd-main.yml b/.github/workflows/cicd-main.yml
index bb8800a..ad14fa4 100644
--- a/.github/workflows/cicd-main.yml
+++ b/.github/workflows/cicd-main.yml
@@ -36,7 +36,7 @@ jobs:
run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin
- name: Build Docker image
- run: docker build -t vemprofut-api:latest .
+ run: docker build -t vemprofut-api:latest ./VemProFutApi
- name: Tag Docker image
run: docker tag vemprofut-api:latest ${{ secrets.DOCKER_USERNAME }}/vemprofut-api:latest
From e8d0f28e4b9bbc95c3c86886ee54925a1cd6be6f Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 23:31:37 -0300
Subject: [PATCH 06/13] Fix Maven command to run Spotless and verify
---
.github/workflows/ci-develop.yml | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/ci-develop.yml b/.github/workflows/ci-develop.yml
index 3fbfeb4..f2ef092 100644
--- a/.github/workflows/ci-develop.yml
+++ b/.github/workflows/ci-develop.yml
@@ -30,4 +30,5 @@ jobs:
distribution: 'temurin'
cache: maven
- name: Run Maven verify (tests + Spotless + SpotBugs)
- run: mvn -B clean verifyl
+ run: mvn spotless:apply && mvn -B clean verify
+ working-directory: ./VemProFutApi
From 41ce06b138091ed2f889aea50dcf826b6a4558ef Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 23:33:07 -0300
Subject: [PATCH 07/13] Update CI workflow to apply Spotless before verify
---
.github/workflows/cicd-main.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/cicd-main.yml b/.github/workflows/cicd-main.yml
index ad14fa4..2d79829 100644
--- a/.github/workflows/cicd-main.yml
+++ b/.github/workflows/cicd-main.yml
@@ -22,7 +22,7 @@ jobs:
cache: maven
- name: Run Maven verify (tests + Spotless + SpotBugs)
- run: mvn -B clean verify
+ run: mvn spotless:apply && mvn -B clean verify
working-directory: ./VemProFutApi
docker:
From b1b028ba30dbce5ee1231b81cf04e63eaeea02f4 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Sat, 13 Dec 2025 23:43:11 -0300
Subject: [PATCH 08/13] Develop merge (#11)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* Feature/implement test repository (#5)
* test(BaseIntegrationTest): Criando a Base para testes usando conteiner Mysql para ser o mais semelhante possivel com o de producao
* feat(Dockenizando): Dockerzinado a aplicacao para está preparada para subir para prod
* feat(BaseIntegrationTest): Iniciando a implementacao dos testes usando o testconteiner com mysql
* fix(testconteiner/docker): resolvendo erro de comunicacao do testconteine com o docker
* feat(RepositoryTest):Refactorando o banco de dados de Testconteiner para H2 em memoria e criando os testes de Peladeiro, Fut,Banimento e Cartoes repositories
* test(organizando diretorios de pastas): Separando os testes unitarios dos testes de intregracao e etc
* test(organizando diretorios):
alterei os nomes dos testes de integracao para o final IT;
configurei o spotbugs para verificar os codigos antes de enviar o PR;
add arquivo de filtro do spotbugs;
* refactor:(mapeando DTOS):
-Mapeando os atributos dos DTOs para os models;
-Ignorando os atributos de models que nao vao ser usados nos DTOs;
-alterei os nomes dos atributos nos DTOs para ficarem iguais ao da classe model para facilitaro mapeamento;
-refatorei os locais onde usava o nome antigo dos atributos dos DTOs para o nome novo;
* Feature/implement test repository (#10)
* test(BaseIntegrationTest): Criando a Base para testes usando conteiner Mysql para ser o mais semelhante possivel com o de producao
* feat(Dockenizando): Dockerzinado a aplicacao para está preparada para subir para prod
* feat(BaseIntegrationTest): Iniciando a implementacao dos testes usando o testconteiner com mysql
* fix(testconteiner/docker): resolvendo erro de comunicacao do testconteine com o docker
* feat(RepositoryTest):Refactorando o banco de dados de Testconteiner para H2 em memoria e criando os testes de Peladeiro, Fut,Banimento e Cartoes repositories
* test(organizando diretorios de pastas): Separando os testes unitarios dos testes de intregracao e etc
* test(organizando diretorios):
alterei os nomes dos testes de integracao para o final IT;
configurei o spotbugs para verificar os codigos antes de enviar o PR;
add arquivo de filtro do spotbugs;
* refactor:(mapeando DTOS):
-Mapeando os atributos dos DTOs para os models;
-Ignorando os atributos de models que nao vao ser usados nos DTOs;
-alterei os nomes dos atributos nos DTOs para ficarem iguais ao da classe model para facilitaro mapeamento;
-refatorei os locais onde usava o nome antigo dos atributos dos DTOs para o nome novo;
---
VemProFutApi/Docker-compose.yml | 52 ++-
VemProFutApi/Dockerfile | 8 +-
VemProFutApi/excludeFilter.xml | 35 ++
VemProFutApi/mysql-init/init.sql | 8 +
VemProFutApi/pom.xml | 41 +-
.../configs/OAuth2LoginSuccessHandler.java | 3 +-
.../vemprofut/controllers/FutController.java | 58 ++-
.../controllers/PeladeiroController.java | 20 +-
.../request/SaveFutRequestDTO.java | 2 +-
.../response/CartoesResponseDTO.java | 2 +-
.../response/SavePeladeiroResponseDTO.java | 2 +-
.../response/UpdatePeladeiroResponseDTO.java | 3 +-
.../com/vemprofut/mappers/ICartoesMapper.java | 3 +
.../br/com/vemprofut/mappers/IFutMapper.java | 10 +
.../vemprofut/mappers/IMappersDefault.java | 19 +-
.../vemprofut/mappers/IPeladeiroMapper.java | 17 +
.../com/vemprofut/models/BanimentoModel.java | 15 +-
.../br/com/vemprofut/models/CartoesModel.java | 10 +
.../models/DTOs/CartaoCountProjection.java | 1 +
.../com/vemprofut/models/DTOs/CartoesDTO.java | 3 +-
.../com/vemprofut/models/DTOs/EditorDTO.java | 2 +-
.../br/com/vemprofut/models/DTOs/FutDTO.java | 2 +-
.../br/com/vemprofut/models/EditorModel.java | 5 +
.../br/com/vemprofut/models/FutModel.java | 17 +
.../com/vemprofut/models/PeladeiroModel.java | 21 +-
.../repositories/BanimentoRepository.java | 8 +-
.../repositories/CartoesRepository.java | 8 +-
.../repositories/EditorRepository.java | 2 +-
.../services/implementacao/FutService.java | 2 +-
.../services/query/ICartoesQueryService.java | 6 -
.../implementacao/BanimentoQueryService.java | 8 +-
.../implementacao/CartoesQueryService.java | 22 +-
.../main/resources/application-dev.properties | 60 ++-
.../resources/application-prod.properties | 39 ++
.../src/main/resources/application.properties | 61 ---
..._table_partidas_contrains_fk_partidas2.sql | 4 +-
...__alter_table_gols_constraint_fk_gols2.sql | 4 +-
...__alter_table_gols_constraint_fk_gols3.sql | 4 +
...200__alter_table_gols_constraint_gols3,sql | 4 -
...articipapeladeiro_contraint_participa1.sql | 2 +-
...icipapeladeiro_contraint_fk_participa2.sql | 2 +-
...er_table_estapeladeio_constraint_esta1.sql | 2 +-
...able_estapeladeiro_constraint_fk_esta2.sql | 2 +-
...ter_table_editor_constraint_fk_editor1.sql | 2 +-
...ter_table_editor_constraint_fk_editor2.sql | 2 +-
...2511241710__alter_table_fk_banimento_2.sql | 2 +-
...2511241712__alter_table_fk_banimento_3.sql | 2 +-
.../vemprofut/VemProFutApplicationTests.java | 12 -
.../repositories/BanimentoRepositoryIT.java | 152 +++++++
.../repositories/CartoesRepositoryIT.java | 424 ++++++++++++++++++
.../repositories/EditorRepositoryIT.java | 90 ++++
.../repositories/FutRepositoryIT.java | 78 ++++
.../repositories/PeladeiroRepositoryIT.java | 147 ++++++
.../resources/application-test.properties | 12 +
54 files changed, 1325 insertions(+), 197 deletions(-)
create mode 100644 VemProFutApi/excludeFilter.xml
create mode 100644 VemProFutApi/mysql-init/init.sql
create mode 100644 VemProFutApi/src/main/resources/application-prod.properties
create mode 100644 VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_fk_gols3.sql
delete mode 100644 VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_gols3,sql
delete mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/FutRepositoryIT.java
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java
create mode 100644 VemProFutApi/src/test/resources/application-test.properties
diff --git a/VemProFutApi/Docker-compose.yml b/VemProFutApi/Docker-compose.yml
index 27b2827..8f6b081 100644
--- a/VemProFutApi/Docker-compose.yml
+++ b/VemProFutApi/Docker-compose.yml
@@ -1,32 +1,62 @@
services:
# Serviço do Banco de Dados MySQL
db:
- image: mysql:8.0
+ image: mysql:8.0.32
container_name: vemprofut-db
restart: always
ports:
- - "3306:3306"
+ - "3307:3306"
+ env_file:
+ - .env
environment:
- MYSQL_DATABASE: ${MYSQL_DATABASE}
- MYSQL_USER: ${MYSQL_USER}
- MYSQL_PASSWORD: ${MYSQL_PASSWORD}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
+ MYSQL_DATABASE: ${MYSQL_DATABASE}
volumes:
- vemprofut-db-data:/var/lib/mysql
+ - ./mysql-init:/docker-entrypoint-initdb.d # criar o usuario automaticamente dentro do container MySQL
+
+ # 👇 Healthcheck para garantir que o MySQL está pronto
+ healthcheck:
+ test: ["CMD-SHELL", "mysqladmin ping -h localhost -uroot -p$MYSQL_ROOT_PASSWORD"]
+ interval: 10s
+ timeout: 5s
+ retries: 15
+ start_period: 30s
# Serviço da API VemProFut
api:
build: .
container_name: vemprofut-api
+ env_file:
+ - .env
restart: on-failure
+ depends_on:
+ db:
+ condition: service_healthy
ports:
- "8080:8080"
- depends_on:
- - db
environment:
- SPRING_DATASOURCE_URL: ${SPRING_DATASOURCE_URL}
- SPRING_DATASOURCE_USERNAME: ${MYSQL_USER}
- SPRING_DATASOURCE_PASSWORD: ${MYSQL_PASSWORD}
+ SPRING_PROFILES_ACTIVE: prod
+
+ # Conexão com MySQL com URL do banco dentro da rede Docker
+ SPRING_DATASOURCE_USERNAME: ${SPRING_DATASOURCE_USERNAME}
+ SPRING_DATASOURCE_PASSWORD: ${MYSQL_ROOT_PASSWORD}
+ SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/${MYSQL_DATABASE}?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&connectTimeout=30000&socketTimeout=60000
+
+ # Flyway - tenta reconectar várias vezes enquanto MySQL inicializa
+ SPRING_FLYWAY_CONNECT_RETRIES: 10
+ SPRING_FLYWAY_CONNECT_RETRIES_INTERVAL: 5s
+
+ # Auth0 - Dessa forma, o Spring vai ler direto do ambiente, sem precisar de '.properties' para mapear
+ SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_AUTH0_CLIENT_ID: ${AUTH0_CLIENT_ID}
+ SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_AUTH0_CLIENT_SECRET: ${AUTH0_CLIENT_SECRET}
+ SPRING_SECURITY_OAUTH2_CLIENT_PROVIDER_AUTH0_ISSUER_URI: ${AUTH0_ISSUER}
+ SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUER_URI: ${AUTH0_ISSUER}
+
+ # Forca Spring Boot a ouvir em todas interfaces (necessario para Docker)
+ SERVER_ADDRESS: 0.0.0.0
+ SERVER_PORT: 8080
+ SERVER_SERVLET_SESSION_COOKIE_SECURE: false
volumes:
- vemprofut-db-data: # garante que os dados do banco de dados não sejam perdidos quando o contêiner do MySQL for reiniciado.
+ vemprofut-db-data: # garante que os dados do DB não sejam perdidos quando o contêiner do MySQL for reiniciado.
diff --git a/VemProFutApi/Dockerfile b/VemProFutApi/Dockerfile
index 1faa1cc..8f0609d 100644
--- a/VemProFutApi/Dockerfile
+++ b/VemProFutApi/Dockerfile
@@ -1,3 +1,4 @@
+# ===================== Builder (Maven + JDK 21) ========================
# Utilizei uma abordagem de múltiplos estágios (multi-stage build), que gera uma imagem final muito menor e mais segura.
# Estágio 1: Build da aplicação com Maven e JDK 21
FROM maven:3.9-eclipse-temurin-21 AS builder
@@ -11,11 +12,16 @@ RUN mvn dependency:go-offline
# Copia o restante do código-fonte e constrói o JAR
COPY src ./src
-RUN mvn clean install -DskipTests
+RUN mvn clean package -DskipTests
+#package mais adequado que install quando construindo imagem...
+
+# ===================== Runtime (JRE 21) ==========================
# Estágio 2: Criação da imagem final com JRE
FROM eclipse-temurin:21-jre-jammy
WORKDIR /app
+
COPY --from=builder /app/target/VemProFut-0.0.1-SNAPSHOT.jar app.jar
+
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
diff --git a/VemProFutApi/excludeFilter.xml b/VemProFutApi/excludeFilter.xml
new file mode 100644
index 0000000..64356c8
--- /dev/null
+++ b/VemProFutApi/excludeFilter.xml
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/VemProFutApi/mysql-init/init.sql b/VemProFutApi/mysql-init/init.sql
new file mode 100644
index 0000000..4f8138c
--- /dev/null
+++ b/VemProFutApi/mysql-init/init.sql
@@ -0,0 +1,8 @@
+-- Cria o usuário
+CREATE USER IF NOT EXISTS 'vpfadm'@'%' IDENTIFIED BY 'root123';
+
+-- Dá permissões no banco
+GRANT ALL PRIVILEGES ON vemprofutdb.* TO 'vpfadm'@'%';
+
+-- Atualiza permissões
+FLUSH PRIVILEGES;
\ No newline at end of file
diff --git a/VemProFutApi/pom.xml b/VemProFutApi/pom.xml
index 6399b1a..fa31b61 100644
--- a/VemProFutApi/pom.xml
+++ b/VemProFutApi/pom.xml
@@ -5,7 +5,7 @@
org.springframework.boot
spring-boot-starter-parent
- 3.5.7
+ 3.4.0
br.com.vemprofut
@@ -29,6 +29,7 @@
21
+
org.springframework.boot
@@ -46,6 +47,7 @@
com.mysql
mysql-connector-j
+ 8.0.32
runtime
@@ -83,6 +85,7 @@
org.flywaydb
flyway-core
+ 10.20.0
@@ -118,11 +121,25 @@
10.6
-
-
+
+
+
+
+
+ com.h2database
+ h2
+ test
+
+
+ junit
+ junit
+ test
+
+
@@ -180,19 +197,25 @@
-
+
- org.apache.maven.plugins
- maven-pmd-plugin
- 3.21.0
+ com.github.spotbugs
+ spotbugs-maven-plugin
+ 4.8.3.0
- true
+ Max
+ Low
+ true
+ true
+ ${project.build.directory}/spotbugs
+ ${project.basedir}/excludeFilter.xml
verify
check
+ spotbugs
@@ -200,4 +223,4 @@
-
+
\ No newline at end of file
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java b/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java
index 0047d74..1381d0d 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java
@@ -12,7 +12,6 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
@@ -25,7 +24,7 @@ public class OAuth2LoginSuccessHandler implements AuthenticationSuccessHandler {
// Agora vamos interceptar o retorno do Auth0...
private final PeladeiroRepository peladeiroRepository;
- private final OAuth2AuthorizedClientService authorizedClientService;
+ // private final OAuth2AuthorizedClientService authorizedClientService;
private final IHistoricoPeladeiroService historicoPeladeiroService;
private final IHistoricoPeladeiroMapper historicoPeladeiroMapper;
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java
index b90f325..59df0f1 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java
@@ -5,7 +5,6 @@
import br.com.vemprofut.models.FutModel;
import br.com.vemprofut.services.IFutService;
import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.util.List;
import lombok.AllArgsConstructor;
@@ -15,7 +14,6 @@
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
-
@RestController
@RequestMapping("fut/")
@AllArgsConstructor
@@ -25,7 +23,9 @@ public class FutController {
// =============== CRUD basico ==========================
@PostMapping
- @Operation(summary = "Cadastra um novo Fut", tags = {"FutController - CRUD Básico"})
+ @Operation(
+ summary = "Cadastra um novo Fut",
+ tags = {"FutController - CRUD Básico"})
public ResponseEntity create(
@Valid @RequestBody final SaveFutRequestDTO requestDTO) {
var response = futService.create(requestDTO);
@@ -33,13 +33,17 @@ public ResponseEntity create(
}
@GetMapping("{id}")
- @Operation(summary = "Busca um Fut pelo ID", tags = {"FutController - CRUD Básico"})
+ @Operation(
+ summary = "Busca um Fut pelo ID",
+ tags = {"FutController - CRUD Básico"})
public ResponseEntity findByFut(@PathVariable final Long id) {
return ResponseEntity.ok(futService.findById(id));
}
@PutMapping("{id}")
- @Operation(summary = "Altera um Fut já cadastrado, informando o id", tags = {"FutController - CRUD Básico"})
+ @Operation(
+ summary = "Altera um Fut já cadastrado, informando o id",
+ tags = {"FutController - CRUD Básico"})
public ResponseEntity update(
@PathVariable final Long id, UpdateFutRequestDTO dto) {
var obj = futService.update(id, dto);
@@ -47,7 +51,9 @@ public ResponseEntity update(
}
@DeleteMapping("{id}")
- @Operation(summary = "Apaga um Fut por meio do id, cuidado! ", tags = {"FutController - CRUD Básico"})
+ @Operation(
+ summary = "Apaga um Fut por meio do id, cuidado! ",
+ tags = {"FutController - CRUD Básico"})
public ResponseEntity delete(@PathVariable final Long id) {
futService.delete(id);
return ResponseEntity.noContent().build();
@@ -56,7 +62,9 @@ public ResponseEntity delete(@PathVariable final Long id) {
// =================== acoes partidas =======================
@PostMapping("partida")
- @Operation(summary = "Criar uma nova partida...", tags = {"FutController - Ações Partidas"})
+ @Operation(
+ summary = "Criar uma nova partida...",
+ tags = {"FutController - Ações Partidas"})
public ResponseEntity criarPartida(
@RequestBody SavePartidaRequestDTO requestDTO) {
FutModel futModel = futService.findByIdModel(requestDTO.futId());
@@ -65,7 +73,9 @@ public ResponseEntity criarPartida(
}
@PostMapping("partidaslist")
- @Operation(summary = "Cria varias partidas de uma só vez, todas com resultados preenchidos", tags = {"FutController - Ações Partidas"})
+ @Operation(
+ summary = "Cria varias partidas de uma só vez, todas com resultados preenchidos",
+ tags = {"FutController - Ações Partidas"})
public ResponseEntity> criarPartidasLista(
@RequestBody List requestDTO) {
return ResponseEntity.status(HttpStatus.CREATED).body(futService.criarPartidasList(requestDTO));
@@ -74,7 +84,9 @@ public ResponseEntity> criarPartidasLista(
// ================ lista peladeiro =====================
@PostMapping("add-peladeiro")
- @Operation(summary = "Adiciona um peladeiro a lista de peladeiros cadastrado no fut", tags = {"FutController - Lista de Peladeiros"})
+ @Operation(
+ summary = "Adiciona um peladeiro a lista de peladeiros cadastrado no fut",
+ tags = {"FutController - Lista de Peladeiros"})
public ResponseEntity adicionarPeladeiroLista(
@RequestBody AddPeladeiroInFutListRequestDTO addPeladeiroRequestDTO) {
futService.addPeladeiro(addPeladeiroRequestDTO);
@@ -82,7 +94,9 @@ public ResponseEntity adicionarPeladeiroLista(
}
@GetMapping("lista-peladeiros/{idFut}")
- @Operation(summary = "busca a lista de todos peldadeiros cadastrados no fut", tags = {"FutController - Lista de Peladeiros"})
+ @Operation(
+ summary = "busca a lista de todos peldadeiros cadastrados no fut",
+ tags = {"FutController - Lista de Peladeiros"})
public ResponseEntity> listarPeladeirosCadastrados(
@PathVariable final Long idFut) {
return ResponseEntity.ok().body(futService.listarPeladeiroCadastradosFut(idFut));
@@ -91,7 +105,9 @@ public ResponseEntity> listarPeladeirosCadastrados(
// =============== lista Editores ===========================
@PostMapping("add-editor")
- @Operation(summary = "Adiciona um Editor a lista de editores de um fut em especifico", tags = {"FutController - Lista de Editores do Fut"})
+ @Operation(
+ summary = "Adiciona um Editor a lista de editores de um fut em especifico",
+ tags = {"FutController - Lista de Editores do Fut"})
public ResponseEntity adicionarEditorLista(
@RequestBody AddEditorInFutListResquestDTO editor) {
futService.addEditor(editor);
@@ -99,7 +115,9 @@ public ResponseEntity adicionarEditorLista(
}
@GetMapping("lista-editores/{idFut}")
- @Operation(summary = "busca a lista de editores de um fut em especifico", tags = {"FutController - Lista de Editores do Fut"})
+ @Operation(
+ summary = "busca a lista de editores de um fut em especifico",
+ tags = {"FutController - Lista de Editores do Fut"})
public ResponseEntity> listarEditoresFut(
@PathVariable final Long idFut) {
@@ -109,7 +127,9 @@ public ResponseEntity> listarEditoresFut(
// ================= upload arquivos fotos ==================
@PostMapping(value = "uploadFoto/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- @Operation(summary = "Para enviar a foto de capa do Fut", tags = {"FutController - Upload de Imagens"})
+ @Operation(
+ summary = "Para enviar a foto de capa do Fut",
+ tags = {"FutController - Upload de Imagens"})
public ResponseEntity uploadFotoFut(
@PathVariable Long id, @RequestPart("file") MultipartFile file) {
futService.atualizarFotoCapa(id, file);
@@ -119,21 +139,27 @@ public ResponseEntity uploadFotoFut(
// ======================== Banimentos =======================
@PostMapping(value = "addBanimento")
- @Operation(summary = "Adicionando um peladeiro da lista para o banimento", tags = {"FutController - Banimento no Fut"})
+ @Operation(
+ summary = "Adicionando um peladeiro da lista para o banimento",
+ tags = {"FutController - Banimento no Fut"})
public ResponseEntity adicionarBanimento(@RequestBody SaveBanimentoRequestDTO dto) {
futService.addBanimentoList(dto);
return ResponseEntity.noContent().build();
}
@GetMapping("lista-banidos/{idFut}")
- @Operation(summary = "Busca a lista de Banidos do Fut em questao", tags = {"FutController - Banimento no Fut"})
+ @Operation(
+ summary = "Busca a lista de Banidos do Fut em questao",
+ tags = {"FutController - Banimento no Fut"})
public ResponseEntity> buscarListaBanidos(
@PathVariable Long idFut) {
return ResponseEntity.ok().body(futService.findAllBanidos(idFut));
}
@DeleteMapping("delete-banimento/{idFut}/{idPeladeiro}")
- @Operation(summary = "retira um peladeiro da lista de banidos", tags = {"FutController - Banimento no Fut"})
+ @Operation(
+ summary = "retira um peladeiro da lista de banidos",
+ tags = {"FutController - Banimento no Fut"})
public ResponseEntity retirandoBanimento(
@PathVariable Long idFut, @PathVariable Long idPeladeiro) {
futService.removeBanido(idPeladeiro, idFut);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java
index 4e57a49..0e7e4f7 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java
@@ -23,7 +23,9 @@ public class PeladeiroController {
private final IPeladeiroService peladeiroService;
@PostMapping
- @Operation(summary = "Cadastra um novo peladeiro", tags = {"PeladeiroController"})
+ @Operation(
+ summary = "Cadastra um novo peladeiro",
+ tags = {"PeladeiroController"})
public ResponseEntity create(
@Valid @RequestBody final SavePeladeiroRequestDTO requestDTO) {
var obj = peladeiroService.create(requestDTO);
@@ -31,14 +33,18 @@ public ResponseEntity create(
}
@GetMapping("{id}")
- @Operation(summary = "Busca um Peladeiro pelo id", tags = {"PeladeiroController"})
+ @Operation(
+ summary = "Busca um Peladeiro pelo id",
+ tags = {"PeladeiroController"})
public ResponseEntity findById(@PathVariable final Long id) {
var obj = peladeiroService.findById(id);
return ResponseEntity.ok(obj);
}
@PutMapping("{id}")
- @Operation(summary = "Faz alteraçoes no Peladeiro cujo id é informado.", tags = {"PeladeiroController"})
+ @Operation(
+ summary = "Faz alteraçoes no Peladeiro cujo id é informado.",
+ tags = {"PeladeiroController"})
public ResponseEntity update(
@PathVariable final Long id, @Valid @RequestBody UpdatePeladeiroRequestDTO dto) {
peladeiroService.update(id, dto);
@@ -46,14 +52,18 @@ public ResponseEntity update(
}
@DeleteMapping("{id}")
- @Operation(summary = "Deleta o peladeiro cujo id foi informado. Cuidado!", tags = {"PeladeiroController"})
+ @Operation(
+ summary = "Deleta o peladeiro cujo id foi informado. Cuidado!",
+ tags = {"PeladeiroController"})
public ResponseEntity delete(@PathVariable final Long id) {
peladeiroService.delete(id);
return ResponseEntity.noContent().build();
}
@PostMapping(value = "uploadFoto/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- @Operation(summary = "Caso nao logado pelo gmail, enviar a foto do perfil", tags = {"PeladeiroController"})
+ @Operation(
+ summary = "Caso nao logado pelo gmail, enviar a foto do perfil",
+ tags = {"PeladeiroController"})
public ResponseEntity uploadFotoPeladeiro(
@PathVariable Long id, @RequestPart("file") MultipartFile file) throws IOException {
peladeiroService.atualizarFoto(id, file);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SaveFutRequestDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SaveFutRequestDTO.java
index 53bc28d..f4d8874 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SaveFutRequestDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SaveFutRequestDTO.java
@@ -8,4 +8,4 @@ public record SaveFutRequestDTO(
@PositiveOrZero Integer jogadoresPorTime,
@PositiveOrZero Integer tempoMaxPartida,
@PositiveOrZero Integer maxGolsVitoria,
- @PositiveOrZero Long administradorPeladeiroId) {}
+ @PositiveOrZero Long administradorPeladeiro) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResponseDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResponseDTO.java
index 95ec35e..36b9ee7 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResponseDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResponseDTO.java
@@ -3,4 +3,4 @@
import br.com.vemprofut.models.enuns.TipoCartao;
public record CartoesResponseDTO(
- Long id, Long partidaId, Long peladeiroId, Long futId, TipoCartao tipoCartao) {}
+ Long id, Long partida, Long peladeiro, Long fut, TipoCartao tipoCartao) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java
index 0ed4f04..64a52b3 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java
@@ -12,7 +12,7 @@ public record SavePeladeiroResponseDTO(
@JsonProperty("peDominante") String peDominante,
@JsonProperty("whatsapp") String whatsapp,
@JsonProperty("historicoPeladeiro") Long historicoPeladeiro,
- @JsonProperty("foto_url") String foto_url,
+ @JsonProperty("fotoUrl") String fotoUrl,
@JsonProperty("partidasIDs") List partidas,
@JsonProperty("futsIDs") List futs,
@JsonProperty("cartoes") List cartoes) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java
index 30e21a8..02fcf35 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java
@@ -8,4 +8,5 @@ public record UpdatePeladeiroResponseDTO(
@JsonProperty("apelido") String apelido,
@JsonProperty("descricao") String descricao,
@JsonProperty("whatsapp") String whatsapp,
- @JsonProperty("peDominante") String peDominante) {}
+ @JsonProperty("peDominante") String peDominante,
+ @JsonProperty("fotoURL") String fotoUrl) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/ICartoesMapper.java b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/ICartoesMapper.java
index bfbfede..0017fdc 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/ICartoesMapper.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/ICartoesMapper.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.mappers;
+import br.com.vemprofut.controllers.response.CartoesResponseDTO;
import br.com.vemprofut.models.CartoesModel;
import br.com.vemprofut.models.DTOs.CartoesDTO;
import org.mapstruct.Mapper;
@@ -24,4 +25,6 @@ Esses dois campos (`cartoesPartida` e `cartoesPeladeiro`) são listas de objetos
// De Entity/Model --> DTO
CartoesDTO toDTO(CartoesModel model);
+
+ CartoesResponseDTO toResponseDTO(CartoesModel model);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IFutMapper.java b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IFutMapper.java
index 21e7077..b15083f 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IFutMapper.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IFutMapper.java
@@ -7,6 +7,7 @@
import br.com.vemprofut.models.DTOs.FutDTO;
import br.com.vemprofut.models.FutModel;
import org.mapstruct.Mapper;
+import org.mapstruct.Mapping;
@Mapper(
componentModel = "spring",
@@ -14,8 +15,17 @@
public interface IFutMapper {
// DTO --> Model
+ @Mapping(target = "foto_url", ignore = true)
+ @Mapping(target = "banidos", ignore = true)
FutModel toModel(FutDTO dto);
+ @Mapping(target = "id", ignore = true)
+ @Mapping(target = "foto_url", ignore = true)
+ @Mapping(target = "historicoFutId", ignore = true)
+ @Mapping(target = "editores", ignore = true)
+ @Mapping(target = "peladeiros", ignore = true)
+ @Mapping(target = "cartoes", ignore = true)
+ @Mapping(target = "banidos", ignore = true)
FutModel saveRequestToModel(SaveFutRequestDTO dto);
SaveFutResponseDTO toSaveResponse(FutModel dto);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IMappersDefault.java b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IMappersDefault.java
index 87e60ae..b848a69 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IMappersDefault.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IMappersDefault.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.mappers;
+import br.com.vemprofut.controllers.response.CartoesResponseDTO;
import br.com.vemprofut.controllers.response.CartoesResumoResponseDTO;
import br.com.vemprofut.controllers.response.PeladeiroResponseDTO;
import br.com.vemprofut.models.CartoesModel;
@@ -64,6 +65,18 @@ default CartoesResumoResponseDTO mapResumoCartoes(List cartoes) {
return resultados;
}
+ default CartoesResponseDTO mapResponceCartoesDTO(CartoesModel model) {
+ CartoesResponseDTO cartoesResponseDTO =
+ new CartoesResponseDTO(
+ model.getId(),
+ model.getPartida().getId(),
+ model.getPeladeiro().getId(),
+ model.getFut().getId(),
+ model.getTipoCartao());
+
+ return cartoesResponseDTO;
+ }
+
// ========================EDITOR=====================
// Converte EditorModel -> Long (pegando o id)
@@ -179,8 +192,8 @@ default PeladeiroResponseDTO mapModelToResponse(PeladeiroModel model) {
// return new PeladeiroNameIdResponseDTO(peladeiroId, nome);
// }
- //======================Banimento=================================
- //TODO: coversao de peladeiro para o long no DTODetails
- //TODO: coversao de fut para o long no DTODetails
+ // ======================Banimento=================================
+ // TODO: coversao de peladeiro para o long no DTODetails
+ // TODO: coversao de fut para o long no DTODetails
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IPeladeiroMapper.java b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IPeladeiroMapper.java
index 3a9c9a1..454e824 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IPeladeiroMapper.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/mappers/IPeladeiroMapper.java
@@ -18,6 +18,12 @@
public interface IPeladeiroMapper {
// DTO --> Model
+ @Mapping(target = "administra", ignore = true)
+ @Mapping(target = "editores", ignore = true)
+ @Mapping(target = "fotoUrl", ignore = true)
+ @Mapping(target = "golsPeladeiro", ignore = true)
+ @Mapping(target = "banimentos", ignore = true)
+ @Mapping(target = "authProvider", ignore = true)
PeladeiroModel toModel(PeladeiroDTO dto);
@BeanMapping(
@@ -32,10 +38,21 @@ public interface IPeladeiroMapper {
PeladeiroDetailResponse modelToDetailsDTO(PeladeiroModel model);
@Mapping(target = "id", ignore = true)
+ @Mapping(target = "historicoPeladeiro", ignore = true)
+ @Mapping(target = "partidas", ignore = true)
+ @Mapping(target = "cartoes", ignore = true)
+ @Mapping(target = "futs", ignore = true)
+ @Mapping(target = "administra", ignore = true)
+ @Mapping(target = "editores", ignore = true)
+ @Mapping(target = "fotoUrl", ignore = true)
+ @Mapping(target = "golsPeladeiro", ignore = true)
+ @Mapping(target = "banimentos", ignore = true)
+ @Mapping(target = "authProvider", ignore = true)
PeladeiroModel saveRequestToModel(SavePeladeiroRequestDTO dto);
UpdatePeladeiroResponseDTO modelToUpdateResponse(PeladeiroModel model);
+ @Mapping(target = "fotoUrl", ignore = true)
SavePeladeiroResponseDTO modelToSaveResponse(PeladeiroModel model);
@Mapping(source = "id", target = "peladeiroId")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/BanimentoModel.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/BanimentoModel.java
index 9b56881..8dac986 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/BanimentoModel.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/BanimentoModel.java
@@ -2,7 +2,6 @@
import jakarta.persistence.*;
import java.time.LocalDate;
-import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@@ -11,10 +10,22 @@
@Table(name = "banimento")
@Getter
@Setter
-@AllArgsConstructor
@NoArgsConstructor
public class BanimentoModel {
+ public BanimentoModel(
+ String motivo,
+ LocalDate dataBanimento,
+ LocalDate dataFimBanimento,
+ PeladeiroModel peladeiro,
+ FutModel fut) {
+ this.motivo = motivo;
+ this.dataBanimento = dataBanimento;
+ this.dataFimBanimento = dataFimBanimento;
+ this.peladeiro = peladeiro;
+ this.fut = fut;
+ }
+
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_banimento")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/CartoesModel.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/CartoesModel.java
index f5e8ae2..3d67694 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/CartoesModel.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/CartoesModel.java
@@ -3,14 +3,24 @@
import br.com.vemprofut.models.enuns.TipoCartao;
import jakarta.persistence.*;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name = "cartoes_peladeiro")
@Getter
@Setter
+@NoArgsConstructor
public class CartoesModel {
+ public CartoesModel(
+ PartidasModel partida, PeladeiroModel peladeiro, FutModel fut, TipoCartao tipoCartao) {
+ this.partida = partida;
+ this.peladeiro = peladeiro;
+ this.fut = fut;
+ this.tipoCartao = tipoCartao;
+ }
+
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_cartoes_peladeiro")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartaoCountProjection.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartaoCountProjection.java
index dc9d8db..6dd1420 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartaoCountProjection.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartaoCountProjection.java
@@ -2,6 +2,7 @@
import br.com.vemprofut.models.enuns.TipoCartao;
+// Essa interface está em DTOs porque ela representa um objeto de transferência de dados.
public interface CartaoCountProjection {
TipoCartao getTipo();
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartoesDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartoesDTO.java
index 15c353c..b7563f0 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartoesDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/CartoesDTO.java
@@ -2,5 +2,4 @@
import br.com.vemprofut.models.enuns.TipoCartao;
-public record CartoesDTO(
- Long id, Long partidaId, Long peladeiroId, Long futId, TipoCartao tipoCartao) {}
+public record CartoesDTO(Long id, Long partida, Long peladeiro, Long fut, TipoCartao tipoCartao) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/EditorDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/EditorDTO.java
index fb50131..027f37a 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/EditorDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/EditorDTO.java
@@ -1,3 +1,3 @@
package br.com.vemprofut.models.DTOs;
-public record EditorDTO(Long id, Long peladeiroId, Long futId) {}
+public record EditorDTO(Long id, Long peladeiro, Long fut) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/FutDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/FutDTO.java
index c9a63f8..d7f1eb5 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/FutDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/DTOs/FutDTO.java
@@ -9,7 +9,7 @@ public record FutDTO(
Integer tempoMaxPartida,
Integer maxGolsVitoria,
Long historicoFutId,
- Long administradorPeladeiroId,
+ Long administradorPeladeiro,
List editores,
List peladeiros,
List cartoes) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/EditorModel.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/EditorModel.java
index b18fcca..f1b2e5d 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/EditorModel.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/EditorModel.java
@@ -12,6 +12,11 @@
@NoArgsConstructor
public class EditorModel {
+ public EditorModel(PeladeiroModel peladeiro, FutModel fut) {
+ this.peladeiro = peladeiro;
+ this.fut = fut;
+ }
+
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_editor")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/FutModel.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/FutModel.java
index 5e36f06..0d316eb 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/FutModel.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/FutModel.java
@@ -4,6 +4,7 @@
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@@ -11,8 +12,24 @@
@Table(name = "fut")
@Getter
@Setter
+@NoArgsConstructor
public class FutModel {
+ public FutModel(
+ String nome,
+ Integer jogadoresPorTime,
+ Integer tempoMaxPartida,
+ Integer maxGolsVitoria,
+ HistoricoFutModel historicoFutId,
+ PeladeiroModel administradorPeladeiro) {
+ this.nome = nome;
+ this.jogadoresPorTime = jogadoresPorTime;
+ this.tempoMaxPartida = tempoMaxPartida;
+ this.maxGolsVitoria = maxGolsVitoria;
+ this.historicoFutId = historicoFutId;
+ this.administradorPeladeiro = administradorPeladeiro;
+ }
+
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_fut")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java
index 00be016..bd1176c 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java
@@ -3,16 +3,31 @@
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.ToString;
+import lombok.*;
@Entity
@Table(name = "peladeiro")
@Getter
@Setter
+@NoArgsConstructor
+@AllArgsConstructor
public class PeladeiroModel {
+ public PeladeiroModel(
+ String nome,
+ String email,
+ String apelido,
+ String descricao,
+ String whatsapp,
+ String peDominante) {
+ this.nome = nome;
+ this.email = email;
+ this.apelido = apelido;
+ this.descricao = descricao;
+ this.whatsapp = whatsapp;
+ this.peDominante = peDominante;
+ }
+
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_peladeiro")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/repositories/BanimentoRepository.java b/VemProFutApi/src/main/java/br/com/vemprofut/repositories/BanimentoRepository.java
index 3b30e88..d5c14d6 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/repositories/BanimentoRepository.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/repositories/BanimentoRepository.java
@@ -11,13 +11,13 @@ public interface BanimentoRepository extends JpaRepository
@Query(
"""
- SELECT b FROM BanimentoModel b WHERE b.fut = :idFut AND b.peladeiro = :idPeladeiro
- """)
+ SELECT b FROM BanimentoModel b WHERE b.fut = :idFut AND b.peladeiro = :idPeladeiro
+ """)
Optional buscarBanimentoFutPeladeiro(
@Param("idFut") Long idFut, @Param("idPeladeiro") Long idPeladeiro);
@Query("""
- SELECT b FROM BanimentoModel b WHERE b.fut = :idFut
- """)
+ SELECT b FROM BanimentoModel b WHERE b.fut = :idFut
+ """)
List buscarListBanidos(@Param("idFut") Long idFut);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/repositories/CartoesRepository.java b/VemProFutApi/src/main/java/br/com/vemprofut/repositories/CartoesRepository.java
index 9a055e9..f0855df 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/repositories/CartoesRepository.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/repositories/CartoesRepository.java
@@ -24,17 +24,17 @@ SELECT c.tipoCartao AS tipo, COUNT(c) AS quantidade
FROM CartoesModel c
WHERE c.peladeiro.id = :peladeiroId
GROUP BY c.tipoCartao
- """)
+ """)
List countByTipoAndPeladeiro(@Param("peladeiroId") Long peladeiroId);
@Query(
"""
SELECT c.tipoCartao AS tipo, COUNT(c) AS quantidade
FROM CartoesModel c
- WHERE c.fut.id = :futId
+ WHERE c.fut.id = :fut
GROUP BY c.tipoCartao
- """)
- List countByTipoAndFut(@Param("futId") Long futId);
+ """)
+ List countByTipoAndFut(@Param("fut") Long futId);
/*
Agora o retorno já vem fortemente tipado: cada item da lista é um 'CartaoCountProjection' com getTipo()
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/repositories/EditorRepository.java b/VemProFutApi/src/main/java/br/com/vemprofut/repositories/EditorRepository.java
index d8bf585..92b99e8 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/repositories/EditorRepository.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/repositories/EditorRepository.java
@@ -13,7 +13,7 @@ public interface EditorRepository extends JpaRepository {
@Query(
"""
SELECT e FROM EditorModel e WHERE e.peladeiro = :peladeiro AND e.fut= :fut
- """)
+ """)
EditorModel findByPeladeiroAndFut(
@Param("peladeiro") PeladeiroModel peladeiroModel, @Param("fut") FutModel futModel);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java
index 8a418dd..3aa0c5f 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java
@@ -60,7 +60,7 @@ public class FutService implements IFutService {
@Transactional
public SaveFutResponseDTO create(SaveFutRequestDTO dto) {
queryService.verifyNomeFutExist(dto.nome());
- var peladeiro = peladeiroQueryService.verifyPeladeiroExist(dto.administradorPeladeiroId());
+ var peladeiro = peladeiroQueryService.verifyPeladeiroExist(dto.administradorPeladeiro());
FutModel saved = repository.save(mapper.saveRequestToModel(dto));
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/ICartoesQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/ICartoesQueryService.java
index d55d01a..1839fa9 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/ICartoesQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/ICartoesQueryService.java
@@ -2,15 +2,9 @@
import br.com.vemprofut.models.CartoesModel;
import br.com.vemprofut.models.DTOs.CartoesDTO;
-import br.com.vemprofut.models.DTOs.PartidasDTO;
-import br.com.vemprofut.models.DTOs.PeladeiroDTO;
public interface ICartoesQueryService {
- void verifyPeladeiroExist(PeladeiroDTO peladeiroDTO);
-
- void verifyPartidasExist(PartidasDTO partidasDTO);
-
void verifyEntitiesExist(CartoesDTO dto);
CartoesModel verityCartoesExist(Long id);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/BanimentoQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/BanimentoQueryService.java
index a7a031e..95900bb 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/BanimentoQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/BanimentoQueryService.java
@@ -7,16 +7,16 @@
import br.com.vemprofut.models.BanimentoModel;
import br.com.vemprofut.repositories.BanimentoRepository;
import br.com.vemprofut.services.query.IBanimentoQueryService;
-import org.springframework.stereotype.Service;
-
import java.util.List;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
@Service
public class BanimentoQueryService implements IBanimentoQueryService {
- private BanimentoRepository repository;
+ @Autowired private BanimentoRepository repository;
- private IBanimentoMapper mapper;
+ @Autowired private IBanimentoMapper mapper;
@Override
public void verifyPeladeiroBanidoExist(Long idFut, Long idPeladeiro) {
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/CartoesQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/CartoesQueryService.java
index c63bd04..20bd3ec 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/CartoesQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/CartoesQueryService.java
@@ -3,37 +3,25 @@
import br.com.vemprofut.exceptions.NotFoundException;
import br.com.vemprofut.models.CartoesModel;
import br.com.vemprofut.models.DTOs.CartoesDTO;
-import br.com.vemprofut.models.DTOs.PartidasDTO;
-import br.com.vemprofut.models.DTOs.PeladeiroDTO;
import br.com.vemprofut.repositories.CartoesRepository;
import br.com.vemprofut.services.query.ICartoesQueryService;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CartoesQueryService implements ICartoesQueryService {
- private CartoesRepository repository;
-
- @Override
- public void verifyPeladeiroExist(PeladeiroDTO peladeiroDTO) {
- // TODO: implementar
- }
-
- @Override
- public void verifyPartidasExist(PartidasDTO partidasDTO) {
- // TODO: implementar
- }
+ @Autowired private CartoesRepository repository;
// Verifica se o peladeiro, partida e fut existem
public void verifyEntitiesExist(CartoesDTO dto) {
- if (!repository.existsById(dto.peladeiroId()))
+ if (!repository.existsById(dto.peladeiro()))
throw new IllegalArgumentException("Peladeiro não encontrado");
- if (!repository.existsById(dto.partidaId()))
+ if (!repository.existsById(dto.partida()))
throw new IllegalArgumentException("Partida não encontrada");
- if (!repository.existsById(dto.futId()))
- throw new IllegalArgumentException("Fut não encontrado");
+ if (!repository.existsById(dto.fut())) throw new IllegalArgumentException("Fut não encontrado");
}
public CartoesModel verityCartoesExist(Long id) {
diff --git a/VemProFutApi/src/main/resources/application-dev.properties b/VemProFutApi/src/main/resources/application-dev.properties
index 0f1ce81..425cb0e 100644
--- a/VemProFutApi/src/main/resources/application-dev.properties
+++ b/VemProFutApi/src/main/resources/application-dev.properties
@@ -1,11 +1,49 @@
-spring:
- jpa:
- show-sql: true
- properties:
- hibernate:
- format_sql: true
- devtools:
- remote:
- secret: 123
- restart:
- trigger-file: trigger.txt
\ No newline at end of file
+spring.application.name=VemProFut
+
+######################################################
+# == BANCO LOCAL (MySQL Rodando Localmente) ==========
+######################################################
+spring.datasource.url=jdbc:mysql://localhost:3306/vemprofutdb?createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
+spring.datasource.username=root
+spring.datasource.password=root123
+
+spring.jpa.hibernate.ddl-auto=none
+
+
+######################################################
+# == LOGS (DEV: Mais detalhados) =====================
+######################################################
+logging.level.root=INFO
+logging.level.br.com.vemprofut=DEBUG
+
+# Mostra queries SQL (util para dev, mas nao tao agressivo)
+logging.level.log.hibernate.SQL=DEBUG
+logging.level.log.hibernate.type.descritor.sql.BasicBinder=TRACE
+
+
+######################################################
+# == FLYWAY ==========================================
+######################################################
+spring.flyway.enabled=true
+spring.flyway.locations=classpath:db/migration
+
+
+######################################################
+# == AUTH0 (Somente para DEV) ========================
+######################################################
+spring.security.oauth2.client.registration.auth0.client-id=jcmpSdlqwwakcitekSVmh0F0Hw6BEcf7
+spring.security.oauth2.client.registration.auth0.client-secret=QWUV1hzjq3fgZy0vNuv_ir9Svsv11JeAw241YuPpMcCCeP7kdTbgajsaptfk52Mx
+spring.security.oauth2.client.registration.auth0.redirect-uri=http://localhost:8080/login/oauth2/code/{registrationId}
+
+spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-6nhln802vsqkhnfm.us.auth0.com/
+
+spring.security.oauth2.client.registration.auth0.authorization-grant-type=authorization_code
+spring.security.oauth2.client.registration.auth0.scope=openid,profile,email
+
+# Provedor (provider) configurado para o nome 'auth0'
+spring.security.oauth2.client.provider.auth0.issuer-uri=https://dev-6nhln802vsqkhnfm.us.auth0.com/
+
+######################################################
+# == UPLOAD LOCAL ====================================
+######################################################
+app.upload.dir=uploads
diff --git a/VemProFutApi/src/main/resources/application-prod.properties b/VemProFutApi/src/main/resources/application-prod.properties
new file mode 100644
index 0000000..be2aa8f
--- /dev/null
+++ b/VemProFutApi/src/main/resources/application-prod.properties
@@ -0,0 +1,39 @@
+spring.application.name=VemProFut
+
+# MYSQL via Docker Compose
+spring.datasource.url=${SPRING_DATASOURCE_URL}
+spring.datasource.username=${SPRING_DATASOURCE_USERNAME}
+spring.datasource.password=${SPRING_DATASOURCE_PASSWORD}
+
+spring.jpa.hibernate.ddl-auto=none
+
+spring.flyway.enabled=true
+spring.flyway.locations=classpath:db/migration
+spring.flyway.fail-on-missing-locations=false
+spring.flyway.connect-retries=10
+spring.flyway.connect-retries-interval=5s
+
+# LOGS NO CONSOLE (padrao Docker)
+logging.level.root=INFO
+logging.level.org.springframework=INFO
+
+# Upload definido por volume
+app.upload.dir=/app/uploads
+
+# ----------- Auth0 / OAuth2 -----------
+# Client registration
+spring.security.oauth2.client.registration.auth0.client-id=${AUTH0_CLIENT_ID}
+spring.security.oauth2.client.registration.auth0.client-secret=${AUTH0_CLIENT_SECRET}
+spring.security.oauth2.client.registration.auth0.scope=openid,profile,email
+spring.security.oauth2.client.registration.auth0.redirect-uri={baseUrl}/login/oauth2/code/auth0
+
+# Provider configuration
+spring.security.oauth2.client.provider.auth0.issuer-uri=${AUTH0_ISSUER}
+
+# Resource server JWT (para valida\u00E7\u00E3o de tokens)
+spring.security.oauth2.resourceserver.jwt.issuer-uri=${AUTH0_ISSUER}
+
+# For\u00E7a API a aceitar conex\u00F5es externas (necess\u00E1rio no Docker)
+server.address=0.0.0.0
+server.port=8080
+server.servlet.session.cookie.secure=false
diff --git a/VemProFutApi/src/main/resources/application.properties b/VemProFutApi/src/main/resources/application.properties
index 917ad11..d20414d 100644
--- a/VemProFutApi/src/main/resources/application.properties
+++ b/VemProFutApi/src/main/resources/application.properties
@@ -1,62 +1 @@
-spring.application.name=VemProFut
-spring.datasource.url=${SPRING_DATASOURCE_URL:jdbc:mysql://localhost:3306/vemprofutdb?createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true&useSSL=false&serverTimeZone=UTC}
-spring.datasource.username=${SPRING_DATASOURCE_USERNAME:root}
-spring.datasource.password=${SPRING_DATASOURCE_PASSWORD:root123}
-
spring.profiles.active=${SPRING_PROFILES_ACTIVE:dev}
-
-spring.jpa.hibernate.ddl-auto=none
-
-###############################################
-# == Ativando logs de excecoes do Spring ======
-###############################################
-
-logging.level.org.springframework.aop=DEBUG
-logging.level.org.springframework.transaction=DEBUG
-logging.level.org.hibernate.SQL=DEBUG
-logging.level.org.hibernate.type.descriptor.sql=TRACE
-
-###############################################
-#================ Flyway ======================
-###############################################
-spring.flyway.enabled=true
-spring.flyway.locations=classpath:db/migration
-
-###############################################################
-# == Logger SLF4J para salvar os logs de erro e etc...=========
-###############################################################
-
-logging.level.root=INFO
-logging.level.br.com.vemprofut=DEBUG
-logging.level.org.flywaydb=DEBUG
-
-logging.file.name=logs/vemprofut.log
-logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} - %msg%n
-
-logging.logback.rollingpolicy.file-name-pattern=logs/vemprofut-%d{yyyy-MM-dd}.log
-logging.logback.rollingpolicy.max-file-size=10MB
-logging.logback.rollingpolicy.max-history=10
-
-###############################################
-# ========== OAuth2 Client (Auth0) ============
-###############################################
-
-spring.security.oauth2.client.registration.auth0.client-id=jcmpSdlqwwakcitekSVmh0F0Hw6BEcf7
-spring.security.oauth2.client.registration.auth0.client-secret=QWUV1hzjq3fgZy0vNuv_ir9Svsv11JeAw241YuPpMcCCeP7kdTbgajsaptfk52Mx
-spring.security.oauth2.client.registration.auth0.scope=openid, profile, email
-spring.security.oauth2.client.registration.auth0.redirect-uri=http://localhost:8080/login/oauth2/code/{registrationId}
-spring.security.oauth2.client.registration.auth0.authorization-grant-type=authorization_code
-
-spring.security.oauth2.client.provider.auth0.issuer-uri=https://dev-6nhln802vsqkhnfm.us.auth0.com/
-
-
-###############################################
-# ===== Resource Server (JWT Validation) ======
-###############################################
-
-spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-6nhln802vsqkhnfm.us.auth0.com/
-
-###############################################
-# ======== Salvar Foto Localmente =============
-###############################################
-app.upload.dir=uploads
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092157__alter_table_partidas_contrains_fk_partidas2.sql b/VemProFutApi/src/main/resources/db/migration/V202511092157__alter_table_partidas_contrains_fk_partidas2.sql
index 39c69a9..3ddbe2a 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092157__alter_table_partidas_contrains_fk_partidas2.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092157__alter_table_partidas_contrains_fk_partidas2.sql
@@ -1,4 +1,4 @@
-ALTER TABLE Partidas ADD CONSTRAINT FK_Partidas_2
+ALTER TABLE partidas ADD CONSTRAINT FK_Partidas_2
FOREIGN KEY (fk_fut)
- REFERENCES Fut (id_fut)
+ REFERENCES fut (id_fut)
ON DELETE CASCADE;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092159__alter_table_gols_constraint_fk_gols2.sql b/VemProFutApi/src/main/resources/db/migration/V202511092159__alter_table_gols_constraint_fk_gols2.sql
index d458781..5bf7507 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092159__alter_table_gols_constraint_fk_gols2.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092159__alter_table_gols_constraint_fk_gols2.sql
@@ -1,4 +1,4 @@
-ALTER TABLE Gols_Partida ADD CONSTRAINT FK_Gols_Partida_2
+ALTER TABLE gols_partida ADD CONSTRAINT FK_Gols_Partida_2
FOREIGN KEY (fk_peladeiro)
- REFERENCES Peladeiro (id_peladeiro)
+ REFERENCES peladeiro (id_peladeiro)
ON DELETE CASCADE;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_fk_gols3.sql b/VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_fk_gols3.sql
new file mode 100644
index 0000000..8cb57f8
--- /dev/null
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_fk_gols3.sql
@@ -0,0 +1,4 @@
+ALTER TABLE gols_partida ADD CONSTRAINT FK_Gols_Partida_3
+ FOREIGN KEY (fk_partida)
+ REFERENCES partidas (id_partida)
+ ON DELETE CASCADE;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_gols3,sql b/VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_gols3,sql
deleted file mode 100644
index 9c70e59..0000000
--- a/VemProFutApi/src/main/resources/db/migration/V202511092200__alter_table_gols_constraint_gols3,sql
+++ /dev/null
@@ -1,4 +0,0 @@
-ALTER TABLE Gols_Partida ADD CONSTRAINT FK_Gols_Partida_2
- FOREIGN KEY (fk_partida)
- REFERENCES Partida (id_partida)
- ON DELETE CASCADE;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092204__alter_table_participapeladeiro_contraint_participa1.sql b/VemProFutApi/src/main/resources/db/migration/V202511092204__alter_table_participapeladeiro_contraint_participa1.sql
index 5ef06e9..78c3bb6 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092204__alter_table_participapeladeiro_contraint_participa1.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092204__alter_table_participapeladeiro_contraint_participa1.sql
@@ -1,4 +1,4 @@
ALTER TABLE participa_peladeiro_fut ADD CONSTRAINT FK_participa_peladeiro_fut_1
FOREIGN KEY (fk_fut)
- REFERENCES Fut (id_fut)
+ REFERENCES fut (id_fut)
ON DELETE CASCADE;
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092205__alter_table_participapeladeiro_contraint_fk_participa2.sql b/VemProFutApi/src/main/resources/db/migration/V202511092205__alter_table_participapeladeiro_contraint_fk_participa2.sql
index e7e9510..5278845 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092205__alter_table_participapeladeiro_contraint_fk_participa2.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092205__alter_table_participapeladeiro_contraint_fk_participa2.sql
@@ -1,4 +1,4 @@
ALTER TABLE participa_peladeiro_fut ADD CONSTRAINT FK_participa_peladeiro_fut_2
FOREIGN KEY (fk_peladeiro)
- REFERENCES Peladeiro (id_peladeiro)
+ REFERENCES peladeiro (id_peladeiro)
ON DELETE CASCADE;
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092206__alter_table_estapeladeio_constraint_esta1.sql b/VemProFutApi/src/main/resources/db/migration/V202511092206__alter_table_estapeladeio_constraint_esta1.sql
index a838639..6da82e3 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092206__alter_table_estapeladeio_constraint_esta1.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092206__alter_table_estapeladeio_constraint_esta1.sql
@@ -1,4 +1,4 @@
ALTER TABLE esta_peladeiro_partidas ADD CONSTRAINT FK_esta_peladeiro_partidas_1
FOREIGN KEY (fk_partidas)
- REFERENCES Partidas (id_partida)
+ REFERENCES partidas (id_partida)
ON DELETE CASCADE;
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092208__alter_table_estapeladeiro_constraint_fk_esta2.sql b/VemProFutApi/src/main/resources/db/migration/V202511092208__alter_table_estapeladeiro_constraint_fk_esta2.sql
index 62e90c6..c4f1a39 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092208__alter_table_estapeladeiro_constraint_fk_esta2.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092208__alter_table_estapeladeiro_constraint_fk_esta2.sql
@@ -1,4 +1,4 @@
ALTER TABLE esta_peladeiro_partidas ADD CONSTRAINT FK_esta_peladeiro_partidas_2
FOREIGN KEY (fk_peladeiro)
- REFERENCES Peladeiro (id_peladeiro)
+ REFERENCES peladeiro (id_peladeiro)
ON DELETE CASCADE;
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092212__alter_table_editor_constraint_fk_editor1.sql b/VemProFutApi/src/main/resources/db/migration/V202511092212__alter_table_editor_constraint_fk_editor1.sql
index 2fb84f8..37cb6d1 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092212__alter_table_editor_constraint_fk_editor1.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092212__alter_table_editor_constraint_fk_editor1.sql
@@ -1,4 +1,4 @@
ALTER TABLE editores_fut ADD CONSTRAINT FK_Editor_1
FOREIGN KEY (fk_fut)
- REFERENCES Fut (id_fut)
+ REFERENCES fut (id_fut)
ON DELETE CASCADE;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511092213__alter_table_editor_constraint_fk_editor2.sql b/VemProFutApi/src/main/resources/db/migration/V202511092213__alter_table_editor_constraint_fk_editor2.sql
index 09e2f68..18699ae 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511092213__alter_table_editor_constraint_fk_editor2.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511092213__alter_table_editor_constraint_fk_editor2.sql
@@ -1,4 +1,4 @@
ALTER TABLE editores_fut ADD CONSTRAINT FK_Editor_2
FOREIGN KEY (fk_peladeiro)
- REFERENCES Peladeiro (id_peladeiro)
+ REFERENCES peladeiro (id_peladeiro)
ON DELETE CASCADE;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511241710__alter_table_fk_banimento_2.sql b/VemProFutApi/src/main/resources/db/migration/V202511241710__alter_table_fk_banimento_2.sql
index 135e5fb..f152c3c 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511241710__alter_table_fk_banimento_2.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511241710__alter_table_fk_banimento_2.sql
@@ -1,4 +1,4 @@
ALTER TABLE banimento ADD CONSTRAINT FK_banimento_2
FOREIGN KEY (fk_peladeiro)
- REFERENCES Peladeiro (id_peladeiro)
+ REFERENCES peladeiro (id_peladeiro)
ON DELETE SET NULL;
\ No newline at end of file
diff --git a/VemProFutApi/src/main/resources/db/migration/V202511241712__alter_table_fk_banimento_3.sql b/VemProFutApi/src/main/resources/db/migration/V202511241712__alter_table_fk_banimento_3.sql
index 6a41c75..95618c9 100644
--- a/VemProFutApi/src/main/resources/db/migration/V202511241712__alter_table_fk_banimento_3.sql
+++ b/VemProFutApi/src/main/resources/db/migration/V202511241712__alter_table_fk_banimento_3.sql
@@ -1,4 +1,4 @@
ALTER TABLE banimento ADD CONSTRAINT FK_banimento_3
FOREIGN KEY (fk_fut)
- REFERENCES Fut (id_fut)
+ REFERENCES fut (id_fut)
ON DELETE SET NULL;
\ No newline at end of file
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java b/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java
deleted file mode 100644
index 8b8c5d1..0000000
--- a/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package br.com.vemprofut;
-
-import org.springframework.boot.test.context.SpringBootTest;
-
-@SpringBootTest
-class VemProFutApplicationTests {
-
- // @Test
- // void contextLoads() {
- // }
-
-}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java
new file mode 100644
index 0000000..19f9e2c
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java
@@ -0,0 +1,152 @@
+package br.com.vemprofut.integration.repositories;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import br.com.vemprofut.configs.OAuth2LoginSuccessHandler;
+import br.com.vemprofut.models.BanimentoModel;
+import br.com.vemprofut.models.FutModel;
+import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.repositories.BanimentoRepository;
+import br.com.vemprofut.repositories.FutRepository;
+import br.com.vemprofut.repositories.PeladeiroRepository;
+import br.com.vemprofut.services.implementacao.UploadLocalService;
+import jakarta.transaction.Transactional;
+import java.time.LocalDate;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.bean.override.mockito.MockitoBean;
+
+@SpringBootTest
+@Transactional
+@ActiveProfiles("test")
+public class BanimentoRepositoryIT {
+
+ @MockitoBean private OAuth2AuthorizedClientService authorizedClientService;
+
+ // Opcional: Mocka o próprio Handler para evitar que ele tente rodar lógica
+ @MockitoBean private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;
+
+ @MockitoBean private ClientRegistrationRepository clientRegistrationRepository;
+
+ @MockitoBean private JwtDecoder jwtDecoder;
+
+ @MockitoBean private UploadLocalService uploadLocalService;
+
+ @Autowired BanimentoRepository banimentoRepository;
+
+ @Autowired PeladeiroRepository peladeiroRepository;
+
+ @Autowired FutRepository futRepository;
+
+ @Test
+ @DisplayName("Deve gerar salvar um banimento e retornar um id")
+ public void save_quandoBanimentoValido_retornaIdGerado() {
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ BanimentoModel banimentoModel =
+ new BanimentoModel(
+ "quebrou a perna do amigo",
+ LocalDate.of(2025, 11, 9),
+ LocalDate.of(2026, 11, 9),
+ peladeiroModel,
+ futModel);
+
+ BanimentoModel banimentoSalvo = banimentoRepository.save(banimentoModel);
+
+ assertNotNull(banimentoSalvo.getId());
+ assertTrue(banimentoSalvo.getId() > 0);
+ }
+
+ @Test
+ @DisplayName("Deve buscar todos os os banimentos")
+ public void findAll_quandoExistemRegistros_retornaListaComTodos() {
+ FutModel futModel1 = futRepository.saveAndFlush(new FutModel());
+ FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
+ PeladeiroModel peladeiroModel1 =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+ PeladeiroModel peladeiroModel2 =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva2",
+ "joao2@test.com",
+ "Apelido2",
+ "descricao qualquer2",
+ "81999999999",
+ "Destro"));
+
+ BanimentoModel banimentoModel1 =
+ new BanimentoModel(
+ "quebrou a perna do amigo",
+ LocalDate.of(2025, 11, 9),
+ LocalDate.of(2026, 11, 9),
+ peladeiroModel1,
+ futModel1);
+ BanimentoModel banimentoModel2 =
+ new BanimentoModel(
+ "quebrou o ombro do amigo",
+ LocalDate.of(2025, 11, 9),
+ LocalDate.of(2026, 11, 9),
+ peladeiroModel2,
+ futModel2);
+
+ banimentoRepository.saveAndFlush(banimentoModel1);
+ banimentoRepository.saveAndFlush(banimentoModel2);
+
+ List todos = banimentoRepository.findAll();
+
+ assertTrue(todos.size() >= 2);
+ }
+
+ @Test
+ @DisplayName("Deve apagar um banimento pelo numero do ID")
+ public void deleteById_quandoIdBanimentoExistir_registroRemovido() {
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ BanimentoModel banimentoModel =
+ new BanimentoModel(
+ "quebrou a perna do amigo",
+ LocalDate.of(2025, 11, 9),
+ LocalDate.of(2026, 11, 9),
+ peladeiroModel,
+ futModel);
+
+ BanimentoModel banimentoSalvo = banimentoRepository.saveAndFlush(banimentoModel);
+
+ Long id = banimentoSalvo.getId();
+
+ banimentoRepository.deleteById(id);
+ assertFalse(banimentoRepository.findById(id).isPresent());
+ }
+}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java
new file mode 100644
index 0000000..a79912a
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java
@@ -0,0 +1,424 @@
+package br.com.vemprofut.integration.repositories;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import br.com.vemprofut.configs.OAuth2LoginSuccessHandler;
+import br.com.vemprofut.models.CartoesModel;
+import br.com.vemprofut.models.DTOs.CartaoCountProjection;
+import br.com.vemprofut.models.FutModel;
+import br.com.vemprofut.models.PartidasModel;
+import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.TipoCartao;
+import br.com.vemprofut.repositories.CartoesRepository;
+import br.com.vemprofut.repositories.FutRepository;
+import br.com.vemprofut.repositories.PartidasRepository;
+import br.com.vemprofut.repositories.PeladeiroRepository;
+import br.com.vemprofut.services.implementacao.UploadLocalService;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.bean.override.mockito.MockitoBean;
+import org.springframework.transaction.annotation.Transactional;
+
+@SpringBootTest
+@Transactional
+@ActiveProfiles("test")
+public class CartoesRepositoryIT {
+
+ @MockitoBean private OAuth2AuthorizedClientService authorizedClientService;
+
+ // Opcional: Mocka o próprio Handler para evitar que ele tente rodar lógica
+ @MockitoBean private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;
+
+ @MockitoBean private ClientRegistrationRepository clientRegistrationRepository;
+
+ @MockitoBean private UploadLocalService uploadLocalService;
+
+ @MockitoBean private JwtDecoder jwtDecoder;
+
+ @Autowired CartoesRepository cartoesRepository;
+
+ @Autowired PartidasRepository partidasRepository;
+
+ @Autowired FutRepository futRepository;
+
+ @Autowired PeladeiroRepository peladeiroRepository;
+
+ @Test
+ @DisplayName("Deve criar um novo cartao ligado ao peladeiro e a partida")
+ void save_quandoCartaoValido_retornaIdGerado() {
+
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ CartoesModel cartoesModel =
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ assertNotNull(cartoesModel.getId());
+ assertTrue(cartoesModel.getId() > 0);
+ }
+
+ @Test
+ @DisplayName("Deve buscar todos cartoes e retorna em uma lista")
+ void findAll_quandoCartoesExistem_retornaListaCartao() {
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+ PartidasModel partidasModel2 = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+ FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ PeladeiroModel peladeiroModel2 =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva2",
+ "joao2@test.com",
+ "Apelido",
+ "descricao qualquer2",
+ "81999999999",
+ "Destro"));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel2, futModel2, TipoCartao.AMARELO));
+
+ List todos = cartoesRepository.findAll();
+
+ assertTrue(todos.size() >= 2);
+ }
+
+ @Test
+ @DisplayName("Deve buscar um cartao pelo IDe retornar um Optional")
+ void findById_quandoCartaoExiste_retornaCartao() {
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ CartoesModel cartoesModel =
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ Long id = cartoesModel.getId();
+
+ assertTrue(cartoesRepository.findById(id).isPresent());
+ }
+
+ @Test
+ @DisplayName("Deve buscar um cartao pelo ID e retornar um Optional vazio")
+ void findById_quandoCartaoExiste_retornaOptinalVazio() {
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ CartoesModel cartoesModel =
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ Long id = 99999L;
+
+ assertTrue(cartoesRepository.findById(id).isEmpty());
+ }
+
+ @Test
+ @DisplayName("Deve buscar todos os cartoes de um Peladeiro especifico")
+ void findByPeladeiro_quandoCartoesDoPeladeiroExistem_retornaListCartoes() {
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ PeladeiroModel peladeiroModel2 =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "Paulo Silva",
+ "paulo@test.com",
+ "Apelido",
+ "descricao qualquer2",
+ "81999999999",
+ "Destro"));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AZUL));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel2, futModel, TipoCartao.AMARELO));
+
+ List todosCartoesPeladeiro = cartoesRepository.findByPeladeiro(peladeiroModel);
+
+ assertEquals(2, todosCartoesPeladeiro.size());
+ }
+
+ @Test
+ @DisplayName("Deve buscar todos os cartoes de uma Partida especifico")
+ void findByPartida_quandoCartoesExistem_retornaListCartoes() {
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+ PartidasModel partidasModel2 = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AZUL));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ List todosCartoesPeladeiro = cartoesRepository.findByPartida(partidasModel);
+
+ assertEquals(2, todosCartoesPeladeiro.size());
+ }
+
+ @Test
+ @DisplayName("Deve buscar todos os cartoes de um Peladeiro especifico")
+ void findByFut_quandoCartoesExistem_retornaListCartoes() {
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+ FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AZUL));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel2, TipoCartao.AMARELO));
+
+ List todosCartoesPeladeiro = cartoesRepository.findByFut(futModel);
+
+ assertEquals(2, todosCartoesPeladeiro.size());
+ }
+
+ @Test
+ @DisplayName("Deve retornar a quantidade de total de cada cartao de um peladeiro especifico")
+ void countByTipoAndPeladeiro_quandoCartoesExistem_retornaListCartoesPeladeiroContado() {
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ PeladeiroModel peladeiroModel2 =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "Paulo Silva",
+ "paulo@test.com",
+ "Apelido",
+ "descricao qualquer2",
+ "81999999999",
+ "Destro"));
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+ FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
+
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+ PartidasModel partidasModel2 = partidasRepository.saveAndFlush(new PartidasModel());
+
+ // dados peladeiro 1
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AZUL));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel, futModel2, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel, futModel2, TipoCartao.VERMELHO));
+
+ // Dados peladeiro 2
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel2, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel2, futModel, TipoCartao.AZUL));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel2, futModel2, TipoCartao.AMARELO));
+
+ List contagem =
+ cartoesRepository.countByTipoAndPeladeiro(peladeiroModel.getId());
+
+ // Transformar em mapa para facilitar
+ Map resultado =
+ Arrays.stream(TipoCartao.values())
+ .collect(
+ Collectors.toMap(
+ tipo -> tipo,
+ tipo ->
+ contagem.stream()
+ .filter(c -> c.getTipo() == tipo)
+ .map(CartaoCountProjection::getQuantidade)
+ .findFirst()
+ .orElse(0L)));
+
+ assertEquals(2, resultado.get(TipoCartao.AMARELO));
+ assertEquals(1, resultado.get(TipoCartao.AZUL));
+ assertEquals(1, resultado.get(TipoCartao.VERMELHO));
+ }
+
+ @Test
+ @DisplayName("Deve retornar a quantidade de total de cada cartao de um Fut especifico")
+ void countByTipoAndFut__quandoCartoesExistem_retornaListCartoesFutContado() {
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "João da Silva",
+ "joao@test.com",
+ "Apelido",
+ "descricao qualquer",
+ "81999999999",
+ "Destro"));
+
+ PeladeiroModel peladeiroModel2 =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "Paulo Silva",
+ "paulo@test.com",
+ "Apelido",
+ "descricao qualquer2",
+ "81999999999",
+ "Destro"));
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+ FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
+
+ PartidasModel partidasModel = partidasRepository.saveAndFlush(new PartidasModel());
+ PartidasModel partidasModel2 = partidasRepository.saveAndFlush(new PartidasModel());
+
+ // dados Fut 1
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel2, futModel, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AZUL));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel, peladeiroModel2, futModel, TipoCartao.AZUL));
+
+ // Dados fut 2
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel2, futModel2, TipoCartao.AMARELO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel, futModel2, TipoCartao.VERMELHO));
+
+ cartoesRepository.saveAndFlush(
+ new CartoesModel(partidasModel2, peladeiroModel, futModel2, TipoCartao.AMARELO));
+
+ List contagem = cartoesRepository.countByTipoAndFut(futModel.getId());
+
+ // Transformar em mapa para facilitar
+ Map resultado =
+ Arrays.stream(TipoCartao.values())
+ .collect(
+ Collectors.toMap(
+ tipo -> tipo,
+ tipo ->
+ contagem.stream()
+ .filter(c -> c.getTipo() == tipo)
+ .map(CartaoCountProjection::getQuantidade)
+ .findFirst()
+ .orElse(0L)));
+ assertEquals(2, resultado.get(TipoCartao.AMARELO));
+ assertEquals(2, resultado.get(TipoCartao.AZUL));
+ assertEquals(0, resultado.get(TipoCartao.VERMELHO));
+ }
+}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java
new file mode 100644
index 0000000..a06fb0d
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java
@@ -0,0 +1,90 @@
+package br.com.vemprofut.integration.repositories;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import br.com.vemprofut.configs.OAuth2LoginSuccessHandler;
+import br.com.vemprofut.models.EditorModel;
+import br.com.vemprofut.models.FutModel;
+import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.repositories.EditorRepository;
+import br.com.vemprofut.repositories.FutRepository;
+import br.com.vemprofut.repositories.PeladeiroRepository;
+import br.com.vemprofut.services.implementacao.UploadLocalService;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.bean.override.mockito.MockitoBean;
+import org.springframework.transaction.annotation.Transactional;
+
+@SpringBootTest
+@Transactional
+@ActiveProfiles("test")
+public class EditorRepositoryIT {
+
+ @MockitoBean private OAuth2AuthorizedClientService authorizedClientService;
+
+ @MockitoBean private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;
+
+ @MockitoBean private ClientRegistrationRepository clientRegistrationRepository;
+
+ @MockitoBean private UploadLocalService uploadLocalService;
+
+ @MockitoBean private JwtDecoder jwtDecoder;
+
+ @Autowired EditorRepository editorRepository;
+
+ @Autowired PeladeiroRepository peladeiroRepository;
+
+ @Autowired FutRepository futRepository;
+
+ @Test
+ @DisplayName("Deve salvar um novo Editor em um Fut especifico")
+ void save_quandoEditorValido_retornaEditorSalvo() {
+
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "Marcio Teste",
+ "teste@test.com",
+ "Ronaldo",
+ "o cara nota 10",
+ "81992235678",
+ "Destro"));
+
+ EditorModel editorModel =
+ editorRepository.saveAndFlush(new EditorModel(peladeiroModel, futModel));
+
+ assertNotNull(editorModel.getId());
+ assertTrue(editorModel.getId() > 0);
+ }
+
+ @Test
+ @DisplayName("Deve buscar e retornar um Editor salvo")
+ void findById_quandoEditorExiste_retornaEditorSalvo() {
+ FutModel futModel = futRepository.saveAndFlush(new FutModel());
+
+ PeladeiroModel peladeiroModel =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel(
+ "Marcio Teste",
+ "teste@test.com",
+ "Ronaldo",
+ "o cara nota 10",
+ "81992235678",
+ "Destro"));
+
+ EditorModel editorModel =
+ editorRepository.saveAndFlush(new EditorModel(peladeiroModel, futModel));
+
+ Long id = editorModel.getId();
+
+ assertTrue(editorRepository.findById(id).isPresent());
+ }
+}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/FutRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/FutRepositoryIT.java
new file mode 100644
index 0000000..569aeeb
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/FutRepositoryIT.java
@@ -0,0 +1,78 @@
+package br.com.vemprofut.integration.repositories;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import br.com.vemprofut.configs.OAuth2LoginSuccessHandler;
+import br.com.vemprofut.models.FutModel;
+import br.com.vemprofut.repositories.FutRepository;
+import br.com.vemprofut.services.implementacao.UploadLocalService;
+import jakarta.transaction.Transactional;
+import java.util.List;
+import java.util.Optional;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.bean.override.mockito.MockitoBean;
+
+@SpringBootTest
+@Transactional
+@ActiveProfiles("test")
+public class FutRepositoryIT {
+
+ @MockitoBean private OAuth2AuthorizedClientService authorizedClientService;
+
+ @MockitoBean private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;
+
+ @MockitoBean private ClientRegistrationRepository clientRegistrationRepository;
+
+ @MockitoBean private UploadLocalService uploadLocalService;
+
+ @MockitoBean private JwtDecoder jwtDecoder;
+
+ @Autowired FutRepository futRepository;
+
+ @Test
+ // @DisplayName("deve gerar um Fut e retornar um id")
+ public void deveSalvarFut() {
+
+ FutModel futModel = new FutModel("Fut teste", 4, 10, 2, null, null);
+
+ FutModel salvo = futRepository.save(futModel);
+
+ assertNotNull(salvo.getId());
+ assertTrue(salvo.getId() > 0);
+ }
+
+ @Test
+ // @DisplayName("findById deve retornar Optional vazio para id inexistente")
+ public void findByIdInexistente() {
+ Optional encontrado = futRepository.findById(9999L);
+ assertTrue(encontrado.isEmpty());
+ }
+
+ @Test
+ // @DisplayName("Deve retornar uma lista de Peladeiro")
+ public void findAllDeveRetornaListaFut() {
+ futRepository.saveAndFlush(new FutModel("Fut teste1", 4, 10, 2, null, null));
+ futRepository.saveAndFlush(new FutModel("Fut teste2", 4, 10, 2, null, null));
+
+ List lista = futRepository.findAll();
+ assertTrue(lista.size() >= 2);
+ }
+
+ @Test
+ // @DisplayName("deve deletar um registro")
+ public void deleteFut() {
+ FutModel f = futRepository.saveAndFlush(new FutModel("Fut teste1", 4, 10, 2, null, null));
+
+ Long id = f.getId();
+ futRepository.deleteById(id);
+ assertFalse(futRepository.findById(id).isPresent());
+ }
+
+ // TODO: implementar os testes de Fut buscarFutComListPeladeiros e buscarFutComListEditores
+}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java
new file mode 100644
index 0000000..826b7a5
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java
@@ -0,0 +1,147 @@
+package br.com.vemprofut.integration.repositories;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import br.com.vemprofut.configs.OAuth2LoginSuccessHandler;
+import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.repositories.PeladeiroRepository;
+import br.com.vemprofut.services.implementacao.UploadLocalService;
+import jakarta.transaction.Transactional;
+import java.util.List;
+import java.util.Optional;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.bean.override.mockito.MockitoBean;
+
+@SpringBootTest
+@Transactional
+@ActiveProfiles("test")
+public class PeladeiroRepositoryIT {
+ /*
+ - Isso roda usando MySQL real via Docker
+ - Isso roda com Flyway
+ - Sem mocks — integração real
+
+ Porque:
+ - Garante que o código realmente funciona no mesmo banco da produção.
+ - Evita problemas de comportamento diferente entre H2 <-> MySQL.
+ - Torna o ambiente de Dev ≈ Prod.
+ */
+ // Mocka o serviço que o Spring não está encontrando
+ /*
+ Ao usar o @MockitoBean, você diz ao Spring: Não se preocupe em criar essa dependência real;
+ use um objeto de simulação (mock) no lugar para que o contexto possa ser inicializado.
+ */
+ @MockitoBean private OAuth2AuthorizedClientService authorizedClientService;
+
+ // Opcional: Mocka o próprio Handler para evitar que ele tente rodar lógica
+ @MockitoBean private OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler;
+
+ @MockitoBean private ClientRegistrationRepository clientRegistrationRepository;
+
+ @MockitoBean private UploadLocalService uploadLocalService;
+
+ @MockitoBean private JwtDecoder jwtDecoder;
+
+ @Autowired PeladeiroRepository peladeiroRepository;
+
+ @Test
+ @DisplayName("Deve gerar salvar um paladeiro e retornar um id")
+ public void save_quandoPeladeiroValido_retornaIdGerado() {
+ PeladeiroModel peladeiroModel =
+ new PeladeiroModel(
+ "Marcio Teste", "teste@test.com", "Ronaldo", "o cara nota 10", "81992235678", "Destro");
+
+ PeladeiroModel salvo = peladeiroRepository.save(peladeiroModel);
+
+ assertNotNull(salvo.getId());
+ assertTrue(salvo.getId() > 0);
+ }
+
+ @Test
+ @DisplayName("findById deve retornar Optional vazio para id inexistente")
+ public void findById_quandoIdInexistente_retornaOptionalVazio() {
+ Optional encontrado = peladeiroRepository.findById(9999L);
+ assertTrue(encontrado.isEmpty());
+ }
+
+ @Test
+ @DisplayName("findAll deve retornar lista com todos os Peladeiros")
+ public void findAll_quandoExistemRegistros_retornaListaComTodos() {
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", "Destro"));
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("B", "b@test.com", "B", "444", "82000000000", "Destro"));
+
+ List todos = peladeiroRepository.findAll();
+ assertTrue(todos.size() >= 2);
+ }
+
+ @Test
+ @DisplayName("deleteById deve remover um registro existente")
+ public void deleteById_quandoIdExistente_registroEhRemovido() {
+ PeladeiroModel p =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("C", "c@test.com", "C", "", "3", "Destro"));
+ Long id = p.getId();
+ peladeiroRepository.deleteById(id);
+ assertFalse(peladeiroRepository.findById(id).isPresent());
+ }
+
+ @Test
+ @DisplayName("deve retorna de o email ja foi castrado ou nao")
+ public void existsByEmail_quandoEmailCadastrado_retornaTrue() {
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("C", "test@test.com", "C", "", "3", "Destro"));
+ String email = "test@test.com";
+ Boolean exist = peladeiroRepository.existsByEmail(email);
+
+ assertTrue(exist);
+ }
+
+ @Test
+ @DisplayName("deve retorna falso de o email ja foi castrado ou nao")
+ public void existsByEmail_quandoEmailNaoCadastrado_retornaFalse() {
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("C", "test@test.com", "C", "", "3", "Destro"));
+ String email = "test2@test.com";
+ Boolean exist = peladeiroRepository.existsByEmail(email);
+
+ assertFalse(exist);
+ }
+
+ @Test
+ // @DisplayName("Deve retornar um Peladeiro ao pesquisar pelo email")
+ public void buscarPeladeiroPeloEmailRetornaPeladeiro() {
+ PeladeiroModel p =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("C", "test@test.com", "C", "descricao", "377777777777", "Destro"));
+ String email = "test@test.com";
+ PeladeiroModel peladeiroModel = peladeiroRepository.findByEmail(email);
+
+ assertEquals(p.getNome(), peladeiroModel.getNome());
+ assertEquals(p.getEmail(), peladeiroModel.getEmail());
+ assertEquals(p.getApelido(), peladeiroModel.getApelido());
+ assertEquals(p.getWhatsapp(), peladeiroModel.getWhatsapp());
+ assertEquals(p.getDescricao(), peladeiroModel.getDescricao());
+ assertEquals(p.getPeDominante(), peladeiroModel.getPeDominante());
+ }
+
+ @Test
+ // @DisplayName("Deve retornar null ao buscar um peladeiro pelo email")
+ public void buscarPeladeiroPeloEmailRetornaNull() {
+ PeladeiroModel p =
+ peladeiroRepository.saveAndFlush(
+ new PeladeiroModel("C", "test@test.com", "C", "descricao", "377777777777", "Destro"));
+ String email = "test1@test.com";
+ PeladeiroModel peladeiroModel = peladeiroRepository.findByEmail(email);
+
+ assertNull(peladeiroModel);
+ }
+}
diff --git a/VemProFutApi/src/test/resources/application-test.properties b/VemProFutApi/src/test/resources/application-test.properties
new file mode 100644
index 0000000..dd082b7
--- /dev/null
+++ b/VemProFutApi/src/test/resources/application-test.properties
@@ -0,0 +1,12 @@
+# MODE=MySQL = Isso faz o H2 emular a sintaxe do MySQL (tipos, fun\u00E7\u00F5es, etc.), permitindo que suas migra\u00E7\u00F5es rodem sem precisar reescrev\u00EA-las.
+spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
+spring.datasource.driver-class-name=org.h2.Driver
+spring.datasource.username=sa
+spring.datasource.password=
+
+spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
+spring.jpa.hibernate.ddl-auto=none
+
+# Flyway
+spring.flyway.enabled=true
+spring.flyway.locations=classpath:db/migration
From b649173489bb7472e25dd0b9ece01963e6aaccb7 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Mon, 15 Dec 2025 23:17:42 -0300
Subject: [PATCH 09/13] Clean up comments in CI Develop workflow (#14)
Removed comments about the workflow's purpose and third-party actions.
---
.github/workflows/ci-develop.yml | 8 --------
1 file changed, 8 deletions(-)
diff --git a/.github/workflows/ci-develop.yml b/.github/workflows/ci-develop.yml
index f2ef092..ba2f8ec 100644
--- a/.github/workflows/ci-develop.yml
+++ b/.github/workflows/ci-develop.yml
@@ -1,11 +1,3 @@
-# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
-# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
-
-# This workflow uses actions that are not certified by GitHub.
-# They are provided by a third-party and are governed by
-# separate terms of service, privacy policy, and support
-# documentation.
-
name: CI Develop
on:
From 1f8b02cf58ea1e2af658478c02d76f01cfbb9245 Mon Sep 17 00:00:00 2001
From: "Marcio J. Costa" <87935294+MarcioCosta013@users.noreply.github.com>
Date: Fri, 2 Jan 2026 12:43:54 -0300
Subject: [PATCH 10/13] Feature/create testes unitarios (#15) (#16)
* test(test unitario create peladeiro):
- Primeiro teste unitario create peladeiro
- Adicionei a depencia e o plugin para adicionar o mockito como Java Agent ja preparando para mudancas futuras do JDK;
- Usando o AssertJ para os Testes unitarios
* test(PeladeiroServiceTest):
- concluida a implementacao dos testes de PeladeiroService;
- algumas modificacoes pontuais em PeladeiroService sem mudar no comportamento do codigo;
- adicionei anotacoes lombok no CartoesResumoResponse em controlles/response para adicionar um contrutor com todos os argumentos;
* refactore(Trocando string por PeDominanteEnum):
- troquei todas as implementacoes de PeDominate que estavam em tipo string para usar o Enum PeDominante;
* doc(Adicionando informacoes ao readme.md):
-Adicionei como fazer para rodar o projeto em diferentes config: test, prod e dev;
---
VemProFutApi/README.md | 52 ++-
VemProFutApi/pom.xml | 16 +-
.../configs/OAuth2LoginSuccessHandler.java | 3 +-
.../request/SavePeladeiroRequestDTO.java | 3 +-
.../request/UpdatePeladeiroRequestDTO.java | 3 +-
.../response/CartoesResumoResponseDTO.java | 4 +
.../response/PeladeiroDetailResponse.java | 3 +-
.../response/SavePeladeiroResponseDTO.java | 3 +-
.../response/UpdatePeladeiroResponseDTO.java | 3 +-
.../com/vemprofut/models/PeladeiroModel.java | 6 +-
.../implementacao/PeladeiroService.java | 10 +-
.../vemprofut/VemProFutApplicationTests.java | 8 +-
.../repositories/BanimentoRepositoryIT.java | 9 +-
.../repositories/CartoesRepositoryIT.java | 27 +-
.../repositories/EditorRepositoryIT.java | 5 +-
.../repositories/GolsPartidaRepositoryIT.java | 23 +-
.../repositories/PeladeiroRepositoryIT.java | 24 +-
.../unit/services/FutServiceTest.java | 205 ++++++++++++
.../unit/services/PeladeiroServiceTest.java | 303 ++++++++++++++++++
19 files changed, 647 insertions(+), 63 deletions(-)
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/unit/services/FutServiceTest.java
create mode 100644 VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java
diff --git a/VemProFutApi/README.md b/VemProFutApi/README.md
index 0f08e16..dc74b21 100644
--- a/VemProFutApi/README.md
+++ b/VemProFutApi/README.md
@@ -1,4 +1,4 @@
-# VemProFut! API (Em andamento...)
+# VemProFut! API (Concluída)



@@ -6,4 +6,54 @@
API base de todo o projeto VemProFut!
+## Organização das pastas:
+
+```
+ VemProFutApi/
+ ├── src/ → Código-fonte principal da aplicação
+ │ ├── main/java/... → Classes Java (controllers, services, repositories, models)
+ │ ├── main/resources → Configurações (application.properties, templates, static)
+ │ └── test/java/... → Testes automatizados
+ │
+ ├── mysql-init/ → Scripts de inicialização do banco MySQL
+ │ └── *.sql → Criação de tabelas, inserts iniciais
+ │
+ ├── .mvn/wrapper/ → Arquivos do Maven Wrapper (executar sem instalar Maven)
+ │
+ ├── Dockerfile → Configuração para criar imagem Docker da API
+ ├── Docker-compose.yml → Orquestração de containers (API + MySQL)
+ │
+ ├── pom.xml → Arquivo de configuração do Maven (dependências e build)
+ ├── mvnw / mvnw.cmd → Scripts para rodar Maven Wrapper (Linux/Windows)
+ │
+ ├── .env.exemple → Exemplo de variáveis de ambiente (configuração DB, etc.)
+ ├── .gitignore → Arquivos/pastas ignorados pelo Git
+ ├── .gitattributes → Configurações de atributos do Git
+ ├── excludeFilter.xml → Configuração de exclusões (provavelmente Sonar ou Checkstyle)
+ └── README.md → Documentação inicial da API
+```
+
+# 🚀 Como rodar a aplicação
+
+A aplicação suporta múltiplos perfis (`dev`, `test`, `prod`) configurados via **Spring Profiles**.
+
+---
+## 🏭 Ambiente de Produção (`prod`)
+
+Rodar com **Docker Compose**:
+```bash
+docker compose up
+```
+## 🔧 Ambiente de Desenvolvimento (`dev`)
+
+Rodar diretamente com **Maven**:
+```bash
+mvn spring-boot:run -Dspring-boot.run.profiles=dev
+```
+## 🧪 Ambiente de Testes (`test`)
+
+Rodar diretamente com **Maven**:
+```bash
+mvn test
+```
diff --git a/VemProFutApi/pom.xml b/VemProFutApi/pom.xml
index fa31b61..49ef2cb 100644
--- a/VemProFutApi/pom.xml
+++ b/VemProFutApi/pom.xml
@@ -134,12 +134,12 @@
test
+
- junit
- junit
- test
+ org.mockito
+ mockito-inline
+ 5.2.0
-
@@ -220,6 +220,14 @@
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.2.5
+
+
+
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java b/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java
index 1381d0d..f4aa470 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/configs/OAuth2LoginSuccessHandler.java
@@ -3,6 +3,7 @@
import br.com.vemprofut.mappers.IHistoricoPeladeiroMapper;
import br.com.vemprofut.models.DTOs.HistoricoPeladeiroDTO;
import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
import br.com.vemprofut.repositories.PeladeiroRepository;
import br.com.vemprofut.services.IHistoricoPeladeiroService;
import jakarta.servlet.http.HttpServletRequest;
@@ -62,7 +63,7 @@ public void onAuthenticationSuccess(
usuario.setApelido(name);
usuario.setDescricao("Usuário criado via OAuth2");
usuario.setWhatsapp("000000000");
- usuario.setPeDominante("Destro"); // escolha padrão
+ usuario.setPeDominante(PeDominante.DESTRO); // escolha padrão
usuario.setAuthProvider(provider);
usuario.setFotoUrl(picture);
usuario.setHistoricoPeladeiro(historicoPeladeiroMapper.toModel(historicoPeladeiro));
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SavePeladeiroRequestDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SavePeladeiroRequestDTO.java
index 2fda2d0..cce4520 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SavePeladeiroRequestDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/SavePeladeiroRequestDTO.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.controllers.request;
+import br.com.vemprofut.models.enuns.PeDominante;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
@@ -9,5 +10,5 @@ public record SavePeladeiroRequestDTO(
@Email String email,
@NotNull String apelido,
@NotBlank String descricao,
- @NotNull String peDominante,
+ @NotNull PeDominante peDominante,
@NotBlank String whatsapp) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/UpdatePeladeiroRequestDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/UpdatePeladeiroRequestDTO.java
index 8fbb2a3..c86dd68 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/UpdatePeladeiroRequestDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/request/UpdatePeladeiroRequestDTO.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.controllers.request;
+import br.com.vemprofut.models.enuns.PeDominante;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
@@ -9,5 +10,5 @@ public record UpdatePeladeiroRequestDTO(
@Email String email,
@NotNull String apelido,
@NotBlank String descricao,
- @NotNull String peDominante,
+ @NotNull PeDominante peDominante,
@NotBlank String whatsapp) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResumoResponseDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResumoResponseDTO.java
index cdc453a..356778f 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResumoResponseDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/CartoesResumoResponseDTO.java
@@ -1,10 +1,14 @@
package br.com.vemprofut.controllers.response;
+import lombok.AllArgsConstructor;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
+@NoArgsConstructor
+@AllArgsConstructor
public class CartoesResumoResponseDTO {
private Integer azul;
private Integer amarelo;
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/PeladeiroDetailResponse.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/PeladeiroDetailResponse.java
index 746c8dc..8a9545c 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/PeladeiroDetailResponse.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/PeladeiroDetailResponse.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.controllers.response;
+import br.com.vemprofut.models.enuns.PeDominante;
import com.fasterxml.jackson.annotation.JsonProperty;
public record PeladeiroDetailResponse(
@@ -9,5 +10,5 @@ public record PeladeiroDetailResponse(
@JsonProperty("apelido") String apelido,
@JsonProperty("descricao") String descricao,
@JsonProperty("whatsapp") String whatsapp,
- @JsonProperty("peDominante") String peDominante,
+ @JsonProperty("peDominante") PeDominante peDominante,
@JsonProperty("numeroCartoes") CartoesResumoResponseDTO cartoes) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java
index 64a52b3..e8162d2 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/SavePeladeiroResponseDTO.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.controllers.response;
+import br.com.vemprofut.models.enuns.PeDominante;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@@ -9,7 +10,7 @@ public record SavePeladeiroResponseDTO(
@JsonProperty("email") String email,
@JsonProperty("apelido") String apelido,
@JsonProperty("descricao") String descricao,
- @JsonProperty("peDominante") String peDominante,
+ @JsonProperty("peDominante") PeDominante peDominante,
@JsonProperty("whatsapp") String whatsapp,
@JsonProperty("historicoPeladeiro") Long historicoPeladeiro,
@JsonProperty("fotoUrl") String fotoUrl,
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java
index 02fcf35..515bf17 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/response/UpdatePeladeiroResponseDTO.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.controllers.response;
+import br.com.vemprofut.models.enuns.PeDominante;
import com.fasterxml.jackson.annotation.JsonProperty;
public record UpdatePeladeiroResponseDTO(
@@ -8,5 +9,5 @@ public record UpdatePeladeiroResponseDTO(
@JsonProperty("apelido") String apelido,
@JsonProperty("descricao") String descricao,
@JsonProperty("whatsapp") String whatsapp,
- @JsonProperty("peDominante") String peDominante,
+ @JsonProperty("peDominante") PeDominante peDominante,
@JsonProperty("fotoURL") String fotoUrl) {}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java b/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java
index bd1176c..85b8ec8 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/models/PeladeiroModel.java
@@ -1,5 +1,6 @@
package br.com.vemprofut.models;
+import br.com.vemprofut.models.enuns.PeDominante;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@@ -19,7 +20,7 @@ public PeladeiroModel(
String apelido,
String descricao,
String whatsapp,
- String peDominante) {
+ PeDominante peDominante) {
this.nome = nome;
this.email = email;
this.apelido = apelido;
@@ -49,7 +50,8 @@ public PeladeiroModel(
private String whatsapp;
@Column(name = "pe_dominante_peladeiro", nullable = false, length = 10)
- private String peDominante;
+ @Enumerated(EnumType.STRING) // salva como texto no banco
+ private PeDominante peDominante; // TODO: mudar para usar um enum...
@ToString.Exclude
@OneToOne
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
index 7f894dd..0201483 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
@@ -29,7 +29,7 @@ public class PeladeiroService implements IPeladeiroService {
@Autowired private PeladeiroRepository repository;
- @Autowired private IPeladeiroMapper IPeladeiroMapper;
+ @Autowired private IPeladeiroMapper peladeiroMapper;
@Autowired private IHistoricoPeladeiroMapper historicoMapper;
@@ -42,14 +42,14 @@ public class PeladeiroService implements IPeladeiroService {
public SavePeladeiroResponseDTO create(SavePeladeiroRequestDTO dto) {
queryService.verifyEmail(dto.email());
log.info("Email verificado!");
- PeladeiroModel peladeiroModel = IPeladeiroMapper.saveRequestToModel(dto);
+ PeladeiroModel peladeiroModel = peladeiroMapper.saveRequestToModel(dto);
PeladeiroModel peladeiroSalvo = repository.save(peladeiroModel);
HistoricoPeladeiroDTO historico = historicoPeladeiroService.create();
peladeiroSalvo.setHistoricoPeladeiro(historicoMapper.toModel(historico));
log.info("Peladeiro cadastrado com sucesso!");
- return IPeladeiroMapper.modelToSaveResponse(repository.save(peladeiroSalvo));
+ return peladeiroMapper.modelToSaveResponse(repository.save(peladeiroSalvo));
}
@Override
@@ -66,7 +66,7 @@ public UpdatePeladeiroResponseDTO update(Long id, UpdatePeladeiroRequestDTO dto)
peladeiroModel.setPeDominante(dto.peDominante());
log.info("Peladeiro alterado com sucesso!");
- return IPeladeiroMapper.modelToUpdateResponse(repository.save(peladeiroModel));
+ return peladeiroMapper.modelToUpdateResponse(repository.save(peladeiroModel));
}
@Override
@@ -99,7 +99,7 @@ public PeladeiroModel findByIdModel(Long id) {
//
// return repository.findAll()
// .stream()
- // .map(IPeladeiroMapper::toDTO)
+ // .map(peladeiroMapper::toDTO)
// .toList();
// }
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java b/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java
index 5f15b0d..5b58373 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/VemProFutApplicationTests.java
@@ -1,12 +1,6 @@
package br.com.vemprofut;
-import org.springframework.boot.test.context.SpringBootTest;
-
-
class VemProFutApplicationTests {
-
- void contextLoads() {
- }
-
+ void contextLoads() {}
}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java
index 19f9e2c..74198e6 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/BanimentoRepositoryIT.java
@@ -6,6 +6,7 @@
import br.com.vemprofut.models.BanimentoModel;
import br.com.vemprofut.models.FutModel;
import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
import br.com.vemprofut.repositories.BanimentoRepository;
import br.com.vemprofut.repositories.FutRepository;
import br.com.vemprofut.repositories.PeladeiroRepository;
@@ -57,7 +58,7 @@ public void save_quandoBanimentoValido_retornaIdGerado() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
BanimentoModel banimentoModel =
new BanimentoModel(
@@ -86,7 +87,7 @@ public void findAll_quandoExistemRegistros_retornaListaComTodos() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
new PeladeiroModel(
@@ -95,7 +96,7 @@ public void findAll_quandoExistemRegistros_retornaListaComTodos() {
"Apelido2",
"descricao qualquer2",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
BanimentoModel banimentoModel1 =
new BanimentoModel(
@@ -132,7 +133,7 @@ public void deleteById_quandoIdBanimentoExistir_registroRemovido() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
BanimentoModel banimentoModel =
new BanimentoModel(
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java
index a79912a..b8a0bc9 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/CartoesRepositoryIT.java
@@ -8,6 +8,7 @@
import br.com.vemprofut.models.FutModel;
import br.com.vemprofut.models.PartidasModel;
import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
import br.com.vemprofut.models.enuns.TipoCartao;
import br.com.vemprofut.repositories.CartoesRepository;
import br.com.vemprofut.repositories.FutRepository;
@@ -69,7 +70,7 @@ void save_quandoCartaoValido_retornaIdGerado() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
CartoesModel cartoesModel =
cartoesRepository.saveAndFlush(
@@ -96,7 +97,7 @@ void findAll_quandoCartoesExistem_retornaListaCartao() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
@@ -106,7 +107,7 @@ void findAll_quandoCartoesExistem_retornaListaCartao() {
"Apelido",
"descricao qualquer2",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
cartoesRepository.saveAndFlush(
new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
@@ -134,7 +135,7 @@ void findById_quandoCartaoExiste_retornaCartao() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
CartoesModel cartoesModel =
cartoesRepository.saveAndFlush(
@@ -160,7 +161,7 @@ void findById_quandoCartaoExiste_retornaOptinalVazio() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
CartoesModel cartoesModel =
cartoesRepository.saveAndFlush(
@@ -186,7 +187,7 @@ void findByPeladeiro_quandoCartoesDoPeladeiroExistem_retornaListCartoes() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
@@ -196,7 +197,7 @@ void findByPeladeiro_quandoCartoesDoPeladeiroExistem_retornaListCartoes() {
"Apelido",
"descricao qualquer2",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
cartoesRepository.saveAndFlush(
new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
@@ -228,7 +229,7 @@ void findByPartida_quandoCartoesExistem_retornaListCartoes() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
cartoesRepository.saveAndFlush(
new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
@@ -260,7 +261,7 @@ void findByFut_quandoCartoesExistem_retornaListCartoes() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
cartoesRepository.saveAndFlush(
new CartoesModel(partidasModel, peladeiroModel, futModel, TipoCartao.AMARELO));
@@ -288,7 +289,7 @@ void countByTipoAndPeladeiro_quandoCartoesExistem_retornaListCartoesPeladeiroCon
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
@@ -298,7 +299,7 @@ void countByTipoAndPeladeiro_quandoCartoesExistem_retornaListCartoesPeladeiroCon
"Apelido",
"descricao qualquer2",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
FutModel futModel = futRepository.saveAndFlush(new FutModel());
FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
@@ -361,7 +362,7 @@ void countByTipoAndFut__quandoCartoesExistem_retornaListCartoesFutContado() {
"Apelido",
"descricao qualquer",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
@@ -371,7 +372,7 @@ void countByTipoAndFut__quandoCartoesExistem_retornaListCartoesFutContado() {
"Apelido",
"descricao qualquer2",
"81999999999",
- "Destro"));
+ PeDominante.DESTRO));
FutModel futModel = futRepository.saveAndFlush(new FutModel());
FutModel futModel2 = futRepository.saveAndFlush(new FutModel());
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java
index a06fb0d..13a5763 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/EditorRepositoryIT.java
@@ -6,6 +6,7 @@
import br.com.vemprofut.models.EditorModel;
import br.com.vemprofut.models.FutModel;
import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
import br.com.vemprofut.repositories.EditorRepository;
import br.com.vemprofut.repositories.FutRepository;
import br.com.vemprofut.repositories.PeladeiroRepository;
@@ -56,7 +57,7 @@ void save_quandoEditorValido_retornaEditorSalvo() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.CANHOTO));
EditorModel editorModel =
editorRepository.saveAndFlush(new EditorModel(peladeiroModel, futModel));
@@ -78,7 +79,7 @@ void findById_quandoEditorExiste_retornaEditorSalvo() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.CANHOTO));
EditorModel editorModel =
editorRepository.saveAndFlush(new EditorModel(peladeiroModel, futModel));
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/GolsPartidaRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/GolsPartidaRepositoryIT.java
index 12aacbb..254eabc 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/GolsPartidaRepositoryIT.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/GolsPartidaRepositoryIT.java
@@ -6,6 +6,7 @@
import br.com.vemprofut.models.GolsPartidaModel;
import br.com.vemprofut.models.PartidasModel;
import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
import br.com.vemprofut.repositories.GolsPartidaRepository;
import br.com.vemprofut.repositories.PartidasRepository;
import br.com.vemprofut.repositories.PeladeiroRepository;
@@ -54,7 +55,7 @@ void save_quandoGolPartidaValido_retornaGolPartidaSalvo() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
GolsPartidaModel golsPartidaSalvo =
@@ -75,7 +76,7 @@ void findById_quandoGolPartidaExiste_retornaGolPartidaModel() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
GolsPartidaModel golsPartidaSalvo =
golsPartidaRepository.save(new GolsPartidaModel(peladeiroSalvo, partidasSalvo));
@@ -95,7 +96,7 @@ void findById_quandoGolPartidaInexistente_retornaNull() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
golsPartidaRepository.save(new GolsPartidaModel(peladeiroSalvo, partidasSalvo));
@@ -113,7 +114,7 @@ void existsById_quandoGolPartidaExiste_retornaTrue() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
GolsPartidaModel golsPartidaSalvo =
golsPartidaRepository.save(new GolsPartidaModel(peladeiroSalvo, partidasSalvo));
@@ -133,7 +134,7 @@ void existsById_quandoGolPartidaExiste_retornaFalse() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
golsPartidaRepository.save(new GolsPartidaModel(peladeiroSalvo, partidasSalvo));
@@ -152,7 +153,7 @@ void findAll_quandoExitemGolPartidas_retornaListGolPartidaModel() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
golsPartidaRepository.saveAndFlush(new GolsPartidaModel(peladeiroSalvo, partidasSalvo));
}
@@ -173,10 +174,10 @@ void findByPeladeiro_quandoGolPartidaExistirem_retornaListaGolPartidas() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", "Destro"));
+ new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
PartidasModel partidasSalvo2 = partidasRepository.saveAndFlush(new PartidasModel());
@@ -210,10 +211,10 @@ void findByPartida_quandoGolPartidaExistirem_retornaListaGolPartidas() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PeladeiroModel peladeiroModel2 =
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", "Destro"));
+ new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
PartidasModel partidasSalvo2 = partidasRepository.saveAndFlush(new PartidasModel());
@@ -247,7 +248,7 @@ void deleteById_quandoGolsPartidaExistir() {
"Ronaldo",
"o cara nota 10",
"81992235678",
- "Destro"));
+ PeDominante.DESTRO));
PartidasModel partidasSalvo = partidasRepository.saveAndFlush(new PartidasModel());
GolsPartidaModel golsPartidaSalvo =
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java
index 826b7a5..e4e693b 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/integration/repositories/PeladeiroRepositoryIT.java
@@ -4,6 +4,7 @@
import br.com.vemprofut.configs.OAuth2LoginSuccessHandler;
import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
import br.com.vemprofut.repositories.PeladeiroRepository;
import br.com.vemprofut.services.implementacao.UploadLocalService;
import jakarta.transaction.Transactional;
@@ -56,7 +57,12 @@ public class PeladeiroRepositoryIT {
public void save_quandoPeladeiroValido_retornaIdGerado() {
PeladeiroModel peladeiroModel =
new PeladeiroModel(
- "Marcio Teste", "teste@test.com", "Ronaldo", "o cara nota 10", "81992235678", "Destro");
+ "Marcio Teste",
+ "teste@test.com",
+ "Ronaldo",
+ "o cara nota 10",
+ "81992235678",
+ PeDominante.DESTRO);
PeladeiroModel salvo = peladeiroRepository.save(peladeiroModel);
@@ -75,9 +81,9 @@ public void findById_quandoIdInexistente_retornaOptionalVazio() {
@DisplayName("findAll deve retornar lista com todos os Peladeiros")
public void findAll_quandoExistemRegistros_retornaListaComTodos() {
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", "Destro"));
+ new PeladeiroModel("A", "a@test.com", "A", "333", "81555555555", PeDominante.DESTRO));
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("B", "b@test.com", "B", "444", "82000000000", "Destro"));
+ new PeladeiroModel("B", "b@test.com", "B", "444", "82000000000", PeDominante.DESTRO));
List todos = peladeiroRepository.findAll();
assertTrue(todos.size() >= 2);
@@ -88,7 +94,7 @@ public void findAll_quandoExistemRegistros_retornaListaComTodos() {
public void deleteById_quandoIdExistente_registroEhRemovido() {
PeladeiroModel p =
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("C", "c@test.com", "C", "", "3", "Destro"));
+ new PeladeiroModel("C", "c@test.com", "C", "", "3", PeDominante.DESTRO));
Long id = p.getId();
peladeiroRepository.deleteById(id);
assertFalse(peladeiroRepository.findById(id).isPresent());
@@ -98,7 +104,7 @@ public void deleteById_quandoIdExistente_registroEhRemovido() {
@DisplayName("deve retorna de o email ja foi castrado ou nao")
public void existsByEmail_quandoEmailCadastrado_retornaTrue() {
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("C", "test@test.com", "C", "", "3", "Destro"));
+ new PeladeiroModel("C", "test@test.com", "C", "", "3", PeDominante.DESTRO));
String email = "test@test.com";
Boolean exist = peladeiroRepository.existsByEmail(email);
@@ -109,7 +115,7 @@ public void existsByEmail_quandoEmailCadastrado_retornaTrue() {
@DisplayName("deve retorna falso de o email ja foi castrado ou nao")
public void existsByEmail_quandoEmailNaoCadastrado_retornaFalse() {
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("C", "test@test.com", "C", "", "3", "Destro"));
+ new PeladeiroModel("C", "test@test.com", "C", "", "3", PeDominante.DESTRO));
String email = "test2@test.com";
Boolean exist = peladeiroRepository.existsByEmail(email);
@@ -121,7 +127,8 @@ public void existsByEmail_quandoEmailNaoCadastrado_retornaFalse() {
public void buscarPeladeiroPeloEmailRetornaPeladeiro() {
PeladeiroModel p =
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("C", "test@test.com", "C", "descricao", "377777777777", "Destro"));
+ new PeladeiroModel(
+ "C", "test@test.com", "C", "descricao", "377777777777", PeDominante.DESTRO));
String email = "test@test.com";
PeladeiroModel peladeiroModel = peladeiroRepository.findByEmail(email);
@@ -138,7 +145,8 @@ public void buscarPeladeiroPeloEmailRetornaPeladeiro() {
public void buscarPeladeiroPeloEmailRetornaNull() {
PeladeiroModel p =
peladeiroRepository.saveAndFlush(
- new PeladeiroModel("C", "test@test.com", "C", "descricao", "377777777777", "Destro"));
+ new PeladeiroModel(
+ "C", "test@test.com", "C", "descricao", "377777777777", PeDominante.DESTRO));
String email = "test1@test.com";
PeladeiroModel peladeiroModel = peladeiroRepository.findByEmail(email);
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/FutServiceTest.java b/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/FutServiceTest.java
new file mode 100644
index 0000000..0d6d866
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/FutServiceTest.java
@@ -0,0 +1,205 @@
+package br.com.vemprofut.unit.services;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
+import static org.mockito.Mockito.*;
+
+import br.com.vemprofut.controllers.request.SaveFutRequestDTO;
+import br.com.vemprofut.controllers.response.FutDetailsResponse;
+import br.com.vemprofut.controllers.response.SaveFutResponseDTO;
+import br.com.vemprofut.exceptions.NomeInUseException;
+import br.com.vemprofut.exceptions.NotFoundException;
+import br.com.vemprofut.mappers.IEditorMapper;
+import br.com.vemprofut.mappers.IFutMapper;
+import br.com.vemprofut.mappers.IPartidasMapper;
+import br.com.vemprofut.mappers.IPeladeiroMapper;
+import br.com.vemprofut.models.DTOs.FutDTO;
+import br.com.vemprofut.models.FutModel;
+import br.com.vemprofut.models.HistoricoFutModel;
+import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.repositories.*;
+import br.com.vemprofut.services.IBanimentoService;
+import br.com.vemprofut.services.IEditorService;
+import br.com.vemprofut.services.IHistoricoFutService;
+import br.com.vemprofut.services.IPartidasService;
+import br.com.vemprofut.services.implementacao.FutService;
+import br.com.vemprofut.services.query.IFutQueryService;
+import br.com.vemprofut.services.query.IPeladeiroQueryService;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+@ExtendWith(MockitoExtension.class)
+public class FutServiceTest {
+
+ @Mock private IFutQueryService queryService;
+ @Mock private IFutMapper mapper;
+ @Mock private IPartidasMapper partidasMapper;
+ @Mock private FutRepository repository;
+ @Mock private IPartidasService partidasService;
+ @Mock private PartidasRepository partidasRepository;
+ @Mock private IPeladeiroQueryService peladeiroQueryService;
+ @Mock private PeladeiroRepository peladeiroRepository;
+ @Mock private IPeladeiroMapper peladeiroMapper;
+ @Mock private IHistoricoFutService historicoFutService;
+ @Mock private CartoesRepository cartoesRepository;
+ @Mock private GolsPartidaRepository golsRepository;
+ @Mock private IEditorService editorService;
+ @Mock private IEditorMapper editorMapper;
+ @Mock private IBanimentoService banidoService;
+
+ @InjectMocks private FutService futService;
+
+ FutModel futModel;
+ PeladeiroModel peladeiroModel;
+ HistoricoFutModel historicoFutModel;
+
+ @BeforeEach
+ void setup() {
+ MockitoAnnotations.openMocks(this);
+ peladeiroModel = new PeladeiroModel();
+ peladeiroModel.setId(1L);
+ peladeiroModel.setNome("Marcio");
+ peladeiroModel.setEmail("marcio-costa@gmail.com");
+
+ historicoFutModel = new HistoricoFutModel();
+ historicoFutModel.setId(1L);
+
+ futModel = new FutModel();
+ futModel.setId(1L);
+ futModel.setNome("Fut teste");
+ futModel.setAdministradorPeladeiro(peladeiroModel);
+ }
+
+ // ======================== CRUD basico ==========================
+ @Test
+ @DisplayName("Deve criar e salvar um novo Fut")
+ void create_quandoFutValido_retornaFutSalvo() {
+ // Arrange:
+ SaveFutRequestDTO saveFutRequestDTO = new SaveFutRequestDTO("Fut teste", 4, 10, 2, 1L);
+
+ SaveFutResponseDTO saveFutResponseDTO =
+ new SaveFutResponseDTO(
+ 1L, "Fut teste", 4, 10, 2, historicoFutModel.getId(), peladeiroModel.getId());
+
+ doNothing().when(queryService).verifyNomeFutExist(futModel.getNome());
+ when(peladeiroQueryService.verifyPeladeiroExist(saveFutRequestDTO.administradorPeladeiro()))
+ .thenReturn(peladeiroModel);
+ when(mapper.saveRequestToModel(saveFutRequestDTO)).thenReturn(futModel);
+ when(repository.save(futModel)).thenReturn(futModel);
+ when(historicoFutService.create()).thenReturn(historicoFutModel);
+ when(mapper.toSaveResponse(futModel)).thenReturn(saveFutResponseDTO);
+
+ // Act:
+ SaveFutResponseDTO response = futService.create(saveFutRequestDTO);
+
+ // Assert:
+ assertThat(response.id()).isNotNull().isEqualTo(1L);
+ assertThat(response.nome()).isEqualTo("Fut teste");
+ assertThat(response.historicoFutId()).isEqualTo(historicoFutModel.getId());
+ assertThat(response.administradorPeladeiro()).isEqualTo(peladeiroModel.getId());
+
+ verify(queryService).verifyNomeFutExist(saveFutRequestDTO.nome());
+ verify(peladeiroQueryService).verifyPeladeiroExist(saveFutRequestDTO.administradorPeladeiro());
+ verify(mapper).saveRequestToModel(saveFutRequestDTO);
+ verify(mapper).toSaveResponse(futModel);
+ verify(repository, times(2)).save(futModel);
+ verify(historicoFutService).create();
+ }
+
+ @Test
+ @DisplayName("Deve retornar erro ao tentar criar um fut")
+ void create_quandoFutInvalido() {
+ // Arrange:
+ SaveFutRequestDTO saveFutRequestDTO = new SaveFutRequestDTO("Fut teste", 4, 10, 2, 1L);
+
+ doThrow(new NomeInUseException("O nome '" + saveFutRequestDTO.nome() + "' já está cadastrado!"))
+ .when(queryService)
+ .verifyNomeFutExist(saveFutRequestDTO.nome());
+
+ // Act + Assert:
+ assertThatThrownBy(() -> futService.create(saveFutRequestDTO))
+ .isInstanceOf(NomeInUseException.class)
+ .hasMessage("O nome '" + saveFutRequestDTO.nome() + "' já está cadastrado!");
+
+ verify(queryService).verifyNomeFutExist(saveFutRequestDTO.nome());
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ @DisplayName("Deve retornar FutDetailsResponse buscando pelo ID")
+ void findById_quandoFutExiste_retornaFutDetailsResponse() {
+
+ // Arrange:
+ FutDetailsResponse futDetailsResponse =
+ new FutDetailsResponse(1L, "Fut teste", 4, 10, 2, 1L, 1L);
+
+ when(queryService.verifyFutExistRetorn(1L)).thenReturn(futModel);
+ when(mapper.modelToDetailsResponse(futModel)).thenReturn(futDetailsResponse);
+
+ // Act:
+ FutDetailsResponse response = futService.findById(1L);
+
+ // Assert
+ assertThat(response.id()).isNotNull().isEqualTo(1L);
+ assertThat(response.nome()).isEqualTo("Fut teste");
+
+ verify(queryService).verifyFutExistRetorn(1L);
+ verify(mapper).modelToDetailsResponse(futModel);
+ }
+
+ @Test
+ @DisplayName("Deve retorna NotFoundException ao buscar pelo ID")
+ void findById_quandoFutInexistente_retornaNotFoundException() {
+
+ // Arrange:
+ FutDetailsResponse futDetailsResponse =
+ new FutDetailsResponse(1L, "Fut teste", 4, 10, 2, 1L, 1L);
+
+ when(queryService.verifyFutExistRetorn(99L))
+ .thenThrow(new NotFoundException("Não foi encontrado o Fut de id " + 99L));
+
+ // Act + Assert
+ assertThatThrownBy(() -> futService.findById(99L))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Não foi encontrado o Fut de id " + 99L);
+ verify(queryService).verifyFutExistRetorn(99L);
+ }
+
+ @Test
+ @DisplayName("Deve buscar Fut pelo Nome")
+ void findByNome_quandoFutExiste_retornaFutDTO() {
+ // Arrange
+ List editores = List.of(3L, 6L, 7L);
+ List peladeiros = List.of(2L, 8L, 3L, 6L, 7L);
+ List cartoes = List.of(1L, 2L, 3L, 5L);
+ FutDTO futDTO = new FutDTO(1L, "Fut Test", 4, 10, 2, 1L, 1L, editores, peladeiros, cartoes);
+
+ when(queryService.verifyNomeFutExistRetorn("Fut Test")).thenReturn(futModel);
+ when(mapper.toDTO(futModel)).thenReturn(futDTO);
+
+ // Act
+ FutDTO response = futService.findByNome("Fut Test");
+
+ // Assert
+ assertThat(response).isNotNull();
+ assertThat(response.id()).isEqualTo(futDTO.id());
+ assertThat(response.nome()).isEqualTo("Fut Test");
+ assertThat(response.editores().size()).isEqualTo(3);
+ assertThat(response.peladeiros().size()).isEqualTo(5);
+ assertThat(response.cartoes().size()).isEqualTo(4);
+
+ verify(queryService).verifyNomeFutExistRetorn("Fut Test");
+ verify(mapper).toDTO(futModel);
+ }
+
+ @Test
+ @DisplayName("Deve buscar um nome de Fut que nao existe e retornar ")
+ void findByNome_quandoFutInexistente_retornaEntityNotFoundException() {}
+}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java b/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java
new file mode 100644
index 0000000..ef9d681
--- /dev/null
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java
@@ -0,0 +1,303 @@
+package br.com.vemprofut.unit.services;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.*;
+
+import br.com.vemprofut.controllers.request.SavePeladeiroRequestDTO;
+import br.com.vemprofut.controllers.request.UpdatePeladeiroRequestDTO;
+import br.com.vemprofut.controllers.response.CartoesResumoResponseDTO;
+import br.com.vemprofut.controllers.response.PeladeiroDetailResponse;
+import br.com.vemprofut.controllers.response.SavePeladeiroResponseDTO;
+import br.com.vemprofut.controllers.response.UpdatePeladeiroResponseDTO;
+import br.com.vemprofut.exceptions.EmailInUseException;
+import br.com.vemprofut.exceptions.NotFoundException;
+import br.com.vemprofut.mappers.IHistoricoPeladeiroMapper;
+import br.com.vemprofut.mappers.IPeladeiroMapper;
+import br.com.vemprofut.models.PeladeiroModel;
+import br.com.vemprofut.models.enuns.PeDominante;
+import br.com.vemprofut.repositories.PeladeiroRepository;
+import br.com.vemprofut.services.ICartoesService;
+import br.com.vemprofut.services.IHistoricoPeladeiroService;
+import br.com.vemprofut.services.implementacao.PeladeiroService;
+import br.com.vemprofut.services.query.IPeladeiroQueryService;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+@ExtendWith(MockitoExtension.class)
+public class PeladeiroServiceTest {
+
+ @Mock private IPeladeiroQueryService queryService;
+ @Mock private PeladeiroRepository repository;
+ @Mock private IPeladeiroMapper peladeiroMapper;
+ @Mock private IHistoricoPeladeiroMapper historicoMapper;
+ @Mock private IHistoricoPeladeiroService historicoPeladeiroService;
+ @Mock private ICartoesService cartoesService;
+
+ @InjectMocks private PeladeiroService peladeiroService;
+
+ PeladeiroModel peladeiroModel;
+
+ @BeforeEach
+ void setup() {
+ MockitoAnnotations.openMocks(this);
+ peladeiroModel = new PeladeiroModel();
+ peladeiroModel.setId(1L);
+ peladeiroModel.setNome("Marcio");
+ peladeiroModel.setEmail("marcio-costa@gmail.com");
+ }
+
+ @Test
+ @DisplayName("Deve Salvar um novo Peladeiro")
+ void create_quandoPeladeiroValido() {
+ // Arrange
+ SavePeladeiroRequestDTO savePeladeiroRequestDTO =
+ new SavePeladeiroRequestDTO(
+ "Marcio",
+ "marcio-costa@gmail.com",
+ "ronaldinho",
+ "o cara forte",
+ PeDominante.DESTRO,
+ "81999999999");
+
+ // cria listas simuladas
+ List partidas = List.of(10L, 20L);
+ List futs = List.of(30L);
+ List cartoes = List.of(40L, 50L);
+
+ doNothing().when(queryService).verifyEmail(savePeladeiroRequestDTO.email());
+ when(peladeiroMapper.saveRequestToModel(savePeladeiroRequestDTO)).thenReturn(peladeiroModel);
+ when(repository.save(peladeiroModel)).thenReturn(peladeiroModel);
+ when(peladeiroMapper.modelToSaveResponse(peladeiroModel))
+ .thenReturn(
+ new SavePeladeiroResponseDTO(
+ 1L,
+ "Marcio",
+ "marcio-costa@gmail.com",
+ "ronaldinho",
+ "o cara forte",
+ PeDominante.DESTRO,
+ "81999999999",
+ 1L,
+ "foto.com/url",
+ partidas,
+ futs,
+ cartoes));
+ // Act
+ SavePeladeiroResponseDTO response = peladeiroService.create(savePeladeiroRequestDTO);
+
+ // Assert
+ assertThat(response.nome()).isEqualTo("Marcio");
+
+ verify(queryService).verifyEmail(savePeladeiroRequestDTO.email());
+ verify(repository, times(2)).save(peladeiroModel);
+ verify(peladeiroMapper).saveRequestToModel(savePeladeiroRequestDTO);
+ verify(peladeiroMapper).modelToSaveResponse(peladeiroModel);
+ }
+
+ @Test
+ @DisplayName("Deve retornar um EmailInUseException por email ja existente")
+ void create_quandoEmailJaCadastrado_retornaEmailInUseException() {
+ // Arrange
+ SavePeladeiroRequestDTO savePeladeiroRequestDTO =
+ new SavePeladeiroRequestDTO(
+ "Marcio",
+ "marcio-costa@gmail.com",
+ "ronaldinho",
+ "o cara forte",
+ PeDominante.DESTRO,
+ "81999999999");
+
+ // cria listas simuladas
+ List partidas = List.of(10L, 20L);
+ List futs = List.of(30L);
+ List cartoes = List.of(40L, 50L);
+
+ doThrow(
+ new EmailInUseException(
+ "O e-mail " + savePeladeiroRequestDTO.email() + " já está em uso"))
+ .when(queryService)
+ .verifyEmail(savePeladeiroRequestDTO.email());
+
+ // Act + Assert
+ assertThatThrownBy(() -> peladeiroService.create(savePeladeiroRequestDTO))
+ .isInstanceOf(EmailInUseException.class)
+ .hasMessage("O e-mail " + savePeladeiroRequestDTO.email() + " já está em uso");
+
+ verify(queryService).verifyEmail(savePeladeiroRequestDTO.email());
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ @DisplayName("Deve fazer uma Alteracao em um Peladeiro ja cadastrado")
+ void update_quandoPeladeiroExiste_retornaPeladeiroAlterado() {
+ // Arrange
+ UpdatePeladeiroRequestDTO requestDTO =
+ new UpdatePeladeiroRequestDTO(
+ "maria",
+ "maria@gmail.com",
+ "mari",
+ "mulher que joga",
+ PeDominante.CANHOTO,
+ "81999993332");
+
+ when(queryService.verifyPeladeiroExist(1L)).thenReturn(peladeiroModel);
+ when(repository.save(peladeiroModel)).thenReturn(peladeiroModel);
+ when(peladeiroMapper.modelToUpdateResponse(peladeiroModel))
+ .thenReturn(
+ new UpdatePeladeiroResponseDTO(
+ "maria",
+ "maria@gmail.com",
+ "mari",
+ "mulher que joga",
+ "81999993332",
+ PeDominante.DESTRO,
+ "foto.com/url"));
+
+ // Act
+ UpdatePeladeiroResponseDTO responseDTO = peladeiroService.update(1L, requestDTO);
+
+ // Assert
+ assertThat(responseDTO).isNotNull();
+ assertThat(responseDTO.nome()).isEqualTo("maria");
+ assertThat(responseDTO.email()).isEqualTo("maria@gmail.com");
+
+ verify(queryService).verifyPeladeiroExist(1L);
+ verify(repository).save(peladeiroModel);
+ }
+
+ @Test
+ @DisplayName("Deve retornar NotFoundException por nao encontrar o Peladeiro pelo ID")
+ void update_quandoPeladeiroInexistente_retornaNotFoundException() {
+ // Arrange
+ UpdatePeladeiroRequestDTO requestDTO =
+ new UpdatePeladeiroRequestDTO(
+ "maria",
+ "maria@gmail.com",
+ "mari",
+ "mulher que joga",
+ PeDominante.CANHOTO,
+ "81999993332");
+
+ when(queryService.verifyPeladeiroExist(99L))
+ .thenThrow(new NotFoundException("Não foi encontrado o Peladeiro de id" + 99L));
+
+ // Act + Assert
+ assertThatThrownBy(() -> peladeiroService.update(99L, requestDTO))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Não foi encontrado o Peladeiro de id" + 99L);
+ verify(queryService).verifyPeladeiroExist(99L);
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ @DisplayName("Deve buscar um peladeiro pelo ID")
+ void findById_quandoPeladeiroExiste_retornaPeladeiroDetailResponse() {
+ // Arrange
+ CartoesResumoResponseDTO cartoesResumoResponseDTO = new CartoesResumoResponseDTO(2, 3, 2);
+ when(queryService.verifyPeladeiroExist(1L)).thenReturn(peladeiroModel);
+ when(cartoesService.contarCartoesPeladeiro(1L)).thenReturn(cartoesResumoResponseDTO);
+
+ // Act
+ PeladeiroDetailResponse peladeiroDetailResponse = peladeiroService.findById(1L);
+
+ // Assert
+ assertThat(peladeiroDetailResponse).isNotNull();
+ assertThat(peladeiroDetailResponse.id()).isEqualTo(1L);
+ assertThat(peladeiroDetailResponse.cartoes().getAzul()).isEqualTo(2);
+ assertThat(peladeiroDetailResponse.cartoes().getAmarelo()).isEqualTo(3);
+ assertThat(peladeiroDetailResponse.cartoes().getVermelho()).isEqualTo(2);
+ assertThat(peladeiroDetailResponse.nome()).isEqualTo("Marcio");
+ assertThat(peladeiroDetailResponse.email()).isEqualTo("marcio-costa@gmail.com");
+
+ verify(queryService).verifyPeladeiroExist(1L);
+ verify(cartoesService).contarCartoesPeladeiro(1L);
+ }
+
+ @Test
+ @DisplayName("Deve buscar um peladeiro pelo ID")
+ void findById_quandoPeladeiroInexistente_retornaNotFoundException() {
+ // Arrange
+ when(queryService.verifyPeladeiroExist(99L))
+ .thenThrow(new NotFoundException("Não foi encontrado o Peladeiro de id " + 99L));
+
+ // Act + Assert
+ assertThatThrownBy(() -> peladeiroService.findById(99L))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Não foi encontrado o Peladeiro de id " + 99L);
+
+ verify(queryService).verifyPeladeiroExist(99L);
+ verifyNoInteractions(
+ repository); // é usando em verifyPeladeiroExist, mas como ele está mockado nao detecta...
+ }
+
+ @Test
+ @DisplayName("")
+ void findByIdModel_quandoPeladeiroExiste_retornaPeladeiroModel() {
+ // Arrenge
+ when(queryService.verifyPeladeiroExist(1L)).thenReturn(peladeiroModel);
+
+ // Act
+ PeladeiroModel response = peladeiroService.findByIdModel(1L);
+
+ // Assert
+ assertThat(response.getId()).isEqualTo(1L);
+ assertThat(response.getNome()).isEqualTo("Marcio");
+ assertThat(response.getEmail()).isEqualTo("marcio-costa@gmail.com");
+
+ verify(queryService).verifyPeladeiroExist(1L);
+ }
+
+ @Test
+ @DisplayName("")
+ void findByIdModel_quandoPeladeiroInexistente_retornaNotFoundException() {
+ // Arrenge
+ when(queryService.verifyPeladeiroExist(99L))
+ .thenThrow(new NotFoundException("Não foi encontrado o Peladeiro de id " + 99L));
+
+ // Act + Assert
+ assertThatThrownBy(() -> peladeiroService.findByIdModel(99L))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Não foi encontrado o Peladeiro de id " + 99L);
+
+ verify(queryService).verifyPeladeiroExist(99L);
+ }
+
+ @Test
+ @DisplayName("Deve apagar o Peladeiro indicado pelo numero do ID")
+ void delete_quandoPeladeiroExiste() {
+ // Arrenge
+ when(queryService.verifyPeladeiroExist(1L)).thenReturn(peladeiroModel);
+ doNothing().when(repository).deleteById(1L);
+
+ // Act
+ peladeiroService.delete(1L);
+
+ // Assert
+ verify(queryService).verifyPeladeiroExist(1L);
+ verify(repository).deleteById(1L);
+ }
+
+ @Test
+ @DisplayName("Deve apagar o Peladeiro indicado pelo numero do ID")
+ void delete_quandoPeladeiroInexistente() {
+ // Arrenge
+ when(queryService.verifyPeladeiroExist(99L))
+ .thenThrow(new NotFoundException("Não foi encontrado o Peladeiro de id " + 99L));
+
+ // Act + Assert
+
+ assertThatThrownBy(() -> peladeiroService.delete(99L))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Não foi encontrado o Peladeiro de id " + 99L);
+
+ verify(queryService).verifyPeladeiroExist(99L);
+ }
+}
From db8e73c2403b3c4b6e3be09fdfba7484b924ea37 Mon Sep 17 00:00:00 2001
From: Marcio Costa
Date: Fri, 2 Jan 2026 13:39:17 -0300
Subject: [PATCH 11/13] feat(Codigo base async): - implementando o primeiro
codigo async da aplicacao;
---
.../com/vemprofut/VemProFutApplication.java | 2 +
.../controllers/PeladeiroController.java | 32 ++++++-----
.../vemprofut/services/IPeladeiroService.java | 15 ++---
.../implementacao/PeladeiroService.java | 56 ++++++++++++-------
.../unit/services/PeladeiroServiceTest.java | 44 ++++++++++++---
5 files changed, 101 insertions(+), 48 deletions(-)
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/VemProFutApplication.java b/VemProFutApi/src/main/java/br/com/vemprofut/VemProFutApplication.java
index 6ea00f4..31f9621 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/VemProFutApplication.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/VemProFutApplication.java
@@ -4,8 +4,10 @@
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
+@EnableAsync
public class VemProFutApplication {
private static final Logger log = LoggerFactory.getLogger(VemProFutApplication.class);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java
index 0e7e4f7..2d14343 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/PeladeiroController.java
@@ -8,6 +8,7 @@
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import java.io.IOException;
+import java.util.concurrent.CompletableFuture;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -26,47 +27,48 @@ public class PeladeiroController {
@Operation(
summary = "Cadastra um novo peladeiro",
tags = {"PeladeiroController"})
- public ResponseEntity create(
+ public CompletableFuture> create(
@Valid @RequestBody final SavePeladeiroRequestDTO requestDTO) {
- var obj = peladeiroService.create(requestDTO);
- return ResponseEntity.status(HttpStatus.CREATED).body(obj);
+
+ return peladeiroService
+ .create(requestDTO)
+ .thenApply(obj -> ResponseEntity.status(HttpStatus.CREATED).body(obj));
}
@GetMapping("{id}")
@Operation(
summary = "Busca um Peladeiro pelo id",
tags = {"PeladeiroController"})
- public ResponseEntity findById(@PathVariable final Long id) {
- var obj = peladeiroService.findById(id);
- return ResponseEntity.ok(obj);
+ public CompletableFuture> findById(
+ @PathVariable final Long id) {
+ return peladeiroService.findById(id).thenApply(ResponseEntity::ok);
}
@PutMapping("{id}")
@Operation(
summary = "Faz alteraçoes no Peladeiro cujo id é informado.",
tags = {"PeladeiroController"})
- public ResponseEntity update(
+ public CompletableFuture> update(
@PathVariable final Long id, @Valid @RequestBody UpdatePeladeiroRequestDTO dto) {
- peladeiroService.update(id, dto);
- return ResponseEntity.noContent().build();
+ return peladeiroService.update(id, dto).thenApply(obj -> ResponseEntity.noContent().build());
}
@DeleteMapping("{id}")
@Operation(
summary = "Deleta o peladeiro cujo id foi informado. Cuidado!",
tags = {"PeladeiroController"})
- public ResponseEntity delete(@PathVariable final Long id) {
- peladeiroService.delete(id);
- return ResponseEntity.noContent().build();
+ public CompletableFuture> delete(@PathVariable final Long id) {
+ return peladeiroService.delete(id).thenApply(obj -> ResponseEntity.noContent().build());
}
@PostMapping(value = "uploadFoto/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Caso nao logado pelo gmail, enviar a foto do perfil",
tags = {"PeladeiroController"})
- public ResponseEntity uploadFotoPeladeiro(
+ public CompletableFuture> uploadFotoPeladeiro(
@PathVariable Long id, @RequestPart("file") MultipartFile file) throws IOException {
- peladeiroService.atualizarFoto(id, file);
- return ResponseEntity.ok("Foto salva!");
+ return peladeiroService
+ .atualizarFoto(id, file)
+ .thenApply(obj -> ResponseEntity.ok("Foto salva!"));
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/IPeladeiroService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/IPeladeiroService.java
index e1366f5..2307de4 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/IPeladeiroService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/IPeladeiroService.java
@@ -6,21 +6,22 @@
import br.com.vemprofut.controllers.response.SavePeladeiroResponseDTO;
import br.com.vemprofut.controllers.response.UpdatePeladeiroResponseDTO;
import br.com.vemprofut.models.PeladeiroModel;
+import java.util.concurrent.CompletableFuture;
import org.springframework.web.multipart.MultipartFile;
public interface IPeladeiroService {
- SavePeladeiroResponseDTO create(SavePeladeiroRequestDTO dto);
+ CompletableFuture create(SavePeladeiroRequestDTO dto);
- UpdatePeladeiroResponseDTO update(Long id, UpdatePeladeiroRequestDTO dto);
+ CompletableFuture update(Long id, UpdatePeladeiroRequestDTO dto);
- PeladeiroDetailResponse findById(Long id);
+ CompletableFuture findById(Long id);
- PeladeiroModel findByIdModel(Long id);
+ CompletableFuture findByIdModel(Long id);
- // List findAll();
+ // CompletableFuture> findAll();
- void delete(Long id);
+ CompletableFuture delete(Long id);
- void atualizarFoto(Long id, MultipartFile file);
+ CompletableFuture atualizarFoto(Long id, MultipartFile file);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
index 0201483..adb541e 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
@@ -15,8 +15,10 @@
import br.com.vemprofut.services.IHistoricoPeladeiroService;
import br.com.vemprofut.services.IPeladeiroService;
import br.com.vemprofut.services.query.IPeladeiroQueryService;
+import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@@ -39,7 +41,7 @@ public class PeladeiroService implements IPeladeiroService {
@Override
@Transactional
- public SavePeladeiroResponseDTO create(SavePeladeiroRequestDTO dto) {
+ public CompletableFuture create(SavePeladeiroRequestDTO dto) {
queryService.verifyEmail(dto.email());
log.info("Email verificado!");
PeladeiroModel peladeiroModel = peladeiroMapper.saveRequestToModel(dto);
@@ -49,12 +51,17 @@ public SavePeladeiroResponseDTO create(SavePeladeiroRequestDTO dto) {
peladeiroSalvo.setHistoricoPeladeiro(historicoMapper.toModel(historico));
log.info("Peladeiro cadastrado com sucesso!");
- return peladeiroMapper.modelToSaveResponse(repository.save(peladeiroSalvo));
+ SavePeladeiroResponseDTO response =
+ peladeiroMapper.modelToSaveResponse(repository.save(peladeiroSalvo));
+
+ return CompletableFuture.completedFuture(response);
}
@Override
@Transactional
- public UpdatePeladeiroResponseDTO update(Long id, UpdatePeladeiroRequestDTO dto) {
+ @Async
+ public CompletableFuture update(
+ Long id, UpdatePeladeiroRequestDTO dto) {
var peladeiroModel = queryService.verifyPeladeiroExist(id);
log.info("Verificado a existencia de Peladeiro");
@@ -66,35 +73,44 @@ public UpdatePeladeiroResponseDTO update(Long id, UpdatePeladeiroRequestDTO dto)
peladeiroModel.setPeDominante(dto.peDominante());
log.info("Peladeiro alterado com sucesso!");
- return peladeiroMapper.modelToUpdateResponse(repository.save(peladeiroModel));
+ UpdatePeladeiroResponseDTO response =
+ peladeiroMapper.modelToUpdateResponse(repository.save(peladeiroModel));
+ return CompletableFuture.completedFuture(response);
}
@Override
@Transactional(readOnly = true)
- public PeladeiroDetailResponse findById(Long id) {
+ @Async
+ public CompletableFuture findById(Long id) {
log.info("Buscando peladeiro pelo id... saida de resposta");
PeladeiroModel retorno = queryService.verifyPeladeiroExist(id);
CartoesResumoResponseDTO resumo = cartoesService.contarCartoesPeladeiro(id);
- return new PeladeiroDetailResponse(
- retorno.getId(),
- retorno.getNome(),
- retorno.getEmail(),
- retorno.getApelido(),
- retorno.getDescricao(),
- retorno.getWhatsapp(),
- retorno.getPeDominante(),
- resumo);
+ var response =
+ new PeladeiroDetailResponse(
+ retorno.getId(),
+ retorno.getNome(),
+ retorno.getEmail(),
+ retorno.getApelido(),
+ retorno.getDescricao(),
+ retorno.getWhatsapp(),
+ retorno.getPeDominante(),
+ resumo);
+
+ return CompletableFuture.completedFuture(response);
}
@Override
@Transactional(readOnly = true)
- public PeladeiroModel findByIdModel(Long id) {
+ @Async
+ public CompletableFuture findByIdModel(Long id) {
log.info("Buscando peladeiro pelo id... saida de uso interno");
- return queryService.verifyPeladeiroExist(id);
+ PeladeiroModel response = queryService.verifyPeladeiroExist(id);
+ return CompletableFuture.completedFuture(response);
}
// @Override
- // @Transactional(readOnly = true)
+ // @Transactional
+ // @Async(readOnly = true)
// public List findAll() {
//
// return repository.findAll()
@@ -105,15 +121,17 @@ public PeladeiroModel findByIdModel(Long id) {
@Override
@Transactional
- public void delete(Long id) {
+ public CompletableFuture delete(Long id) {
queryService.verifyPeladeiroExist(id);
log.info("Existência de Peladeiro confirmada com sucesso!");
repository.deleteById(id);
+ return CompletableFuture.completedFuture(null);
}
@Override
@Transactional
- public void atualizarFoto(Long id, MultipartFile file) {
+ public CompletableFuture atualizarFoto(Long id, MultipartFile file) {
queryService.verifyPeladeiroSaveFile(id, file);
+ return CompletableFuture.completedFuture(null);
}
}
diff --git a/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java b/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java
index ef9d681..bddeffb 100644
--- a/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java
+++ b/VemProFutApi/src/test/java/br/com/vemprofut/unit/services/PeladeiroServiceTest.java
@@ -30,6 +30,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.web.multipart.MultipartFile;
@ExtendWith(MockitoExtension.class)
public class PeladeiroServiceTest {
@@ -91,7 +92,7 @@ void create_quandoPeladeiroValido() {
futs,
cartoes));
// Act
- SavePeladeiroResponseDTO response = peladeiroService.create(savePeladeiroRequestDTO);
+ SavePeladeiroResponseDTO response = peladeiroService.create(savePeladeiroRequestDTO).join();
// Assert
assertThat(response.nome()).isEqualTo("Marcio");
@@ -162,7 +163,7 @@ void update_quandoPeladeiroExiste_retornaPeladeiroAlterado() {
"foto.com/url"));
// Act
- UpdatePeladeiroResponseDTO responseDTO = peladeiroService.update(1L, requestDTO);
+ UpdatePeladeiroResponseDTO responseDTO = peladeiroService.update(1L, requestDTO).join();
// Assert
assertThat(responseDTO).isNotNull();
@@ -206,7 +207,7 @@ void findById_quandoPeladeiroExiste_retornaPeladeiroDetailResponse() {
when(cartoesService.contarCartoesPeladeiro(1L)).thenReturn(cartoesResumoResponseDTO);
// Act
- PeladeiroDetailResponse peladeiroDetailResponse = peladeiroService.findById(1L);
+ PeladeiroDetailResponse peladeiroDetailResponse = peladeiroService.findById(1L).join();
// Assert
assertThat(peladeiroDetailResponse).isNotNull();
@@ -239,13 +240,13 @@ void findById_quandoPeladeiroInexistente_retornaNotFoundException() {
}
@Test
- @DisplayName("")
+ @DisplayName("Deve retornar PeladeiroModel quando ID existe")
void findByIdModel_quandoPeladeiroExiste_retornaPeladeiroModel() {
// Arrenge
when(queryService.verifyPeladeiroExist(1L)).thenReturn(peladeiroModel);
// Act
- PeladeiroModel response = peladeiroService.findByIdModel(1L);
+ PeladeiroModel response = peladeiroService.findByIdModel(1L).join();
// Assert
assertThat(response.getId()).isEqualTo(1L);
@@ -256,7 +257,7 @@ void findByIdModel_quandoPeladeiroExiste_retornaPeladeiroModel() {
}
@Test
- @DisplayName("")
+ @DisplayName("Deve retornar erro NotFoundException quando ID nao existe")
void findByIdModel_quandoPeladeiroInexistente_retornaNotFoundException() {
// Arrenge
when(queryService.verifyPeladeiroExist(99L))
@@ -278,7 +279,7 @@ void delete_quandoPeladeiroExiste() {
doNothing().when(repository).deleteById(1L);
// Act
- peladeiroService.delete(1L);
+ peladeiroService.delete(1L).join();
// Assert
verify(queryService).verifyPeladeiroExist(1L);
@@ -300,4 +301,33 @@ void delete_quandoPeladeiroInexistente() {
verify(queryService).verifyPeladeiroExist(99L);
}
+
+ @Test
+ @DisplayName("Deve atualizar a foto do Peladeiro")
+ void atualizarFoto_quandoPeladeiroExiste() {
+ MultipartFile file = mock(MultipartFile.class);
+
+ doNothing().when(queryService).verifyPeladeiroSaveFile(1L, file);
+ peladeiroService.atualizarFoto(1L, file).join();
+
+ verify(queryService).verifyPeladeiroSaveFile(1L, file);
+ }
+
+ @Test
+ @DisplayName("Deve lançar NotFoundException ao tentar atualizar foto de Peladeiro inexistente")
+ void atualizarFoto_quandoPeladeiroInexistente_retornaNotFoundException() {
+ MultipartFile file = mock(MultipartFile.class);
+
+ // Arrange: simula que o queryService lança exceção
+ doThrow(new NotFoundException("Não foi encontrado o Peladeiro de id 99"))
+ .when(queryService)
+ .verifyPeladeiroSaveFile(99L, file);
+
+ // Act + Assert
+ assertThatThrownBy(() -> peladeiroService.atualizarFoto(99L, file).join())
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Não foi encontrado o Peladeiro de id 99");
+
+ verify(queryService).verifyPeladeiroSaveFile(99L, file);
+ }
}
From 5d59ae88a47bc41c77aeeb3bc335c0c0c4dd9730 Mon Sep 17 00:00:00 2001
From: Marcio Costa
Date: Sun, 4 Jan 2026 01:54:21 -0300
Subject: [PATCH 12/13] =?UTF-8?q?refactore(primeiro=20grupo=20de=20async):?=
=?UTF-8?q?=20-=20Mudei=20a=20logica=20do=20codigo=20basico=20do=20commit?=
=?UTF-8?q?=20anterior;=20-=20Usei=20a=20logica=20da=20anotacao=20@Async?=
=?UTF-8?q?=20para=20todo=20codigo=20menos=20CartoesService;=20-=20Em=20Ca?=
=?UTF-8?q?rtoesServices=20usei=20sem=20a=20anotacao=20@Async,=20e=20usei?=
=?UTF-8?q?=20o=20metodo=20'supplyAsync'=20s=C3=B3=20para=20aprendizado=20?=
=?UTF-8?q?mais=20o=20resultado=20=C3=A9=20o=20mesmo;?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../br/com/vemprofut/configs/AsyncConfig.java | 22 ++++
.../vemprofut/controllers/FutController.java | 8 +-
.../vemprofut/services/IBanimentoService.java | 7 +-
.../vemprofut/services/ICartoesService.java | 19 +--
.../vemprofut/services/IEditorService.java | 11 +-
.../com/vemprofut/services/IFutService.java | 37 +++---
.../vemprofut/services/IPartidasService.java | 14 ++-
.../implementacao/BanimentoService.java | 16 ++-
.../implementacao/CartoesService.java | 109 ++++++++++++------
.../services/implementacao/EditorService.java | 46 ++++++--
.../services/implementacao/FutService.java | 89 ++++++++------
.../implementacao/PartidasService.java | 63 ++++++----
.../implementacao/PeladeiroService.java | 79 +++++++------
.../IHistoricoPeladeiroQueryService.java | 5 +-
.../services/query/IPartidasQueryService.java | 3 +-
.../query/IPeladeiroQueryService.java | 7 +-
.../HistoricoPeladeiroQueryService.java | 18 ++-
.../implementacao/PartidasQueryService.java | 11 +-
.../implementacao/PeladeiroQueryService.java | 53 +++++----
19 files changed, 395 insertions(+), 222 deletions(-)
create mode 100644 VemProFutApi/src/main/java/br/com/vemprofut/configs/AsyncConfig.java
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/configs/AsyncConfig.java b/VemProFutApi/src/main/java/br/com/vemprofut/configs/AsyncConfig.java
new file mode 100644
index 0000000..abd0c5b
--- /dev/null
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/configs/AsyncConfig.java
@@ -0,0 +1,22 @@
+package br.com.vemprofut.configs;
+
+import java.util.concurrent.Executor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+@Configuration
+@EnableAsync
+public class AsyncConfig {
+ @Bean(name = "defaultExecutor")
+ public Executor defaultExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setCorePoolSize(10);
+ executor.setMaxPoolSize(20);
+ executor.setQueueCapacity(100);
+ executor.setThreadNamePrefix("async-");
+ executor.initialize();
+ return executor;
+ }
+}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java
index 59df0f1..59cf606 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/controllers/FutController.java
@@ -7,6 +7,7 @@
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -26,10 +27,11 @@ public class FutController {
@Operation(
summary = "Cadastra um novo Fut",
tags = {"FutController - CRUD Básico"})
- public ResponseEntity create(
+ public CompletableFuture> create(
@Valid @RequestBody final SaveFutRequestDTO requestDTO) {
- var response = futService.create(requestDTO);
- return ResponseEntity.status(HttpStatus.CREATED).body(response);
+ return futService
+ .create(requestDTO)
+ .thenApply(obj -> ResponseEntity.status(HttpStatus.CREATED).body(obj));
}
@GetMapping("{id}")
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/IBanimentoService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/IBanimentoService.java
index b5d71cc..b988598 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/IBanimentoService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/IBanimentoService.java
@@ -4,11 +4,12 @@
import br.com.vemprofut.controllers.response.BanimentoDetailsResponseDTO;
import br.com.vemprofut.controllers.response.SaveBanimentoResponseDTO;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
public interface IBanimentoService {
- SaveBanimentoResponseDTO create(SaveBanimentoRequestDTO dto);
+ CompletableFuture create(SaveBanimentoRequestDTO dto);
- List findAll(Long idFut);
+ CompletableFuture> findAll(Long idFut);
- void delete(Long idPeladeiro);
+ CompletableFuture delete(Long idPeladeiro);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/ICartoesService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/ICartoesService.java
index 3b67133..1037680 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/ICartoesService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/ICartoesService.java
@@ -4,24 +4,25 @@
import br.com.vemprofut.models.CartoesModel;
import br.com.vemprofut.models.DTOs.CartoesDTO;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
public interface ICartoesService {
- CartoesDTO create(CartoesDTO dto);
+ CompletableFuture create(CartoesDTO dto);
- List findByPeladeiro(Long id);
+ CompletableFuture> findByPeladeiro(Long id);
- List findByPartida(Long id);
+ CompletableFuture> findByPartida(Long id);
- List findByFut(Long id);
+ CompletableFuture> findByFut(Long id);
- List findAll();
+ CompletableFuture> findAll();
- CartoesDTO findById(Long id);
+ CompletableFuture findById(Long id);
- CartoesModel findByIdModel(Long id);
+ CompletableFuture findByIdModel(Long id);
- CartoesResumoResponseDTO contarCartoesPeladeiro(Long peladeiroId);
+ CompletableFuture contarCartoesPeladeiro(Long peladeiroId);
- CartoesResumoResponseDTO contarCartoesFut(Long futId);
+ CompletableFuture contarCartoesFut(Long futId);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/IEditorService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/IEditorService.java
index ad8ad7f..121dcf5 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/IEditorService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/IEditorService.java
@@ -4,16 +4,17 @@
import br.com.vemprofut.models.DTOs.FutDTO;
import br.com.vemprofut.models.EditorModel;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
public interface IEditorService {
- EditorModel create(EditorModel dto);
+ CompletableFuture create(EditorModel dto);
- EditorDTO findById(Long id);
+ CompletableFuture findById(Long id);
- EditorModel findByIdModel(Long id);
+ CompletableFuture findByIdModel(Long id);
- List findAll(FutDTO futDTO);
+ CompletableFuture> findAll(FutDTO futDTO);
- void delete(Long id);
+ CompletableFuture delete(Long id);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/IFutService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/IFutService.java
index 6b8724d..2656bf5 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/IFutService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/IFutService.java
@@ -5,41 +5,44 @@
import br.com.vemprofut.models.DTOs.FutDTO;
import br.com.vemprofut.models.FutModel;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
import org.springframework.web.multipart.MultipartFile;
public interface IFutService {
- SaveFutResponseDTO create(SaveFutRequestDTO dto);
+ CompletableFuture create(SaveFutRequestDTO dto);
- FutDetailsResponse findById(Long id);
+ CompletableFuture findById(Long id);
- FutModel findByIdModel(Long id);
+ CompletableFuture findByIdModel(Long id);
- FutDTO findByNome(String nome);
+ CompletableFuture findByNome(String nome);
- List findAll();
+ CompletableFuture> findAll();
- UpdateFutResponseDTO update(Long id, UpdateFutRequestDTO dto);
+ CompletableFuture update(Long id, UpdateFutRequestDTO dto);
- void delete(Long id);
+ CompletableFuture delete(Long id);
- SavePartidasResponseDTO criarPartida(SavePartidaRequestDTO requestDTO, FutModel futModel);
+ CompletableFuture criarPartida(
+ SavePartidaRequestDTO requestDTO, FutModel futModel);
- void addPeladeiro(AddPeladeiroInFutListRequestDTO requestDTO);
+ CompletableFuture addPeladeiro(AddPeladeiroInFutListRequestDTO requestDTO);
- List criarPartidasList(List requestDTOS);
+ CompletableFuture> criarPartidasList(
+ List requestDTOS);
- List listarPeladeiroCadastradosFut(Long futId);
+ CompletableFuture> listarPeladeiroCadastradosFut(Long futId);
- void addEditor(AddEditorInFutListResquestDTO resquestDTO);
+ CompletableFuture addEditor(AddEditorInFutListResquestDTO resquestDTO);
- List listarEditoresCadastradosFut(Long idFut);
+ CompletableFuture> listarEditoresCadastradosFut(Long idFut);
- void atualizarFotoCapa(Long id, MultipartFile file);
+ CompletableFuture atualizarFotoCapa(Long id, MultipartFile file);
- SaveBanimentoResponseDTO addBanimentoList(SaveBanimentoRequestDTO dto);
+ CompletableFuture addBanimentoList(SaveBanimentoRequestDTO dto);
- List findAllBanidos(Long idFut);
+ CompletableFuture> findAllBanidos(Long idFut);
- void removeBanido(Long idPeladeiro, Long idFut);
+ CompletableFuture removeBanido(Long idPeladeiro, Long idFut);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/IPartidasService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/IPartidasService.java
index a7a7d5c..05523a5 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/IPartidasService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/IPartidasService.java
@@ -6,18 +6,20 @@
import br.com.vemprofut.models.DTOs.PeladeiroDTO;
import br.com.vemprofut.models.FutModel;
import br.com.vemprofut.models.PartidasModel;
+import java.util.concurrent.CompletableFuture;
public interface IPartidasService {
- SavePartidasResponseDTO create(SavePartidaRequestDTO requestDTO, FutModel futModel);
+ CompletableFuture create(
+ SavePartidaRequestDTO requestDTO, FutModel futModel);
- PartidasDTO findById(Long id);
+ CompletableFuture findById(Long id);
- PartidasModel findByIdModel(Long id);
+ CompletableFuture findByIdModel(Long id);
- void addGols(PeladeiroDTO peladeiroDTO, PartidasDTO partidasDTO);
+ CompletableFuture addGols(PeladeiroDTO peladeiroDTO, PartidasDTO partidasDTO);
- void addPeladeiros(Long peladeiroId, PartidasDTO partidasDTO);
+ CompletableFuture addPeladeiros(Long peladeiroId, PartidasDTO partidasDTO);
- void addCartoes(Long cartaoId, PartidasDTO partidasDTO);
+ CompletableFuture addCartoes(Long cartaoId, PartidasDTO partidasDTO);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/BanimentoService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/BanimentoService.java
index 3dbbf95..76d3f99 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/BanimentoService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/BanimentoService.java
@@ -13,7 +13,9 @@
import br.com.vemprofut.services.IBanimentoService;
import br.com.vemprofut.services.query.IBanimentoQueryService;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@@ -29,7 +31,7 @@ public class BanimentoService implements IBanimentoService {
@Autowired private FutRepository futRepository;
- public SaveBanimentoResponseDTO create(SaveBanimentoRequestDTO dto) {
+ public CompletableFuture create(SaveBanimentoRequestDTO dto) {
banimentoQueryService.verifyPeladeiroBanidoExist(dto.fut(), dto.peladeiro());
// Já foi verificado em FutService se Fut e Peladeiro existem... entao é só buscar
@@ -43,16 +45,20 @@ public SaveBanimentoResponseDTO create(SaveBanimentoRequestDTO dto) {
banimentoModel.setDataBanimento(dto.dataBaninimento());
banimentoModel.setDataFimBanimento(dto.dataFimBanimento());
- return banimentoMapper.toSaveResponse(repository.save(banimentoModel));
+ return CompletableFuture.completedFuture(
+ banimentoMapper.toSaveResponse(repository.save(banimentoModel)));
}
@Override
- public List findAll(Long idFut) {
- return banimentoQueryService.verifyExistListBanido(idFut);
+ @Async
+ public CompletableFuture> findAll(Long idFut) {
+ return CompletableFuture.completedFuture(banimentoQueryService.verifyExistListBanido(idFut));
}
@Override
- public void delete(Long idPeladeiro) {
+ public CompletableFuture delete(Long idPeladeiro) {
+
repository.deleteById(idPeladeiro);
+ return CompletableFuture.completedFuture(null);
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/CartoesService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/CartoesService.java
index 12e16e6..43845bb 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/CartoesService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/CartoesService.java
@@ -7,9 +7,6 @@
import br.com.vemprofut.models.CartoesModel;
import br.com.vemprofut.models.DTOs.CartaoCountProjection;
import br.com.vemprofut.models.DTOs.CartoesDTO;
-import br.com.vemprofut.models.FutModel;
-import br.com.vemprofut.models.PartidasModel;
-import br.com.vemprofut.models.PeladeiroModel;
import br.com.vemprofut.repositories.CartoesRepository;
import br.com.vemprofut.services.ICartoesService;
import br.com.vemprofut.services.IFutService;
@@ -17,7 +14,10 @@
import br.com.vemprofut.services.query.IPartidasQueryService;
import br.com.vemprofut.services.query.IPeladeiroQueryService;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -40,65 +40,109 @@ public class CartoesService implements ICartoesService {
@Autowired @Lazy private IFutService futService;
+ @Autowired
+ @Qualifier("defaultExecutor")
+ Executor executor;
+
+ /*
+ Executor = uma forma diferente de tornar async
+ em vez de usar @Async("defaultExecutor").
+ */
+
@Override
@Transactional
- public CartoesDTO create(CartoesDTO dto) {
- queryService.verifyEntitiesExist(dto);
-
- CartoesModel model = mapper.toModel(dto);
- CartoesModel saved = repository.save(model);
- return mapper.toDTO(saved);
+ public CompletableFuture create(CartoesDTO dto) {
+ return CompletableFuture.supplyAsync(
+ () -> {
+ queryService.verifyEntitiesExist(dto);
+ CartoesModel model = mapper.toModel(dto);
+ CartoesModel saved = repository.save(model);
+ return mapper.toDTO(saved);
+ },
+ executor);
}
@Override
@Transactional(readOnly = true)
- public List findAll() {
- return repository.findAll().stream().map(mapper::toDTO).toList();
+ public CompletableFuture> findAll() {
+ return CompletableFuture.supplyAsync(
+ () -> {
+ return repository.findAll().stream().map(mapper::toDTO).toList();
+ },
+ executor);
}
@Override
@Transactional(readOnly = true)
- public CartoesDTO findById(Long id) {
-
- return mapper.toDTO(queryService.verityCartoesExist(id));
+ public CompletableFuture findById(Long id) {
+
+ return CompletableFuture.supplyAsync(
+ () -> {
+ var cartao = queryService.verityCartoesExist(id);
+ return mapper.toDTO(cartao);
+ },
+ executor);
}
@Override
@Transactional(readOnly = true)
- public CartoesModel findByIdModel(Long id) {
-
- return queryService.verityCartoesExist(id);
+ public CompletableFuture findByIdModel(Long id) {
+ return CompletableFuture.supplyAsync(
+ () -> {
+ return queryService.verityCartoesExist(id);
+ },
+ executor);
}
@Override
@Transactional(readOnly = true)
- public List findByPeladeiro(Long id) {
- PeladeiroModel peladeiroModel = peladeiroQueryService.verifyPeladeiroExist(id);
- return repository.findByPeladeiro(peladeiroModel).stream().map(mapper::toDTO).toList();
+ public CompletableFuture> findByPeladeiro(Long id) {
+ /* PeladeiroModel peladeiroModel = peladeiroQueryService.verifyPeladeiroExist(id);
+ return CompletableFuture.completedFuture( <--- sincrono
+ repository.findByPeladeiro(peladeiroModel).stream().map(mapper::toDTO).toList());
+ */
+ // async
+ return peladeiroQueryService
+ .verifyPeladeiroExist(id)
+ .thenApply(
+ peladeiroModel ->
+ repository.findByPeladeiro(peladeiroModel).stream().map(mapper::toDTO).toList());
}
@Override
@Transactional(readOnly = true)
- public List findByPartida(Long id) {
- PartidasModel partidasModel = partidasQueryService.verifyPartidaExistWithRetorn(id);
- return repository.findByPartida(partidasModel).stream().map(mapper::toDTO).toList();
+ public CompletableFuture> findByPartida(Long id) {
+ return partidasQueryService
+ .verifyPartidaExistWithRetorn(id)
+ .thenApply(
+ partidasModel ->
+ repository.findByPartida(partidasModel).stream().map(mapper::toDTO).toList());
}
@Override
@Transactional(readOnly = true)
- public List findByFut(Long id) {
- FutModel futModel = futService.findByIdModel(id);
- return repository.findByFut(futModel).stream().map(mapper::toDTO).toList();
+ public CompletableFuture> findByFut(Long id) {
+ return futService
+ .findByIdModel(id)
+ .thenApply(futModel -> repository.findByFut(futModel).stream().map(mapper::toDTO).toList());
}
- public CartoesResumoResponseDTO contarCartoesPeladeiro(Long peladeiroId) {
- List resultados = repository.countByTipoAndPeladeiro(peladeiroId);
- return montarResumo(resultados);
+ public CompletableFuture contarCartoesPeladeiro(Long peladeiroId) {
+
+ return CompletableFuture.supplyAsync(
+ () -> {
+ List resultados = repository.countByTipoAndPeladeiro(peladeiroId);
+ return montarResumo(resultados);
+ });
}
- public CartoesResumoResponseDTO contarCartoesFut(Long futId) {
- List resultados = repository.countByTipoAndFut(futId);
- return montarResumo(resultados);
+ public CompletableFuture contarCartoesFut(Long futId) {
+
+ return CompletableFuture.supplyAsync(
+ () -> {
+ List resultados = repository.countByTipoAndFut(futId);
+ return montarResumo(resultados);
+ });
}
private CartoesResumoResponseDTO montarResumo(List resultados) {
@@ -111,7 +155,6 @@ private CartoesResumoResponseDTO montarResumo(List result
case VERMELHO -> dto.setVermelho(proj.getQuantidade().intValue());
}
}
-
return dto;
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/EditorService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/EditorService.java
index 6869013..2bcc778 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/EditorService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/EditorService.java
@@ -8,7 +8,9 @@
import br.com.vemprofut.services.IEditorService;
import br.com.vemprofut.services.query.IEditorQueryService;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -22,34 +24,54 @@ public class EditorService implements IEditorService {
@Autowired private EditorRepository repository;
@Override
- public EditorModel create(EditorModel model) {
- queryService.verityEditorExist(model);
- return repository.save(model);
+ @Async("defaultExecutor")
+ @Transactional
+ public CompletableFuture create(EditorModel model) {
+ // queryService.verityEditorExist(model); ---> nao async
+ // return CompletableFuture.completedFuture(repository.save(model));
+
+ // Async
+ return CompletableFuture.supplyAsync(
+ () -> {
+ queryService.verityEditorExist(model);
+ return repository.save(model);
+ });
}
@Override
+ @Async("defaultExecutor")
@Transactional(readOnly = true)
- public EditorDTO findById(Long id) {
- return mapper.toDTO(queryService.verityEditorIdExistReturn(id));
+ public CompletableFuture findById(Long id) {
+ return CompletableFuture.supplyAsync(
+ () -> mapper.toDTO(queryService.verityEditorIdExistReturn(id)));
}
@Override
+ @Async("defaultExecutor")
@Transactional(readOnly = true)
- public EditorModel findByIdModel(Long id) {
- return queryService.verityEditorIdExistReturn(id);
+ public CompletableFuture findByIdModel(Long id) {
+ return CompletableFuture.supplyAsync(() -> queryService.verityEditorIdExistReturn(id));
}
@Override
+ @Async("defaultExecutor")
@Transactional(readOnly = true)
- public List findAll(FutDTO futDTO) {
- queryService.verityFutExist(futDTO);
-
- return repository.findByFutId(futDTO.id()).stream().map(mapper::toDTO).toList();
+ public CompletableFuture> findAll(FutDTO futDTO) {
+ queryService.verityFutExist(futDTO); // sincrono
+ var response =
+ repository
+ .findByFutId(futDTO.id()) // sincrono
+ .stream()
+ .map(mapper::toDTO)
+ .toList();
+ return CompletableFuture.completedFuture(response);
}
@Override
- public void delete(Long id) {
+ @Async("defaultExecutor")
+ public CompletableFuture delete(Long id) {
queryService.verityEditorIdExist(id);
repository.deleteById(id);
+ return CompletableFuture.completedFuture(null);
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java
index 3aa0c5f..80272b3 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/FutService.java
@@ -14,8 +14,12 @@
import br.com.vemprofut.services.query.IPeladeiroQueryService;
import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@@ -54,11 +58,15 @@ public class FutService implements IFutService {
@Autowired private IBanimentoService banidoService;
+ @Autowired
+ @Qualifier("partidasExecutor")
+ private Executor executor;
+
// ======================== CRUD basico ==========================
@Override
@Transactional
- public SaveFutResponseDTO create(SaveFutRequestDTO dto) {
+ public CompletableFuture create(SaveFutRequestDTO dto) {
queryService.verifyNomeFutExist(dto.nome());
var peladeiro = peladeiroQueryService.verifyPeladeiroExist(dto.administradorPeladeiro());
@@ -67,67 +75,78 @@ public SaveFutResponseDTO create(SaveFutRequestDTO dto) {
HistoricoFutModel historico = historicoFutService.create();
saved.setHistoricoFutId(historico);
saved.setAdministradorPeladeiro(peladeiro);
- return mapper.toSaveResponse(repository.save(saved));
+ SaveFutResponseDTO response = mapper.toSaveResponse(repository.save(saved));
+ return CompletableFuture.completedFuture(response);
}
@Override
@Transactional(readOnly = true)
- public FutDetailsResponse findById(Long id) {
+ @Async
+ public CompletableFuture findById(Long id) {
var futModel = queryService.verifyFutExistRetorn(id);
- return mapper.modelToDetailsResponse(futModel);
+ FutDetailsResponse response = mapper.modelToDetailsResponse(futModel);
+ return CompletableFuture.completedFuture(response);
}
@Override
@Transactional(readOnly = true)
- public FutModel findByIdModel(Long id) {
- return queryService.verifyFutExistRetorn(id);
+ @Async
+ public CompletableFuture findByIdModel(Long id) {
+ return CompletableFuture.completedFuture(queryService.verifyFutExistRetorn(id));
}
@Override
@Transactional(readOnly = true)
- public FutDTO findByNome(String nome) {
+ public CompletableFuture findByNome(String nome) {
var futModel = queryService.verifyNomeFutExistRetorn(nome);
- return mapper.toDTO(futModel);
+ return CompletableFuture.completedFuture(mapper.toDTO(futModel));
}
@Override
@Transactional(readOnly = true)
- public List findAll() {
- return repository.findAll().stream().map(mapper::toDTO).toList();
+ @Async
+ public CompletableFuture> findAll() {
+ return CompletableFuture.completedFuture(
+ repository.findAll().stream().map(mapper::toDTO).toList());
}
@Override
@Transactional
- public UpdateFutResponseDTO update(Long id, UpdateFutRequestDTO dto) {
+ public CompletableFuture update(Long id, UpdateFutRequestDTO dto) {
var retorno = queryService.verifyFutExistRetorn(id);
retorno.setJogadoresPorTime(dto.jogadoresPorTime());
retorno.setTempoMaxPartida(dto.tempoMaxPartida());
retorno.setMaxGolsVitoria(dto.maxGolsVitoria());
- return mapper.modelToUpdateResponse(repository.save(retorno));
+ return CompletableFuture.completedFuture(
+ mapper.modelToUpdateResponse(repository.save(retorno)));
}
@Override
@Transactional
- public void delete(Long id) {
+ public CompletableFuture delete(Long id) {
queryService.verifyFutExistRetorn(id);
repository.deleteById(id);
+ return CompletableFuture.completedFuture(null);
}
// ======================== acoes partidas ==========================
- @Override
+ /*@Override
@Transactional
- public SavePartidasResponseDTO criarPartida(SavePartidaRequestDTO requestDTO, FutModel futModel) {
- return partidasService.create(requestDTO, futModel);
+ public CompletableFuture criarPartida(SavePartidaRequestDTO requestDTO, FutModel futModel) {
+ return CompletableFuture.completedFuture(partidasService.create(requestDTO, futModel));
}
@Override
- @Transactional
- public List criarPartidasList(List requestDTOS) {
+ public CompletableFuture> criarPartidasList(List requestDTOS) {
+ // dispara cada DTO em paralelo
+ List> futures = requestDTOS.stream()
+ .map(dto -> CompletableFuture.supplyAsync(() -> criarPartida(dto), executor))
+ .toList(); //TODO: ---------------------------------------------
- List partidaList = new ArrayList<>();
+ // espera todos terminarem e junta os resultados
for (SavePartidaRequestDTO dto : requestDTOS) {
// 1 - criando partida
@@ -190,14 +209,14 @@ public List criarPartidasList(List addPeladeiro(AddPeladeiroInFutListRequestDTO requestDTO) {
PeladeiroModel peladeiroModel =
peladeiroQueryService.verifyPeladeiroExist(requestDTO.peladeiroId());
FutModel futModel = queryService.verifyFutExistRetorn(requestDTO.futId());
@@ -209,11 +228,12 @@ public void addPeladeiro(AddPeladeiroInFutListRequestDTO requestDTO) {
.add(peladeiroModel); // Esse adiciona a tabela: "participa_peladeiro_fut".
repository.save(
futModel); // Esse salva em FutModel (que é onde a table intermediaria foi criada)
+ return CompletableFuture.completedFuture(null);
}
@Override
@Transactional
- public List listarPeladeiroCadastradosFut(Long futId) {
+ public CompletableFuture> listarPeladeiroCadastradosFut(Long futId) {
FutModel futModel = queryService.verifyFutExistRetornListPeladeiro(futId); /*
Esse metodo retorna futModel já com peladeiros carregado... resolvendo o problema abaixo.
@ManyToMany é LAZY, Ou seja:
@@ -230,13 +250,13 @@ public List listarPeladeiroCadastradosFut(Long futId) {
for (PeladeiroModel p : futModel.getPeladeiros()) {
listResponce.add(peladeiroMapper.modelToPeladeiroResponse(p));
}
- return listResponce;
+ return CompletableFuture.completedFuture(listResponce);
}
// ===================== lista Editores =============================
@Override
@Transactional
- public void addEditor(AddEditorInFutListResquestDTO resquestDTO) {
+ public CompletableFuture addEditor(AddEditorInFutListResquestDTO resquestDTO) {
EditorModel editorModel = new EditorModel();
// Verificacoes
@@ -259,7 +279,8 @@ public void addEditor(AddEditorInFutListResquestDTO resquestDTO) {
@Override
@Transactional
- public List listarEditoresCadastradosFut(Long idFut) {
+ public CompletableFuture> listarEditoresCadastradosFut(
+ Long idFut) {
FutModel futModel = queryService.verifyFutExistRetornListEditores(idFut);
log.info("Verificacao de existencia de Fut realizada com sucesso!");
@@ -269,14 +290,14 @@ public List listarEditoresCadastradosFut(Long idFut)
listResponse.add(editorMapper.toResponseNameId(e));
}
- return listResponse;
+ return CompletableFuture.completedFuture(listResponse);
}
// ===================== upload arquivos fotos ======================
@Override
@Transactional
- public void atualizarFotoCapa(Long id, MultipartFile file) {
+ public CompletableFuture atualizarFotoCapa(Long id, MultipartFile file) {
queryService.verifyFutSaveFile(id, file);
}
@@ -284,30 +305,32 @@ public void atualizarFotoCapa(Long id, MultipartFile file) {
@Override
@Transactional
- public SaveBanimentoResponseDTO addBanimentoList(SaveBanimentoRequestDTO dto) {
+ public CompletableFuture addBanimentoList(SaveBanimentoRequestDTO dto) {
FutModel futModel = queryService.verifyFutExistRetorn(dto.fut());
PeladeiroModel peladeiroModel = peladeiroQueryService.verifyPeladeiroExist(dto.peladeiro());
// Verificacao de existe o peladeiro em questao na lista de peladeiro...
queryService.verifyBanidoListPeladeiros(futModel, peladeiroModel);
- return banidoService.create(dto);
+ return CompletableFuture.completedFuture(banidoService.create(dto));
}
@Override
@Transactional
- public List findAllBanidos(Long idFut) {
- return banidoService.findAll(idFut);
+ @Async
+ public CompletableFuture> findAllBanidos(Long idFut) {
+ return CompletableFuture.completedFuture(banidoService.findAll(idFut));
}
@Override
@Transactional
- public void removeBanido(Long idPeladeiro, Long idFut) {
+ public CompletableFuture removeBanido(Long idPeladeiro, Long idFut) {
// TODO: retirar um Banido da lista
queryService.verifyBanidoListPeladeiros(
queryService.verifyFutExistRetorn(idFut),
peladeiroQueryService.verifyPeladeiroExist(idPeladeiro));
banidoService.delete(idPeladeiro);
+ return CompletableFuture.completedFuture(null);
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PartidasService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PartidasService.java
index 396b9e7..64a5bba 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PartidasService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PartidasService.java
@@ -5,17 +5,17 @@
import br.com.vemprofut.mappers.ICartoesMapper;
import br.com.vemprofut.mappers.IPartidasMapper;
import br.com.vemprofut.mappers.IPeladeiroMapper;
-import br.com.vemprofut.models.CartoesModel;
import br.com.vemprofut.models.DTOs.PartidasDTO;
import br.com.vemprofut.models.DTOs.PeladeiroDTO;
import br.com.vemprofut.models.FutModel;
import br.com.vemprofut.models.GolsPartidaModel;
import br.com.vemprofut.models.PartidasModel;
-import br.com.vemprofut.models.PeladeiroModel;
import br.com.vemprofut.repositories.PartidasRepository;
import br.com.vemprofut.services.*;
import br.com.vemprofut.services.query.IPartidasQueryService;
+import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -40,56 +40,77 @@ public class PartidasService implements IPartidasService {
@Override
@Transactional
- public SavePartidasResponseDTO create(SavePartidaRequestDTO requestDTO, FutModel futModel) {
-
+ @Async("defaultExecutor")
+ public CompletableFuture create(
+ SavePartidaRequestDTO requestDTO, FutModel futModel) {
PartidasModel partidasModel = new PartidasModel(requestDTO.reservas(), futModel);
- return mapperPartidas.toResponse(repository.save(partidasModel));
+ SavePartidasResponseDTO response = mapperPartidas.toResponse(repository.save(partidasModel));
+ return CompletableFuture.completedFuture(response);
}
@Override
@Transactional(readOnly = true)
- public PartidasDTO findById(Long id) {
- return mapperPartidas.toDTO(queryService.verifyPartidaExistWithRetorn(id));
+ @Async("defaultExecutor")
+ public CompletableFuture findById(Long id) {
+ return queryService.verifyPartidaExistWithRetorn(id).thenApply(mapperPartidas::toDTO);
}
@Override
@Transactional(readOnly = true)
- public PartidasModel findByIdModel(Long id) {
+ @Async("defaultExecutor")
+ public CompletableFuture findByIdModel(Long id) {
return queryService.verifyPartidaExistWithRetorn(id);
}
@Override
@Transactional
- public void addGols(PeladeiroDTO peladeiroDTO, PartidasDTO partidasDTO) {
+ @Async("defaultExecutor")
+ public CompletableFuture addGols(PeladeiroDTO peladeiroDTO, PartidasDTO partidasDTO) {
GolsPartidaModel gol = golsService.create(peladeiroDTO, partidasDTO);
PartidasModel partida = mapperPartidas.toModel(partidasDTO);
partida.getGolsPartida().add(gol);
repository.save(partida);
+ return CompletableFuture.completedFuture(null);
}
@Override
@Transactional
- public void addPeladeiros(Long peladeiroId, PartidasDTO partidasDTO) {
- // TODO: mudar o DTO para Long de peladeiro.
- PeladeiroModel peladeiroModel = peladeiroService.findByIdModel(peladeiroId);
-
- PartidasModel partida = mapperPartidas.toModel(partidasDTO);
- partida.getPeladeiros().add(peladeiroModel);
-
- repository.save(partida);
+ @Async("defaultExecutor")
+ public CompletableFuture addPeladeiros(Long peladeiroId, PartidasDTO partidasDTO) {
+ /*
+ Aqui você espera o CompletableFuture terminar.
+ Quando o PeladeiroModel estiver disponível, adiciona na partida e salva.
+ O método retorna um CompletableFuture que completa quando tudo terminar.
+ */
+ return peladeiroService
+ .findByIdModel(peladeiroId)
+ .thenAccept(
+ peladeiroModel -> {
+ PartidasModel partida = mapperPartidas.toModel(partidasDTO);
+ partida.getPeladeiros().add(peladeiroModel);
+ });
}
@Override
@Transactional
- public void addCartoes(Long cartaoId, PartidasDTO partidasDTO) {
+ @Async("defaultExecutor")
+ public CompletableFuture addCartoes(Long cartaoId, PartidasDTO partidasDTO) {
// TODO: mudar o DTO para Long de cartoes.
+ /* ---> sincrono
CartoesModel cartoesModel = cartoesService.findByIdModel(cartaoId);
-
PartidasModel partida = mapperPartidas.toModel(partidasDTO);
partida.getCartoes().add(cartoesModel);
-
- repository.save(partida);
+ return repository.save(partida); */
+ // Async
+ return cartoesService
+ .findByIdModel(cartaoId)
+ .thenAccept(
+ cartoesModel -> {
+ PartidasModel partida = mapperPartidas.toModel(partidasDTO);
+ partida.getCartoes().add(cartoesModel);
+ repository.save(partida);
+ });
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
index adb541e..5057376 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/implementacao/PeladeiroService.java
@@ -41,6 +41,7 @@ public class PeladeiroService implements IPeladeiroService {
@Override
@Transactional
+ @Async("defaultExecutor")
public CompletableFuture create(SavePeladeiroRequestDTO dto) {
queryService.verifyEmail(dto.email());
log.info("Email verificado!");
@@ -51,67 +52,67 @@ public CompletableFuture create(SavePeladeiroRequestDT
peladeiroSalvo.setHistoricoPeladeiro(historicoMapper.toModel(historico));
log.info("Peladeiro cadastrado com sucesso!");
- SavePeladeiroResponseDTO response =
- peladeiroMapper.modelToSaveResponse(repository.save(peladeiroSalvo));
-
+ var response = peladeiroMapper.modelToSaveResponse(repository.save(peladeiroSalvo));
return CompletableFuture.completedFuture(response);
}
@Override
@Transactional
- @Async
+ @Async("defaultExecutor")
public CompletableFuture update(
Long id, UpdatePeladeiroRequestDTO dto) {
- var peladeiroModel = queryService.verifyPeladeiroExist(id);
log.info("Verificado a existencia de Peladeiro");
-
- peladeiroModel.setNome(dto.nome());
- peladeiroModel.setEmail(dto.email());
- peladeiroModel.setApelido(dto.apelido());
- peladeiroModel.setDescricao(dto.descricao());
- peladeiroModel.setWhatsapp(dto.whatsapp());
- peladeiroModel.setPeDominante(dto.peDominante());
-
- log.info("Peladeiro alterado com sucesso!");
- UpdatePeladeiroResponseDTO response =
- peladeiroMapper.modelToUpdateResponse(repository.save(peladeiroModel));
- return CompletableFuture.completedFuture(response);
+ return queryService
+ .verifyPeladeiroExist(id)
+ .thenApply(
+ peladeiroModel -> {
+ peladeiroModel.setNome(dto.nome());
+ peladeiroModel.setEmail(dto.email());
+ peladeiroModel.setApelido(dto.apelido());
+ peladeiroModel.setDescricao(dto.descricao());
+ peladeiroModel.setWhatsapp(dto.whatsapp());
+ peladeiroModel.setPeDominante(dto.peDominante());
+
+ log.info("Peladeiro alterado com sucesso!");
+
+ return peladeiroMapper.modelToUpdateResponse(repository.save(peladeiroModel));
+ });
}
@Override
@Transactional(readOnly = true)
- @Async
+ @Async("defaultExecutor")
public CompletableFuture findById(Long id) {
log.info("Buscando peladeiro pelo id... saida de resposta");
- PeladeiroModel retorno = queryService.verifyPeladeiroExist(id);
- CartoesResumoResponseDTO resumo = cartoesService.contarCartoesPeladeiro(id);
- var response =
- new PeladeiroDetailResponse(
- retorno.getId(),
- retorno.getNome(),
- retorno.getEmail(),
- retorno.getApelido(),
- retorno.getDescricao(),
- retorno.getWhatsapp(),
- retorno.getPeDominante(),
- resumo);
-
- return CompletableFuture.completedFuture(response);
+ CompletableFuture peladeiroFuture = queryService.verifyPeladeiroExist(id);
+ CompletableFuture resumoFuture =
+ cartoesService.contarCartoesPeladeiro(id);
+ return peladeiroFuture.thenCombine(
+ resumoFuture,
+ (retorno, resumo) ->
+ new PeladeiroDetailResponse(
+ retorno.getId(),
+ retorno.getNome(),
+ retorno.getEmail(),
+ retorno.getApelido(),
+ retorno.getDescricao(),
+ retorno.getWhatsapp(),
+ retorno.getPeDominante(),
+ resumo));
}
@Override
@Transactional(readOnly = true)
- @Async
+ @Async("defaultExecutor")
public CompletableFuture findByIdModel(Long id) {
log.info("Buscando peladeiro pelo id... saida de uso interno");
- PeladeiroModel response = queryService.verifyPeladeiroExist(id);
- return CompletableFuture.completedFuture(response);
+ return queryService.verifyPeladeiroExist(id);
}
// @Override
- // @Transactional
- // @Async(readOnly = true)
- // public List findAll() {
+ // @Transactional(readOnly = true)
+ // @Async("defaultExecutor")
+ // public CompletableFuture> findAll() {
//
// return repository.findAll()
// .stream()
@@ -120,6 +121,7 @@ public CompletableFuture findByIdModel(Long id) {
// }
@Override
+ @Async("defaultExecutor")
@Transactional
public CompletableFuture delete(Long id) {
queryService.verifyPeladeiroExist(id);
@@ -129,6 +131,7 @@ public CompletableFuture delete(Long id) {
}
@Override
+ @Async("defaultExecutor")
@Transactional
public CompletableFuture atualizarFoto(Long id, MultipartFile file) {
queryService.verifyPeladeiroSaveFile(id, file);
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IHistoricoPeladeiroQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IHistoricoPeladeiroQueryService.java
index 182da8c..134d80a 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IHistoricoPeladeiroQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IHistoricoPeladeiroQueryService.java
@@ -1,10 +1,11 @@
package br.com.vemprofut.services.query;
import br.com.vemprofut.models.HistoricoPeladeiroModel;
+import java.util.concurrent.CompletableFuture;
public interface IHistoricoPeladeiroQueryService {
- HistoricoPeladeiroModel verityHistoricoPeladeiroExistReturn(Long id);
+ CompletableFuture verityHistoricoPeladeiroExistReturn(Long id);
- void verityHistoricoPeladeiroExist(Long id);
+ CompletableFuture verityHistoricoPeladeiroExist(Long id);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPartidasQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPartidasQueryService.java
index 1d0d7dd..445a98a 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPartidasQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPartidasQueryService.java
@@ -1,8 +1,9 @@
package br.com.vemprofut.services.query;
import br.com.vemprofut.models.PartidasModel;
+import java.util.concurrent.CompletableFuture;
public interface IPartidasQueryService {
- PartidasModel verifyPartidaExistWithRetorn(Long id);
+ CompletableFuture verifyPartidaExistWithRetorn(Long id);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPeladeiroQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPeladeiroQueryService.java
index a7057cc..d7e16b2 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPeladeiroQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/IPeladeiroQueryService.java
@@ -1,13 +1,14 @@
package br.com.vemprofut.services.query;
import br.com.vemprofut.models.PeladeiroModel;
+import java.util.concurrent.CompletableFuture;
import org.springframework.web.multipart.MultipartFile;
public interface IPeladeiroQueryService {
- void verifyEmail(final String email);
+ CompletableFuture verifyEmail(final String email);
- PeladeiroModel verifyPeladeiroExist(final Long id);
+ CompletableFuture verifyPeladeiroExist(final Long id);
- void verifyPeladeiroSaveFile(Long id, MultipartFile file);
+ CompletableFuture verifyPeladeiroSaveFile(Long id, MultipartFile file);
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/HistoricoPeladeiroQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/HistoricoPeladeiroQueryService.java
index 4ece915..7ddfe08 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/HistoricoPeladeiroQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/HistoricoPeladeiroQueryService.java
@@ -4,7 +4,9 @@
import br.com.vemprofut.models.HistoricoPeladeiroModel;
import br.com.vemprofut.repositories.HistoricoPeladeiroRepository;
import br.com.vemprofut.services.query.IHistoricoPeladeiroQueryService;
+import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@@ -12,18 +14,24 @@ public class HistoricoPeladeiroQueryService implements IHistoricoPeladeiroQueryS
@Autowired HistoricoPeladeiroRepository repository;
@Override
- public HistoricoPeladeiroModel verityHistoricoPeladeiroExistReturn(Long id) {
-
+ @Async("defaultExecutor")
+ public CompletableFuture verityHistoricoPeladeiroExistReturn(Long id) {
return repository
.findById(id)
- .orElseThrow(
- () -> new NotFoundException("Não foi encontrado o Historico de Peladeiro de id " + id));
+ .map(CompletableFuture::completedFuture)
+ .orElseGet(
+ () ->
+ CompletableFuture.failedFuture(
+ new NotFoundException(
+ "Não foi encontrado o Historico de Peladeiro de id " + id)));
}
@Override
- public void verityHistoricoPeladeiroExist(Long id) {
+ @Async("defaultExecutor")
+ public CompletableFuture verityHistoricoPeladeiroExist(Long id) {
if (!repository.existsById(id)) {
throw new NotFoundException("Id: " + id + "de Historico Jogador não encontrado!");
}
+ return CompletableFuture.completedFuture(null);
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PartidasQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PartidasQueryService.java
index dc8abd3..9806409 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PartidasQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PartidasQueryService.java
@@ -7,7 +7,9 @@
import br.com.vemprofut.repositories.PartidasRepository;
import br.com.vemprofut.repositories.PeladeiroRepository;
import br.com.vemprofut.services.query.IPartidasQueryService;
+import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@@ -21,9 +23,14 @@ public class PartidasQueryService implements IPartidasQueryService {
@Autowired private PeladeiroRepository peladeiroRepository;
@Override
- public PartidasModel verifyPartidaExistWithRetorn(Long id) {
+ @Async("defaultExecutor")
+ public CompletableFuture verifyPartidaExistWithRetorn(Long id) {
return repository
.findById(id)
- .orElseThrow(() -> new NotFoundException("Não foi encontrado a Partida de id " + id));
+ .map(CompletableFuture::completedFuture)
+ .orElseGet(
+ () ->
+ CompletableFuture.failedFuture(
+ new NotFoundException("Não foi encontrado a Partida de id " + id)));
}
}
diff --git a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PeladeiroQueryService.java b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PeladeiroQueryService.java
index 2670d1f..a96cb9b 100644
--- a/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PeladeiroQueryService.java
+++ b/VemProFutApi/src/main/java/br/com/vemprofut/services/query/implementacao/PeladeiroQueryService.java
@@ -8,8 +8,10 @@
import br.com.vemprofut.services.IUploadLocalService;
import br.com.vemprofut.services.query.IPeladeiroQueryService;
import java.io.IOException;
+import java.util.concurrent.CompletableFuture;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -22,42 +24,45 @@ public class PeladeiroQueryService implements IPeladeiroQueryService {
private final IUploadLocalService uploadLocalService;
@Override
- public void verifyEmail(String email) {
+ @Async("defaultExecutor")
+ public CompletableFuture verifyEmail(String email) {
if (repository.existsByEmail(email)) {
var message = "O e-mail " + email + " já está em uso";
log.error(message);
throw new EmailInUseException(message);
}
+ return CompletableFuture.completedFuture(null);
}
@Override
- public PeladeiroModel verifyPeladeiroExist(Long id) {
+ @Async("defaultExecutor")
+ public CompletableFuture verifyPeladeiroExist(Long id) {
log.debug("Verificando existência do Peladeiro com ID: {}", id);
- PeladeiroModel peladeiro =
- repository
- .findById(id)
- .orElseThrow(
- () -> {
- log.warn("Peladeiro com ID {} não encontrado no banco de dados", id);
- return new NotFoundException("Não foi encontrado o Peladeiro de id " + id);
- });
-
- log.debug("Peladeiro encontrado: {}", peladeiro);
- return peladeiro;
+ return repository
+ .findById(id)
+ .map(CompletableFuture::completedFuture)
+ .orElseGet(
+ () ->
+ CompletableFuture.failedFuture(
+ new NotFoundException("Não foi encontrado o Peladeiro de id " + id)));
}
@Override
- public void verifyPeladeiroSaveFile(Long id, MultipartFile file) {
- PeladeiroModel peladeiroModel = verifyPeladeiroExist(id);
- try {
- String url = uploadLocalService.upload(file, "peladeiro");
- peladeiroModel.setFotoUrl(url);
- repository.save(peladeiroModel);
- log.info("Foto salva!");
- } catch (IOException ex) {
- throw new FileStorageException(
- "Erro ao salvar a foto do peladeiro com id: " + id, ex.getCause());
- }
+ @Async("defaultExecutor")
+ public CompletableFuture verifyPeladeiroSaveFile(Long id, MultipartFile file) {
+ return verifyPeladeiroExist(id) // retorna CompletableFuture
+ .thenAccept(
+ peladeiroModel -> {
+ try {
+ String url = uploadLocalService.upload(file, "peladeiro");
+ peladeiroModel.setFotoUrl(url);
+ repository.save(peladeiroModel);
+ log.info("Foto salva!");
+ } catch (IOException ex) {
+ throw new FileStorageException(
+ "Erro ao salvar a foto do peladeiro com id: " + id, ex);
+ }
+ });
}
}
From 8531f9e210e7eceb3a7d6c6fe9e2d887bec88ba4 Mon Sep 17 00:00:00 2001
From: Marcio Costa
Date: Mon, 5 Jan 2026 22:03:53 -0300
Subject: [PATCH 13/13] =?UTF-8?q?refactore(transicao=20para=20assicrono):?=
=?UTF-8?q?=20-=20transformei=20todas=20as=20classes=20de=20services,=20qu?=
=?UTF-8?q?eryService,=20controllers=20e=20mappers=20em=20assincrono(async?=
=?UTF-8?q?);=20-=20gerei=20uma=20imagem=20na=20pasta=20de=20fluxograma=20?=
=?UTF-8?q?da=20logica=20de=20funcionamento=20do=20metodo=20criarPartidasL?=
=?UTF-8?q?ist=20(async);=20-=20adaptei=20todos=20os=20testes=20feito=20at?=
=?UTF-8?q?=C3=A9=20aqui=20para=20async;?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Fluxograma_BPMN/criarListPartida.png | Bin 0 -> 73550 bytes
.../configs/OAuth2LoginSuccessHandler.java | 37 +-
.../vemprofut/controllers/FutController.java | 83 ++--
.../vemprofut/mappers/IMappersDefault.java | 10 +-
.../services/IHistoricoPeladeiroService.java | 11 +-
.../services/implementacao/FutService.java | 398 ++++++++++--------
.../HistoricoPeladeiroService.java | 42 +-
.../implementacao/PeladeiroService.java | 15 +-
.../services/query/IFutQueryService.java | 22 +-
.../query/implementacao/FutQueryService.java | 110 +++--
.../unit/services/FutServiceTest.java | 36 +-
.../unit/services/PeladeiroServiceTest.java | 43 +-
12 files changed, 477 insertions(+), 330 deletions(-)
create mode 100644 Diagramas/Fluxograma_BPMN/criarListPartida.png
diff --git a/Diagramas/Fluxograma_BPMN/criarListPartida.png b/Diagramas/Fluxograma_BPMN/criarListPartida.png
new file mode 100644
index 0000000000000000000000000000000000000000..9a2f0f9af53fffa34b7a3556f7f30a23a345d595
GIT binary patch
literal 73550
zcmdqJcU)6>*Ds1X>R6CbR1`!;L6EK@Al(KCNbg-mdM}{|R74a6lqw)aI)o0PLqrA<
z5Rj6D9+jQ|krH}2YvXg@cJ6!b`P@I>e4cqG1DjobWv%rsYrj%ck*7b*e3*`oj$Yy3
zT@5F!(JRMr!>y{Rp8_5OeJzP4r0188k*dXnLjsXpDT{=o1{M+c!bnip%)&fL`0#Lde~c|rXC{rlg7f`Zx@
z9p$Zcnx>W26n!C_KZWB8a{YYd4l314N=s=&uASEFug@wf-q*V6q`&sZAFcg(+6&?%
zk+`U&_*B;{mCIZbhWrL)y?w=|+15RoqP3^tZ++yR?5Cr1INRUf&+N1^Y*6i%<1MvW
zX+WFGSisx1KDg3XR!}y^VQ+{v^1r{KbM=QM)}`t2Z9Y1>CrZeJJ~8}k7A}>^Ewh;t
z+pMadR?cc~++luALzA}s%Lg^LdYo0lTg$vPsu-mJS95T@SYg|{ShXp;(1@6-r65A
zuZ1&w_XRu_Nr-;;&WZvHl5S@29vF_wOOMUXTUwg%1oM+2rIbK%At51qqeJlbXs0q1
zGOf!TqFnMA%dK=NiZ1shX&pIvuKl{XsVV_%YU9=PsJVaC&C@wBHUXTvcwGPE?$4yj
zY~|#q`^&GMIjUa`
z&)&3HuX$yrGPk~+GxDO!`JU=3p+aXo{H3U<9I~v8ey+~V=8_5`pYdqLa8$*(>rVQd
zk1%!8&rhO7mKW;r1vI3fS%~C}7NL`DXFsel)~oe(1zfvvMmzr&Bh715tg6cA@&$6O
zwBO^G>yq=eG0Gb{`QG&3a!s>Z?5<6RZW}LsH)O*o*1ZssHiOG<$RpF?bO`rGZFbW&
zCs))i_YKdEWO32MpaPq|512>npS0`c_)-4f)fKwm7fQdasR%bo5ZCS3kBeU*C>hWw
zs@04Bs(LF@RgM)VYumbFRh6w0f2%3^zt2oSpO6rd`=;AXaYv1O~l2`r9N*fz|oIG!NtY-ZDdGDu4t{X<+0h$p3GYt9WKti
zs5|6?FqLO_cc0OxHW{@>nKN10rCDyiohpd~IC_mT^?6%}6g5CtU*l#fh~
zSx3etWhTq`YPMGoXFQ~$IW2WX^WRC!HoM!m^>j3Jd9o`ZcQgI#G#6G<-5so9d30oH$j`Kk(J}8iR83{ho;&B}vf~iv
z;)-?eIC`nMnMe5QEly2``er8=cXbQz_=wR*(TUMs0iAzAFnN3t*&VA1X_1lVx2AZ#
zR#&ZC69mb#PowWiT
zx$@wN%H5{vP^v{=b=1XK1DpX>#-;Gnr%xxDnQbU8@Z5G`yZZ&c71{0%g!_v<3-DiF
z$n-ujd=?TC;-dH^b-F)}iR^|#VVy6*FPEPpb2fBhb89R5FIIEPwctzA;u^<}9a~sl
zE=O_05$^vwLfmaC<)u*8Nxy}6`AXc~VZywi>pIM17#msmx>pOm+1tpYU0t?L
zqgd`f)69#8Pi77f4EQffNEq&$t2b1N6~G%aNM-7HENKLiD_Z`WxGQWw(3>d?i=vNl
zFN9zxr54B-uANd@(?S-Pxv#44X)qsW{OhtMi{yN#-8F8hOZq<`?nA`lH!SaFGWAvQ
zggyLA5E;ksF;R($`O&<(Htq4k!QtV$78Voqg+G2q9>8d0GV9SBJlC%;y&%F+sh#-u
zj8^