Start Project, Create Models and Start Ports

This commit is contained in:
João P.A Silveira 2026-05-22 11:08:01 -03:00
commit 48e751c7c0
55 changed files with 1251 additions and 0 deletions

3
.gitattributes vendored Normal file
View file

@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

37
.gitignore vendored Normal file
View file

@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

338
agents.md Normal file
View file

@ -0,0 +1,338 @@
# 🤖 CoreSync — Agent Guidelines
Este documento define a arquitetura, as regras de negócio e os padrões de código obrigatórios para o desenvolvimento do backend do **CoreSync**. Todo código gerado ou modificado deve obedecer estritamente às diretrizes abaixo.
---
## 🛠 Stack Tecnológico
| Camada | Tecnologia |
|---|---|
| Linguagem | Groovy (Closures, Records, sintaxe enxuta) |
| Runtime | Java 26 (toolchain configurado no Gradle) |
| Framework | Spring Boot (Web, Security, Data MongoDB) |
| Banco de Dados | MongoDB |
| Cliente | React Native — comunicação exclusiva via JSON/REST + JWT stateless |
---
## 🏛 Arquitetura: Hexagonal (Ports & Adapters) + DDD
O sistema é um **Monolito Modular** construído sobre **Arquitetura Hexagonal**. O objetivo é o isolamento absoluto da Regra de Negócio.
### Regra de Ouro
> As camadas `domain` e `application` são **100% agnósticas de framework**. Elas não conhecem Spring Boot, MongoDB nem HTTP. Tudo que for infraestrutura ou framework vive exclusivamente na camada `adapter`.
### 📂 Estrutura de Pacotes Obrigatória
Os pacotes são organizados por **módulo de negócio** (ex: `user`, `workout`, `session`). Dentro de cada módulo:
```
src/main/groovy/br/dev/jsilveira/coresync/[modulo]/
├── domain/
│ ├── model/ # Records Groovy — Agregados, Entidades e Value Objects
│ └── exception/ # Exceções de negócio do módulo
├── application/
│ ├── port/
│ │ ├── in/ # Interfaces de entrada (Casos de Uso chamados pela API)
│ │ └── out/ # Interfaces de saída (o que o domínio precisa do mundo externo)
│ └── service/ # Implementa ports/in; consome ports/out
├── adapter/
│ ├── in/web/ # Controllers REST + DTOs de entrada/saída
│ └── out/persistence/ # Spring Data Repositories, Entities MongoDB, Mappers
└── config/ # Classes @Configuration com definições de @Bean
```
---
## 📜 Regras de Código
### 1. Modelagem com Records (Imutabilidade)
- Todas as Entidades, Agregados e Value Objects do domínio **devem ser `record` do Groovy**.
- O estado **nunca é mutado diretamente**. Toda transição de estado produz uma nova instância do record (padrão *copy-on-write*).
### 2. Validação no Construtor Compacto
- Toda validação de invariantes de negócio ocorre **no construtor compacto do record**.
- É **proibido** instanciar um objeto de domínio em estado inválido (IDs nulos, strings vazias, datas inconsistentes, dependências ausentes).
- Violations devem lançar a **exceção de negócio específica do módulo** (nunca `IllegalArgumentException` genérica).
### 3. Identificadores (UUID)
- O banco de dados **não gera IDs**. Cada entidade possui seu próprio `UUID id`.
- A geração do ID ocorre na camada **`application/service`** via `UUID.randomUUID()`, antes do envio ao adaptador de persistência.
- Referências entre Aggregate Roots são feitas **exclusivamente por ID** — nunca aninhe objetos raiz dentro de outros.
### 4. Zero Lombok
- Lombok é **proibido**. Use os recursos nativos do Groovy:
- Construtores de mapa (`new Foo(bar: "x")`)
- Propriedades automáticas (`@groovy.transform.CompileStatic`)
- `@Slf4j` nativo do Groovy para logging
- `record` para imutabilidade
### 5. Domínio Rico (Rich Domain)
- O domínio **não deve ser anêmico**. Lógicas de cálculo, transições de estado, formatações e validações pertinentes à entidade ficam **dentro do próprio record**.
- O `Service` orquestra; ele **não executa regras de negócio**.
### 6. Services são POJOs
- Classes de `application/service` **não recebem** `@Service` nem qualquer anotação do Spring.
- São classes Groovy puras instanciadas como `@Bean` via uma classe `@Configuration` no módulo.
- Dependências injetadas **exclusivamente pelo construtor**.
### 7. Nomenclatura
| Artefato | Convenção |
|---|---|
| Porta de entrada | `[Ação][Entidade]UseCase` (ex: `FinishSessionUseCase`) |
| Porta de saída — leitura | `Load[Entidade]Port` |
| Porta de saída — escrita | `Save[Entidade]Port` |
| Porta de saída — remoção | `Delete[Entidade]Port` |
| Serviço | `[Ação][Entidade]Service` |
| Controller | `[Entidade]Controller` |
| Entity (Mongo) | `[Entidade]Entity` |
| DTO de entrada | `[Entidade]Request` |
| DTO de saída | `[Entidade]Response` |
### 8. Mapeamento entre Camadas
- Conversão entre `DomainModel ↔ Entity` e `DomainModel ↔ DTO` ocorre em classes **Mapper dedicadas** em `adapter/out/persistence/` e `adapter/in/web/`, respectivamente.
- Nunca exponha uma `Entity` fora do adaptador de persistência.
- Nunca exponha um objeto de domínio diretamente em uma resposta HTTP.
### 9. Tratamento de Erros
- Exceções de negócio definidas em `domain/exception/` são capturadas por um `@ControllerAdvice` global no adaptador web.
- O `@ControllerAdvice` traduz exceções para respostas HTTP adequadas (ex: `SessionException``400 Bad Request`).
- O domínio **nunca conhece** códigos HTTP.
### 10. Segurança e Autenticação
- Toda autenticação é **stateless via JWT**.
- O token é validado no adaptador (`adapter/in/web/`) antes de qualquer chamada ao caso de uso.
- O `userId` extraído do token deve ser passado explicitamente como parâmetro ao caso de uso — nunca acessado diretamente de um contexto de segurança dentro da camada `application`.
---
## 💻 Exemplos de Código
### Modelo de Domínio — `record` com Construtor Compacto
**Local:** `session/domain/model/UserWorkoutSession.groovy`
```groovy
package br.dev.jsilveira.coresync.session.domain.model
import br.dev.jsilveira.coresync.session.domain.exception.SessionException
import java.time.LocalDateTime
import java.util.UUID
record UserWorkoutSession(
UUID id,
UUID userId,
UUID workoutDayId,
LocalDateTime startedAt,
LocalDateTime completedAt
) {
// Construtor compacto: validação de invariantes de negócio
public UserWorkoutSession {
if (!id) throw new SessionException("O ID não pode ser nulo")
if (!userId) throw new SessionException("O ID do usuário é obrigatório")
if (!workoutDayId) throw new SessionException("O ID do treino é obrigatório")
if (!startedAt) throw new SessionException("A data de início é obrigatória")
if (completedAt != null && completedAt.isBefore(startedAt)) {
throw new SessionException("A data de conclusão não pode ser anterior à data de início")
}
}
// Domínio Rico: transição de estado gera uma nova instância imutável
UserWorkoutSession finish(LocalDateTime time = LocalDateTime.now()) {
if (completedAt != null) throw new SessionException("A sessão já foi finalizada")
return new UserWorkoutSession(id, userId, workoutDayId, startedAt, time)
}
boolean isFinished() {
return completedAt != null
}
}
```
---
### Porta de Entrada (API)
**Local:** `session/application/port/in/FinishSessionUseCase.groovy`
```groovy
package br.dev.jsilveira.coresync.session.application.port.in
import java.util.UUID
interface FinishSessionUseCase {
void execute(UUID sessionId, UUID requestingUserId)
}
```
---
### Porta de Saída (SPI)
**Local:** `session/application/port/out/SaveSessionPort.groovy`
```groovy
package br.dev.jsilveira.coresync.session.application.port.out
import br.dev.jsilveira.coresync.session.domain.model.UserWorkoutSession
// O domínio declara o contrato; a implementação vive no adaptador
interface SaveSessionPort {
void save(UserWorkoutSession session)
}
```
**Local:** `session/application/port/out/LoadSessionPort.groovy`
```groovy
package br.dev.jsilveira.coresync.session.application.port.out
import br.dev.jsilveira.coresync.session.domain.model.UserWorkoutSession
import java.util.UUID
interface LoadSessionPort {
UserWorkoutSession load(UUID sessionId)
}
```
---
### Serviço (Caso de Uso) — POJO Groovy
**Local:** `session/application/service/FinishWorkoutSessionService.groovy`
```groovy
package br.dev.jsilveira.coresync.session.application.service
import br.dev.jsilveira.coresync.session.application.port.in.FinishSessionUseCase
import br.dev.jsilveira.coresync.session.application.port.out.LoadSessionPort
import br.dev.jsilveira.coresync.session.application.port.out.SaveSessionPort
import br.dev.jsilveira.coresync.session.domain.exception.SessionException
import java.util.UUID
// Sem @Service — instanciado via @Bean em SessionConfig
class FinishWorkoutSessionService implements FinishSessionUseCase {
private final LoadSessionPort loadPort
private final SaveSessionPort savePort
FinishWorkoutSessionService(LoadSessionPort loadPort, SaveSessionPort savePort) {
this.loadPort = loadPort
this.savePort = savePort
}
@Override
void execute(UUID sessionId, UUID requestingUserId) {
def session = loadPort.load(sessionId)
// Autorização de negócio: o usuário só pode finalizar a própria sessão
if (session.userId() != requestingUserId) {
throw new SessionException("Usuário não autorizado a finalizar esta sessão")
}
// Regra de negócio encapsulada no domínio
def finishedSession = session.finish()
savePort.save(finishedSession)
}
}
```
---
### Entity de Banco (Adaptador de Persistência)
**Local:** `session/adapter/out/persistence/entity/SessionEntity.groovy`
```groovy
package br.dev.jsilveira.coresync.session.adapter.out.persistence.entity
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDateTime
import java.util.UUID
// Anotações de framework são permitidas apenas na camada adapter
@Document(collection = "workout_sessions")
record SessionEntity(
@Id UUID id,
UUID userId,
UUID workoutDayId,
LocalDateTime startedAt,
LocalDateTime completedAt
) {}
```
---
### Configuração do Módulo (Bean Wiring)
**Local:** `session/config/SessionConfig.groovy`
```groovy
package br.dev.jsilveira.coresync.session.config
import br.dev.jsilveira.coresync.session.application.port.out.LoadSessionPort
import br.dev.jsilveira.coresync.session.application.port.out.SaveSessionPort
import br.dev.jsilveira.coresync.session.application.service.FinishWorkoutSessionService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class SessionConfig {
@Bean
FinishWorkoutSessionService finishWorkoutSessionService(
LoadSessionPort loadPort,
SaveSessionPort savePort
) {
return new FinishWorkoutSessionService(loadPort, savePort)
}
}
```
---
## ✅ Checklist por Artefato
Antes de submeter qualquer código, verifique:
**Domain Model (record)**
- [ ] Validações completas no construtor compacto
- [ ] Sem anotações de Spring ou Mongo
- [ ] Transições de estado retornam nova instância (imutabilidade)
- [ ] Lógica de negócio pertinente está no record, não no service
**Application Service**
- [ ] Sem `@Service` ou qualquer anotação do Spring
- [ ] Injeção de dependência apenas por construtor
- [ ] Consome somente `ports/in` e `ports/out`
- [ ] Não contém regras de negócio (delega ao domínio)
**Adapter (Controller / Repository)**
- [ ] Controller recebe e retorna apenas DTOs (`*Request` / `*Response`)
- [ ] Mapeamento domínio ↔ DTO em Mapper dedicado
- [ ] Repository implementa a interface `port/out` correspondente
- [ ] Mapeamento domínio ↔ Entity em Mapper dedicado
**Geral**
- [ ] Nenhum import do Lombok em qualquer camada
- [ ] IDs gerados na camada `application`, nunca no banco
- [ ] Referências entre Aggregate Roots feitas apenas por UUID
- [ ] Exceções de negócio definidas em `domain/exception/`

40
build.gradle Normal file
View file

@ -0,0 +1,40 @@
plugins {
id 'groovy'
id 'org.springframework.boot' version '4.0.6'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'br.dev.jsilveira'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(26)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.apache.groovy:groovy'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
developmentOnly 'org.springframework.boot:spring-boot-docker-compose'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test'
testImplementation 'org.springframework.boot:spring-boot-starter-data-mongodb-test'
testImplementation 'org.springframework.boot:spring-boot-starter-mongodb-test'
testImplementation 'org.springframework.boot:spring-boot-starter-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}

9
compose.yaml Normal file
View file

@ -0,0 +1,9 @@
services:
mongodb:
image: 'mongo:latest'
environment:
- 'MONGO_INITDB_DATABASE=mydatabase'
- 'MONGO_INITDB_ROOT_PASSWORD=secret'
- 'MONGO_INITDB_ROOT_USERNAME=root'
ports:
- '27017'

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
gradlew vendored Executable file
View file

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

93
gradlew.bat vendored Normal file
View file

@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle Normal file
View file

@ -0,0 +1 @@
rootProject.name = 'coresync'

View file

@ -0,0 +1,13 @@
package br.dev.jsilveira.coresync
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class CoresyncApplication {
static void main(String[] args) {
SpringApplication.run(CoresyncApplication, args)
}
}

View file

@ -0,0 +1,4 @@
package br.dev.jsilveira.coresync.adapter.in.web
class TrainingController {
}

View file

@ -0,0 +1,4 @@
package br.dev.jsilveira.coresync.adapter.out.persistence
class MongoTrainingAdapter {
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface CreateUserUseCase {
User execute(String name, String email)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.WorkoutPlan
interface CreateWorkoutPlanUserCase {
WorkoutPlan(String name, UUID userId)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface DisableUserEmailVerifiedUseCase {
User execute(UUID id)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface DisableUserUseCase {
User execute(UUID id)
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface DisableWorkoutDayRestUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface DisableWorkoutPlanUserCase {
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface EnableUserEmailVerifiedUseCase {
User execute(UUID id)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface EnableUserUseCase {
User execute(UUID id)
}

View file

@ -0,0 +1,4 @@
package br.dev.jsilveira.coresync.application.port.in;
public interface EnableWorkoutDayRestUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface EnableWorkoutPlanUserCase {
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface UpdateUserEmailUseCase {
User execute(UUID id, String email)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface UpdateUserImageUseCase {
User execute(UUID id, String image)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface UpdateUserNameUseCase {
User execute(UUID id, String name)
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.application.port.in
import br.dev.jsilveira.coresync.domain.model.User
interface UpdateUserUpdatedAtUseCase {
User execute(UUID id)
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateUserWorkoutSessionCompletedAtUserCase {
}

View file

@ -0,0 +1,4 @@
package br.dev.jsilveira.coresync.application.port.in;
public interface UpdateWorkoutDayDurationUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutDayNameUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutDayUpdatedAtUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutDayWeekDayUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutDayWorkoutExercisesUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutExerciseNameUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutExerciseOrderUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutExerciseRepsUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutExerciseRestTimeUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutExerciseSetsUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutExerciseUpdatedAtUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutPlanNameUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutPlanUpdateAtUserCase {
}

View file

@ -0,0 +1,5 @@
package br.dev.jsilveira.coresync.application.port.in
interface UpdateWorkoutPlanWorkoutDaysUserCase {
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.domain.exception;
public class UserException extends RuntimeException {
public UserException(String message) {
super(message);
}
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.domain.exception;
public class UserWorkoutSessionException extends RuntimeException {
public UserWorkoutSessionException(String message) {
super(message);
}
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.domain.exception;
public class WorkoutDayException extends RuntimeException {
public WorkoutDayException(String message) {
super(message);
}
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.domain.exception;
public class WorkoutExerciseException extends RuntimeException {
public WorkoutExerciseException(String message) {
super(message);
}
}

View file

@ -0,0 +1,7 @@
package br.dev.jsilveira.coresync.domain.exception;
public class WorkoutPlanException extends RuntimeException {
public WorkoutPlanException(String message) {
super(message);
}
}

View file

@ -0,0 +1,30 @@
package br.dev.jsilveira.coresync.domain.model
import br.dev.jsilveira.coresync.domain.exception.UserException
import java.time.LocalDateTime
record User(
UUID id,
String name,
String email,
Boolean emailVerified = Boolean.FALSE,
String image = null,
LocalDateTime createdAt = LocalDateTime.now(),
LocalDateTime updatedAt = LocalDateTime.now(),
Boolean isActive = Boolean.TRUE
) {
public User {
if (id == null) {
throw new UserException("O campo de identificação não pode ser nulo")
}
if (!name?.trim()) {
throw new UserException("O campo de nome não estar vazio")
}
if(!email?.trim()) {
throw new UserException("O campo email não pode estar vazio")
}
}
}

View file

@ -0,0 +1,56 @@
package br.dev.jsilveira.coresync.domain.model
import br.dev.jsilveira.coresync.domain.exception.UserWorkoutSessionException
import java.time.LocalDateTime
import java.time.Duration
record UserWorkoutSession(
UUID id,
UUID userId,
UUID workoutDayId,
LocalDateTime startedAt = LocalDateTime.now(),
LocalDateTime completedAt
) {
public UserWorkoutSession {
if (id == null) {
throw new UserWorkoutSessionException("O campo de identificação não pode ser nulo")
}
if (userId == null) {
throw new UserWorkoutSessionException("O campo de identificação do usuário não pode ser nulo")
}
if (workoutDayId == null) {
throw new UserWorkoutSessionException("O campo de identificação do dia de treino não pode ser nulo")
}
if (startedAt == null) {
throw new UserWorkoutSessionException("A data e hora de início não podem ser nulas")
}
if (completedAt != null && completedAt.isBefore(startedAt)) {
throw new UserWorkoutSessionException("A data de conclusão não pode ser anterior à data de início")
}
}
boolean isCompleted() {
return completedAt != null
}
Long getDurationInMinutes() {
if (!isCompleted()) {
return 0L
}
return Duration.between(startedAt, completedAt).toMinutes()
}
UserWorkoutSession finish(LocalDateTime time = LocalDateTime.now()) {
if (isCompleted()) {
throw new UserWorkoutSessionException("Esta sessão de treino já foi finalizada")
}
return new UserWorkoutSession(
this.id(),
this.userId(),
this.workoutDayId(),
this.startedAt(),
time
)
}
}

View file

@ -0,0 +1,25 @@
package br.dev.jsilveira.coresync.domain.model
enum WeekDay {
DOMINGO(1),
SEGUNDA(2),
TERCA(3),
QUARTA(4),
QUINTA(5),
SEXTA(6),
SABADO(7)
final int day
WeekDay(int numberOfDay) {
this.day = numberOfDay
}
static WeekDay fromInt(int number) {
def weekDay = values().find { it.day == number }
if (!weekDay) {
throw new IllegalArgumentException("Dia da semana inválido: ${number}. Use de 1 a 7.")
}
return weekDay as WeekDay
}
}

View file

@ -0,0 +1,54 @@
package br.dev.jsilveira.coresync.domain.model
import br.dev.jsilveira.coresync.domain.exception.WorkoutDayException
import java.time.LocalDateTime
record WorkoutDay(
UUID id,
String name,
UUID workoutPlanId,
Boolean isRest = Boolean.FALSE,
WeekDay weekDay,
Integer estimatedDurationInSeconds = 0,
LocalDateTime createdAt = LocalDateTime.now(),
LocalDateTime updatedAt = LocalDateTime.now(),
List<WorkoutExercise> workoutExercises = []
) {
public WorkoutDay {
if (id == null) {
throw new WorkoutDayException("O campo de identificação não pode ser nulo")
}
if (!name?.trim()) {
throw new WorkoutDayException("O campo de nome não estar vazio")
}
if (workoutPlanId == null) {
throw new WorkoutDayException("O campo de identificação do plano de treino não pode ser nulo")
}
if (weekDay == null){
throw new WorkoutDayException("O campo de dia da semana não pode ser nulo")
}
if (estimatedDurationInSeconds < 0){
throw new WorkoutDayException("O campo de estimativa de tempo não pode ser negativo")
}
if (isRest && workoutExercises && !workoutExercises.isEmpty()) {
throw new WorkoutDayException("Um dia de descanso não pode conter exercícios")
}
if (workoutExercises == null) {
workoutExercises = []
}
workoutExercises = workoutExercises.asImmutable()
}
int calculateTotalTime() {
return workoutExercises.sum { it.estimatedTime() } ?: 0 as int
}
}

View file

@ -0,0 +1,43 @@
package br.dev.jsilveira.coresync.domain.model
import br.dev.jsilveira.coresync.domain.exception.WorkoutExerciseException
import java.time.LocalDateTime
record WorkoutExercise(
UUID id,
Integer order = 0,
String name,
Integer sets,
Integer reps,
Integer restTimeInSeconds,
UUID workoutDayId,
LocalDateTime createdAt = LocalDateTime.now(),
LocalDateTime updatedAt = LocalDateTime.now()
) {
public WorkoutExercise {
if (id == null){
throw new WorkoutExerciseException("O campo de identificação não pode ser nulo")
}
if (!name?.trim()) {
throw new WorkoutExerciseException("O campo de nome não estar vazio")
}
if (sets < 1) {
throw new WorkoutExerciseException("O campo de séries deve ser maior que zero")
}
if (reps < 1) {
throw new WorkoutExerciseException("O campo de repetições deve ser maior que zero")
}
if (restTimeInSeconds < 1) {
throw new WorkoutExerciseException("O campo de tempo de descanso deve ser maior que zero")
}
if (workoutDayId == null){
throw new WorkoutExerciseException("O campo de identificação do dia de treino não pode ser nulo")
}
}
}

View file

@ -0,0 +1,34 @@
package br.dev.jsilveira.coresync.domain.model
import br.dev.jsilveira.coresync.domain.exception.WorkoutPlanException
import java.time.LocalDateTime
record WorkoutPlan(
UUID id,
String name,
UUID userId,
Boolean isActive = Boolean.FALSE,
LocalDateTime createdAt = LocalDateTime.now(),
LocalDateTime updateAt = LocaDateTime.now(),
List<WorkoutDay> workoutDays = []
) {
public WorkoutPlan {
if (id == null){
throw new WorkoutPlanException("O campo de identificação não pode ser nulo")
}
if (!name?.trim()) {
throw new WorkoutPlanException("O campo de nome não pode estar vazio")
}
if (userId == null) {
throw new WorkoutPlanException("O campo de identificação do usuário não pode ser nulo")
}
if (workoutDays == null) {
workoutDays = []
}
workoutDays = workoutDays.asImmutable()
}
}

View file

@ -0,0 +1 @@
spring.application.name=coresync

View file

@ -0,0 +1,13 @@
package br.dev.jsilveira.coresync
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class CoresyncApplicationTests {
@Test
void contextLoads() {
}
}