From 4b7b8649d3b2012e563e7a5dcd689aaa56f7dbfd Mon Sep 17 00:00:00 2001 From: Aboubacar SANGARE Date: Tue, 23 Sep 2025 11:19:21 +0000 Subject: [PATCH] implemented models and logic for Cheval, Course, CourseCheval and Pari. --- .gitattributes | 2 + .gitignore | 236 ++++++++++++++ .mvn/wrapper/maven-wrapper.properties | 3 + mvnw | 295 ++++++++++++++++++ mvnw.cmd | 189 +++++++++++ pom.xml | 103 ++++++ .../java/com/pmumali/plr/PlrApplication.java | 13 + .../plr/controllers/ChevalController.java | 83 +++++ .../plr/controllers/CourseController.java | 221 +++++++++++++ .../plr/controllers/PariController.java | 89 ++++++ .../plr/dtos/BulkChevalCourseRequest.java | 8 + .../com/pmumali/plr/dtos/ChevalCourseDto.java | 3 + .../plr/dtos/ChevalCourseEstDisqualifie.java | 3 + .../plr/dtos/ChevalCourseNonPartantDto.java | 3 + ...hevalCourseNonPartantEtEstDisqualifie.java | 3 + .../java/com/pmumali/plr/dtos/ChevalDto.java | 3 + .../java/com/pmumali/plr/dtos/CourseDto.java | 7 + .../java/com/pmumali/plr/dtos/PariDto.java | 7 + .../com/pmumali/plr/enums/CourseStatue.java | 5 + .../java/com/pmumali/plr/enums/PariType.java | 5 + .../com/pmumali/plr/models/BaseEntite.java | 30 ++ .../java/com/pmumali/plr/models/Cheval.java | 26 ++ .../com/pmumali/plr/models/ChevalCourse.java | 39 +++ .../java/com/pmumali/plr/models/Course.java | 29 ++ .../java/com/pmumali/plr/models/Pari.java | 33 ++ .../repositories/ChevalCourseRepository.java | 38 +++ .../plr/repositories/ChevalRepository.java | 7 + .../plr/repositories/CourseRepository.java | 14 + .../plr/repositories/PariRepository.java | 26 ++ .../pmumali/plr/services/ChevalService.java | 45 +++ .../pmumali/plr/services/CourseService.java | 238 ++++++++++++++ .../com/pmumali/plr/services/PariService.java | 65 ++++ src/main/resources/application.yml | 28 ++ .../com/pmumali/plr/PlrApplicationTests.java | 13 + 34 files changed, 1912 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/pmumali/plr/PlrApplication.java create mode 100644 src/main/java/com/pmumali/plr/controllers/ChevalController.java create mode 100644 src/main/java/com/pmumali/plr/controllers/CourseController.java create mode 100644 src/main/java/com/pmumali/plr/controllers/PariController.java create mode 100644 src/main/java/com/pmumali/plr/dtos/BulkChevalCourseRequest.java create mode 100644 src/main/java/com/pmumali/plr/dtos/ChevalCourseDto.java create mode 100644 src/main/java/com/pmumali/plr/dtos/ChevalCourseEstDisqualifie.java create mode 100644 src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantDto.java create mode 100644 src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantEtEstDisqualifie.java create mode 100644 src/main/java/com/pmumali/plr/dtos/ChevalDto.java create mode 100644 src/main/java/com/pmumali/plr/dtos/CourseDto.java create mode 100644 src/main/java/com/pmumali/plr/dtos/PariDto.java create mode 100644 src/main/java/com/pmumali/plr/enums/CourseStatue.java create mode 100644 src/main/java/com/pmumali/plr/enums/PariType.java create mode 100644 src/main/java/com/pmumali/plr/models/BaseEntite.java create mode 100644 src/main/java/com/pmumali/plr/models/Cheval.java create mode 100644 src/main/java/com/pmumali/plr/models/ChevalCourse.java create mode 100644 src/main/java/com/pmumali/plr/models/Course.java create mode 100644 src/main/java/com/pmumali/plr/models/Pari.java create mode 100644 src/main/java/com/pmumali/plr/repositories/ChevalCourseRepository.java create mode 100644 src/main/java/com/pmumali/plr/repositories/ChevalRepository.java create mode 100644 src/main/java/com/pmumali/plr/repositories/CourseRepository.java create mode 100644 src/main/java/com/pmumali/plr/repositories/PariRepository.java create mode 100644 src/main/java/com/pmumali/plr/services/ChevalService.java create mode 100644 src/main/java/com/pmumali/plr/services/CourseService.java create mode 100644 src/main/java/com/pmumali/plr/services/PariService.java create mode 100644 src/main/resources/application.yml create mode 100644 src/test/java/com/pmumali/plr/PlrApplicationTests.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..95d8e96 --- /dev/null +++ b/.gitignore @@ -0,0 +1,236 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + + +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + + +# Created by https://www.gitignore.io/api/git,java,maven,eclipse,windows + +### Eclipse ### + +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Annotation Processing +.apt_generated/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet + +### Eclipse Patch ### +# Eclipse Core +.project + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# Annotation Processing +.apt_generated + +.sts4-cache/ + +### Git ### +# Created by git for backups. To disable backups in Git: +# $ git config --global mergetool.keepBackup false +*.orig + +# Created by git when using merge tools for conflicts +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Some additional ignores (sort later) +*.DS_Store +*.sw? +.#* +*# +*~ +.classpath +.project +.settings +bin +build +target +dependency-reduced-pom.xml +*.sublime-* +/scratch +.gradle +README.html +*.iml +.idea +.exercism \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c0bcafe --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..962cbb9 --- /dev/null +++ b/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.6 + + + com.pmumali + plr + 0.0.1-SNAPSHOT + plr + Demo project for Spring Boot + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.flywaydb + flyway-database-postgresql + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.8.13 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/com/pmumali/plr/PlrApplication.java b/src/main/java/com/pmumali/plr/PlrApplication.java new file mode 100644 index 0000000..ea1acfa --- /dev/null +++ b/src/main/java/com/pmumali/plr/PlrApplication.java @@ -0,0 +1,13 @@ +package com.pmumali.plr; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PlrApplication { + + public static void main(String[] args) { + SpringApplication.run(PlrApplication.class, args); + } + +} diff --git a/src/main/java/com/pmumali/plr/controllers/ChevalController.java b/src/main/java/com/pmumali/plr/controllers/ChevalController.java new file mode 100644 index 0000000..d685aa4 --- /dev/null +++ b/src/main/java/com/pmumali/plr/controllers/ChevalController.java @@ -0,0 +1,83 @@ +package com.pmumali.plr.controllers; + +import java.net.URI; +import java.util.List; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.pmumali.plr.dtos.ChevalDto; +import com.pmumali.plr.models.Cheval; +import com.pmumali.plr.services.ChevalService; + +import io.swagger.v3.oas.annotations.Operation; +import lombok.Data; + +@Data +@RestController +@RequestMapping("/api/chevaux") +public class ChevalController { + private final ChevalService chevalService; + + @Operation(summary = "Créer un cheval") + @PostMapping + public ResponseEntity create(@RequestBody ChevalDto dto) { + Cheval ch = new Cheval(); + ch.setNom(dto.nom()); + ch.setNumero(dto.numero()); + ch.setNomEcurie(dto.nomEcurie()); + ch.setBirthYear(dto.birthYear()); + + ch = chevalService.create(ch); + + ChevalDto response = new ChevalDto(ch.getId(), ch.getNom(), ch.getNumero(), ch.getNomEcurie(), + ch.getBirthYear()); + return ResponseEntity.created(URI.create("/api/chevaux/" + ch.getId())).body(response); + } + + @Operation(summary = "Lister tous les chevaux") + @GetMapping + public ResponseEntity> all() { + List list = chevalService.all().stream() + .map(h -> new ChevalDto(h.getId(), h.getNom(), h.getNumero(), h.getNomEcurie(), h.getBirthYear())) + .toList(); + return ResponseEntity.ok(list); + } + + @Operation(summary = "Récupérer un cheval par id") + @GetMapping("/{id}") + public ResponseEntity one(@PathVariable Long id) { + Cheval h = chevalService.get(id); + ChevalDto dto = new ChevalDto(h.getId(), h.getNom(), h.getNumero(), h.getNomEcurie(), h.getBirthYear()); + return ResponseEntity.ok(dto); + } + + @Operation(summary = "Mettre à jour un cheval") + @PutMapping("/{id}") + public ResponseEntity update(@PathVariable Long id, @RequestBody ChevalDto dto) { + Cheval ch = new Cheval(); + ch.setNom(dto.nom()); + ch.setNumero(dto.numero()); + ch.setNomEcurie(dto.nomEcurie()); + ch.setBirthYear(dto.birthYear()); + + ch = chevalService.update(id, ch); + ChevalDto response = new ChevalDto(ch.getId(), ch.getNom(), ch.getNumero(), ch.getNomEcurie(), + ch.getBirthYear()); + return ResponseEntity.ok(response); + } + + @Operation(summary = "Supprimer un cheval") + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + chevalService.delete(id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/pmumali/plr/controllers/CourseController.java b/src/main/java/com/pmumali/plr/controllers/CourseController.java new file mode 100644 index 0000000..267b254 --- /dev/null +++ b/src/main/java/com/pmumali/plr/controllers/CourseController.java @@ -0,0 +1,221 @@ +package com.pmumali.plr.controllers; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.pmumali.plr.dtos.BulkChevalCourseRequest; +import com.pmumali.plr.dtos.ChevalCourseDto; +import com.pmumali.plr.dtos.CourseDto; +import com.pmumali.plr.enums.CourseStatue; +import com.pmumali.plr.models.ChevalCourse; +import com.pmumali.plr.models.Course; +import com.pmumali.plr.services.CourseService; + +import io.swagger.v3.oas.annotations.Operation; +import lombok.AllArgsConstructor; +import lombok.Data; + +@RestController +@RequestMapping("/api/courses") +@Data +@AllArgsConstructor +public class CourseController { + private final CourseService courseService; + + @Operation(summary = "Créer une course") + @PostMapping + public ResponseEntity create(@RequestBody CourseDto dto) { + Course c = new Course(); + + c.setNom(dto.nom()); + c.setLieu(dto.lieu()); + c.setDepartureDateTime(dto.departureDateTime()); + c.setStatus(dto.status()); + + c = courseService.create(c); + CourseDto result = new CourseDto(c.getId(), c.getNom(), c.getLieu(), c.getDepartureDateTime(), c.getStatus()); + + return ResponseEntity.created(URI.create("/api/courses/" + c.getId())).body(result); + } + + /** GET /api/courses - list all or filter by status ?status=PLANIFIEE */ + @Operation(summary = "Récupérer une course par son id") + @GetMapping("{id}") + public ResponseEntity getCourse( + @PathVariable Long id) { + Course course = courseService.get(id); + CourseDto response = new CourseDto(course.getId(), course.getNom(), course.getLieu(), + course.getDepartureDateTime(), course.getStatus()); + return ResponseEntity.ok(response); + } + + /** GET /api/courses - list all or filter by status ?status=PLANIFIEE */ + @Operation(summary = "Lister tous les courses filtrer ou non par le statue") + @GetMapping + public ResponseEntity> listAll( + @RequestParam(value = "status", required = false) CourseStatue status) { + List courses = (status == null) ? courseService.getAllCourses() + : courseService.getCoursesByStatus(status); + + List dtos = courses.stream() + .map(c -> new CourseDto(c.getId(), c.getNom(), c.getLieu(), c.getDepartureDateTime(), c.getStatus())) + .toList(); + + return ResponseEntity.ok(dtos); + } + + /** PUT /api/courses/{id} - update course */ + @Operation(summary = "Mettre à jour une course") + @PutMapping("/{id}") + public ResponseEntity editCourse(@PathVariable Long id, @RequestBody CourseDto dto) { + // Build a Course entity from incoming DTO (only filled fields will be applied) + Course update = new Course(); + update.setNom(dto.nom()); + update.setLieu(dto.lieu()); + update.setDepartureDateTime(dto.departureDateTime()); + update.setStatus(dto.status()); + + Course updated = courseService.updateCourse(id, update); + + CourseDto result = new CourseDto(updated.getId(), updated.getNom(), updated.getLieu(), + updated.getDepartureDateTime(), updated.getStatus()); + return ResponseEntity.ok(result); + } + + /** + * DELETE /api/courses/{id} + * - default soft delete (cancels the race) + * - pass ?hard=true to attempt a hard delete (physical removal) + */ + @Operation(summary = "Supprimer une course") + @DeleteMapping("/{id}") + public ResponseEntity deleteCourse(@PathVariable Long id, + @RequestParam(value = "hard", required = false, defaultValue = "false") boolean hard) { + try { + courseService.deleteCourse(id, hard); + if (!hard) { + // return the cancelled course representation + Course c = courseService.get(id); + CourseDto dto = new CourseDto(c.getId(), c.getNom(), c.getLieu(), c.getDepartureDateTime(), + c.getStatus()); + return ResponseEntity.ok(dto); + } else { + // hard delete succeeded: no content + return ResponseEntity.noContent().build(); + } + } catch (DataIntegrityViolationException ex) { + return ResponseEntity.status(409).body(java.util.Collections.singletonMap("error", ex.getMessage())); + } + } + + // Ajout d'un cheval à la course -> POST /api/courses/{id}/chevaux + @Operation(summary = "Ajouter un cheval à une course") + @PostMapping("/{id}/chevaux") + public ResponseEntity ajouterCheval(@PathVariable Long id, @RequestBody ChevalCourseDto dto) { + ChevalCourse rh = courseService.ajouterCheval(id, dto.chevalId(), dto.numeroCheval()); + + ChevalCourseDto response = new ChevalCourseDto( + rh.getId(), + rh.getCourse().getId(), + rh.getCheval().getId(), + rh.getNumeroCheval(), + rh.getNonPartant(), + rh.getEstDisqualifie()); + + return ResponseEntity.created(URI.create("/api/courses/" + id + "/chevaux/" + rh.getId())).body(response); + } + + @Operation(summary = "Ajouter des chevaux à une course") + @PostMapping("/{id}/chevaux/bulk") + public ResponseEntity bulkAddChevaux(@PathVariable("id") Long id, @RequestBody BulkChevalCourseRequest request) { + try { + List saved = courseService.ajouterChevauxBulk(id, request); + + List dtos = saved.stream() + .map(rh -> new ChevalCourseDto(rh.getId(), rh.getCourse().getId(), rh.getCheval().getId(), + rh.getNumeroCheval(), rh.getNonPartant(), rh.getEstDisqualifie())) + .collect(Collectors.toList()); + + return ResponseEntity.created(URI.create("/api/courses/" + id + "/chevaux")).body(dtos); + } catch (IllegalArgumentException e) { + // doublons dans la requête + return ResponseEntity.badRequest().body(Map.of("error", e.getMessage())); + } catch (DataIntegrityViolationException e) { + // conflit avec la DB (numéro déjà utilisé, contrainte unique) + return ResponseEntity.status(409).body(Map.of("error", e.getMessage())); + } + } + + // Lister les inscriptions d'une course + @Operation(summary = "Lister les chevaux inscrits à une course") + @GetMapping("/{id}/chevaux") + public List listChevaux(@PathVariable Long id) { + return courseService.getInscriptions(id).stream() + .map(rh -> new ChevalCourseDto(rh.getId(), rh.getCourse().getId(), rh.getCheval().getId(), + rh.getNumeroCheval(), rh.getNonPartant(), rh.getEstDisqualifie())) + .toList(); + } + + // Marquer un cheval comme non-partant (scratch) + @Operation(summary = "Marquer un cheval comme non-partant (NP) à une course") + @PutMapping("/cheval-course/{chevalCourseId}/scratch") + public ResponseEntity scratch(@PathVariable Long chevalCourseId, @RequestParam boolean value) { + courseService.estNonPartant(chevalCourseId, value); + return ResponseEntity.noContent().build(); + } + + // Déclarer disqualifié + @Operation(summary = "Déclarer un cheval comme disqualifié à une course") + @PutMapping("/cheval-course/{chevalCourseId}/disqualify") + public ResponseEntity disqualify(@PathVariable Long chevalCourseId, @RequestParam boolean value) { + courseService.declarerDisqualifie(chevalCourseId, value); + return ResponseEntity.noContent().build(); + } + + // Supprimer inscription + @Operation(summary = "Supprimer un cheval inscrit d'une course") + @DeleteMapping("/cheval-course/{chevalCourseId}") + public ResponseEntity removeInscription(@PathVariable Long chevalCourseId) { + courseService.removeChevalFromCourse(chevalCourseId); + return ResponseEntity.noContent().build(); + } + + // Autres endpoints utiles : counts + @Operation(summary = "Compter les chevaux non-partants à une course") + @GetMapping("/{id}/counts/non-partants") + public int countNonPartants(@PathVariable Long id) { + return courseService.countNonPartants(id); + } + + @Operation(summary = "Compter les chevaux partants à une course") + @GetMapping("/{id}/counts/valid-participants") + public int countValidParticipants(@PathVariable Long id) { + return courseService.countValidParticipants(id); + } + + @Operation(summary = "Lister les course par statue (PLANIFIEE, EN_COURS, CLOTUREE, ANNULEE)") + @GetMapping("/status/{status}") + public ResponseEntity> getCoursesByStatus(@PathVariable("status") CourseStatue status) { + List courses = courseService.getCoursesByCourseStatue(status); + + List dtos = courses.stream() + .map(c -> new CourseDto(c.getId(), c.getNom(), c.getLieu(), c.getDepartureDateTime(), c.getStatus())) + .toList(); + + return ResponseEntity.ok(dtos); + } +} diff --git a/src/main/java/com/pmumali/plr/controllers/PariController.java b/src/main/java/com/pmumali/plr/controllers/PariController.java new file mode 100644 index 0000000..319aac3 --- /dev/null +++ b/src/main/java/com/pmumali/plr/controllers/PariController.java @@ -0,0 +1,89 @@ +package com.pmumali.plr.controllers; + +import java.net.URI; +import java.util.List; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.pmumali.plr.dtos.PariDto; +import com.pmumali.plr.enums.PariType; +import com.pmumali.plr.models.Pari; +import com.pmumali.plr.services.PariService; + +import io.swagger.v3.oas.annotations.Operation; +import lombok.AllArgsConstructor; +import lombok.Data; + +@RestController +@RequestMapping("/api/paris") +@Data +@AllArgsConstructor +public class PariController { + private final PariService pariService; + + @Operation(summary = "Placer un pari") + @PostMapping + public ResponseEntity create(@RequestBody PariDto dto) { + Pari p = pariService.create(dto.courseId(), dto.chevalId(), dto.pariType(), dto.mise(), dto.bettorRef()); + PariDto response = new PariDto(p.getId(), p.getCourse().getId(), p.getCheval().getId(), p.getPariType(), + p.getMise(), p.getBettorRef()); + return ResponseEntity.created(URI.create("/api/paris/" + p.getId())).body(response); + } + + @Operation(summary = "Lister tous les paris") + @GetMapping + public ResponseEntity> all() { + List list = pariService.all().stream() + .map(h -> new PariDto(h.getId(), h.getCourse().getId(), h.getCheval().getId(), h.getPariType(), + h.getMise(), h.getBettorRef())) + .toList(); + return ResponseEntity.ok(list); + } + + @Operation(summary = "Récupérer un pari par id") + @GetMapping("/{id}") + public ResponseEntity one(@PathVariable Long id) { + Pari p = pariService.get(id); + PariDto dto = new PariDto(p.getId(), p.getCourse().getId(), p.getCheval().getId(), p.getPariType(), p.getMise(), + p.getBettorRef()); + return ResponseEntity.ok(dto); + } + + // Recherche par type (ex: SIMPLE_GAGNANT) + @Operation(summary = "Lister les paris par type") + @GetMapping("/type/{pariType}") + public ResponseEntity> getAllByPariType(@PathVariable PariType pariType) { + List list = pariService.getParisByPariType(pariType).stream() + .map(h -> new PariDto(h.getId(), h.getCourse().getId(), h.getCheval().getId(), h.getPariType(), + h.getMise(), h.getBettorRef())) + .toList(); + return ResponseEntity.ok(list); + } + + // Recherche par course et type + @Operation(summary = "Lister les paris par course + type") + @GetMapping("/course/{courseId}/type/{pariType}") + public ResponseEntity> getByCourseAndType(@PathVariable Long courseId, + @PathVariable PariType pariType) { + List list = pariService.getParisByCourseAndType(courseId, pariType).stream() + .map(h -> new PariDto(h.getId(), h.getCourse().getId(), h.getCheval().getId(), h.getPariType(), + h.getMise(), h.getBettorRef())) + .toList(); + return ResponseEntity.ok(list); + } + + // Somme des mises d'une course / type (utile pour calculs de pools) + @Operation(summary = "Total des mises pour une course et un type de pari") + @GetMapping("/course/{courseId}/type/{pariType}/sum") + public ResponseEntity sumMises(@PathVariable Long courseId, @PathVariable PariType pariType) { + java.math.BigDecimal total = pariService.sumMiseByCourseIdAndPariType(courseId, pariType); + return ResponseEntity.ok(total); + } + +} diff --git a/src/main/java/com/pmumali/plr/dtos/BulkChevalCourseRequest.java b/src/main/java/com/pmumali/plr/dtos/BulkChevalCourseRequest.java new file mode 100644 index 0000000..7585119 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/BulkChevalCourseRequest.java @@ -0,0 +1,8 @@ +package com.pmumali.plr.dtos; + +import java.util.List; + +public record BulkChevalCourseRequest(List entries) { + public static record ChevalEntry(Long chevalId, Integer numeroCheval) { + } +} diff --git a/src/main/java/com/pmumali/plr/dtos/ChevalCourseDto.java b/src/main/java/com/pmumali/plr/dtos/ChevalCourseDto.java new file mode 100644 index 0000000..1ce4da5 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/ChevalCourseDto.java @@ -0,0 +1,3 @@ +package com.pmumali.plr.dtos; + +public record ChevalCourseDto(Long id, Long courseId, Long chevalId, Integer numeroCheval, Boolean nonPartant, Boolean estDisqualifie) {} diff --git a/src/main/java/com/pmumali/plr/dtos/ChevalCourseEstDisqualifie.java b/src/main/java/com/pmumali/plr/dtos/ChevalCourseEstDisqualifie.java new file mode 100644 index 0000000..b40c665 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/ChevalCourseEstDisqualifie.java @@ -0,0 +1,3 @@ +package com.pmumali.plr.dtos; + +public record ChevalCourseEstDisqualifie(Long chevalId, Boolean estDisqualifie) {} diff --git a/src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantDto.java b/src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantDto.java new file mode 100644 index 0000000..f06bf62 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantDto.java @@ -0,0 +1,3 @@ +package com.pmumali.plr.dtos; + +public record ChevalCourseNonPartantDto(Long chevalId, Integer nonPartant) {} diff --git a/src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantEtEstDisqualifie.java b/src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantEtEstDisqualifie.java new file mode 100644 index 0000000..d5f7611 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/ChevalCourseNonPartantEtEstDisqualifie.java @@ -0,0 +1,3 @@ +package com.pmumali.plr.dtos; + +public record ChevalCourseNonPartantEtEstDisqualifie(Long chevalId, Boolean nonPartant, Boolean estDisqualifie) {} diff --git a/src/main/java/com/pmumali/plr/dtos/ChevalDto.java b/src/main/java/com/pmumali/plr/dtos/ChevalDto.java new file mode 100644 index 0000000..2885bf5 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/ChevalDto.java @@ -0,0 +1,3 @@ +package com.pmumali.plr.dtos; + +public record ChevalDto(Long id, String nom, Integer numero, String nomEcurie, Integer birthYear) {} diff --git a/src/main/java/com/pmumali/plr/dtos/CourseDto.java b/src/main/java/com/pmumali/plr/dtos/CourseDto.java new file mode 100644 index 0000000..fbca2f1 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/CourseDto.java @@ -0,0 +1,7 @@ +package com.pmumali.plr.dtos; + +import java.time.LocalDateTime; + +import com.pmumali.plr.enums.CourseStatue; + +public record CourseDto(Long id, String nom, String lieu, LocalDateTime departureDateTime, CourseStatue status){} \ No newline at end of file diff --git a/src/main/java/com/pmumali/plr/dtos/PariDto.java b/src/main/java/com/pmumali/plr/dtos/PariDto.java new file mode 100644 index 0000000..960d9c0 --- /dev/null +++ b/src/main/java/com/pmumali/plr/dtos/PariDto.java @@ -0,0 +1,7 @@ +package com.pmumali.plr.dtos; + +import java.math.BigDecimal; + +import com.pmumali.plr.enums.PariType; + +public record PariDto(Long id, Long courseId, Long chevalId, PariType pariType, BigDecimal mise, String bettorRef) {} diff --git a/src/main/java/com/pmumali/plr/enums/CourseStatue.java b/src/main/java/com/pmumali/plr/enums/CourseStatue.java new file mode 100644 index 0000000..f7a2dba --- /dev/null +++ b/src/main/java/com/pmumali/plr/enums/CourseStatue.java @@ -0,0 +1,5 @@ +package com.pmumali.plr.enums; + +public enum CourseStatue { + PLANIFIEE, EN_COURS, CLOTUREE, ANNULEE +} diff --git a/src/main/java/com/pmumali/plr/enums/PariType.java b/src/main/java/com/pmumali/plr/enums/PariType.java new file mode 100644 index 0000000..060dfa6 --- /dev/null +++ b/src/main/java/com/pmumali/plr/enums/PariType.java @@ -0,0 +1,5 @@ +package com.pmumali.plr.enums; + +public enum PariType { + SIMPLE_GAGNANT, SIMPLE_PLACE +} diff --git a/src/main/java/com/pmumali/plr/models/BaseEntite.java b/src/main/java/com/pmumali/plr/models/BaseEntite.java new file mode 100644 index 0000000..bd40757 --- /dev/null +++ b/src/main/java/com/pmumali/plr/models/BaseEntite.java @@ -0,0 +1,30 @@ +package com.pmumali.plr.models; + +import java.time.LocalDateTime; + +import jakarta.persistence.Column; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.PreUpdate; +import lombok.Data; + +@Data +@MappedSuperclass +public abstract class BaseEntite { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @Column(name="created_at") + protected LocalDateTime createdAt = LocalDateTime.now(); + + @Column(name="updated_at") + protected LocalDateTime updatedAt = LocalDateTime.now(); + + @PreUpdate protected void onUpdate() + { + this.updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/pmumali/plr/models/Cheval.java b/src/main/java/com/pmumali/plr/models/Cheval.java new file mode 100644 index 0000000..3efac73 --- /dev/null +++ b/src/main/java/com/pmumali/plr/models/Cheval.java @@ -0,0 +1,26 @@ +package com.pmumali.plr.models; + + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + + +@Entity +@Data +@Getter +@Setter +@EqualsAndHashCode(callSuper=false) +public class Cheval extends BaseEntite { + private String nom; + + private Integer numero; + + private String nomEcurie; + + @Column(name = "birth_year") + private Integer birthYear; +} diff --git a/src/main/java/com/pmumali/plr/models/ChevalCourse.java b/src/main/java/com/pmumali/plr/models/ChevalCourse.java new file mode 100644 index 0000000..be1d94b --- /dev/null +++ b/src/main/java/com/pmumali/plr/models/ChevalCourse.java @@ -0,0 +1,39 @@ +package com.pmumali.plr.models; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + + +@Entity +@Table( + name = "cheval_course", + uniqueConstraints = @UniqueConstraint(name="uk_course_numero", columnNames = {"course_id","numero_cheval"}) +) +@Data +@Getter +@Setter +@EqualsAndHashCode(callSuper=false) +public class ChevalCourse extends BaseEntite { + @ManyToOne(optional = false) @JoinColumn(name="course_id") + private Course course; + + @ManyToOne(optional = false) @JoinColumn(name="cheval_id") + private Cheval cheval; + + @Column(name="numero_cheval", nullable=false) + private Integer numeroCheval; + + @Column(name="non_partant", nullable=false) + private Boolean nonPartant = false; + + @Column(name="est_disqualifie", nullable=false) + private Boolean estDisqualifie = false; +} diff --git a/src/main/java/com/pmumali/plr/models/Course.java b/src/main/java/com/pmumali/plr/models/Course.java new file mode 100644 index 0000000..7ad2e49 --- /dev/null +++ b/src/main/java/com/pmumali/plr/models/Course.java @@ -0,0 +1,29 @@ +package com.pmumali.plr.models; + +import java.time.LocalDateTime; + +import com.pmumali.plr.enums.CourseStatue; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + + +@Entity +@Data +@Getter +@Setter +@EqualsAndHashCode(callSuper=false) +public class Course extends BaseEntite { + private String nom; + + private String lieu; + + @Column(name="date_depart") + private LocalDateTime departureDateTime; + + private CourseStatue status = CourseStatue.PLANIFIEE; +} diff --git a/src/main/java/com/pmumali/plr/models/Pari.java b/src/main/java/com/pmumali/plr/models/Pari.java new file mode 100644 index 0000000..a06c6cf --- /dev/null +++ b/src/main/java/com/pmumali/plr/models/Pari.java @@ -0,0 +1,33 @@ +package com.pmumali.plr.models; + +import java.math.BigDecimal; + +import com.pmumali.plr.enums.PariType; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +@Data +@Entity +@Getter +@Setter +@EqualsAndHashCode(callSuper=false) +public class Pari extends BaseEntite { + @ManyToOne(optional=false) + private Course course; + + @ManyToOne(optional=false) + private Cheval cheval; + + private PariType pariType; + + @Column(nullable=false) + private BigDecimal mise; + + private String bettorRef; +} diff --git a/src/main/java/com/pmumali/plr/repositories/ChevalCourseRepository.java b/src/main/java/com/pmumali/plr/repositories/ChevalCourseRepository.java new file mode 100644 index 0000000..d0009de --- /dev/null +++ b/src/main/java/com/pmumali/plr/repositories/ChevalCourseRepository.java @@ -0,0 +1,38 @@ +package com.pmumali.plr.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.pmumali.plr.models.ChevalCourse; +import com.pmumali.plr.models.Course; + +public interface ChevalCourseRepository extends JpaRepository { + // Retourne les chevaux non-partants pour une course + List findByCourseAndNonPartantTrue(Course course); + + // Retourne les chevaux disqualifiés pour une course + List findByCourseAndEstDisqualifieTrue(Course course); + + // Comptes + int countByCourseAndNonPartantTrue(Course course); + + int countByCourseAndEstDisqualifieTrue(Course course); + + // Variantes avec param booléen si tu veux filtrer dynamiquement + List findByCourseAndNonPartant(Course course, Boolean nonPartant); + + List findByCourseAndEstDisqualifie(Course course, Boolean estDisqualifie); + + // Exemples utiles déjà présents + List findByCourseAndNonPartantFalse(Course course); + + int countByCourseAndNonPartantFalseAndEstDisqualifieFalse(Course course); + + // Récupérer toutes les inscriptions (ordre par numéro cheval utile) + List findByCourseOrderByNumeroChevalAsc(Course course); + + boolean existsByCourseAndNumeroCheval(Course course, Integer numeroCheval); + + int countByCourse(Course course); +} diff --git a/src/main/java/com/pmumali/plr/repositories/ChevalRepository.java b/src/main/java/com/pmumali/plr/repositories/ChevalRepository.java new file mode 100644 index 0000000..406e9f9 --- /dev/null +++ b/src/main/java/com/pmumali/plr/repositories/ChevalRepository.java @@ -0,0 +1,7 @@ +package com.pmumali.plr.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.pmumali.plr.models.Cheval; + +public interface ChevalRepository extends JpaRepository{} diff --git a/src/main/java/com/pmumali/plr/repositories/CourseRepository.java b/src/main/java/com/pmumali/plr/repositories/CourseRepository.java new file mode 100644 index 0000000..b5ee5ae --- /dev/null +++ b/src/main/java/com/pmumali/plr/repositories/CourseRepository.java @@ -0,0 +1,14 @@ +package com.pmumali.plr.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.pmumali.plr.enums.CourseStatue; +import com.pmumali.plr.models.Course; + +public interface CourseRepository extends JpaRepository { + List findByStatus(CourseStatue status); + + List findByStatusNot(CourseStatue status); +} diff --git a/src/main/java/com/pmumali/plr/repositories/PariRepository.java b/src/main/java/com/pmumali/plr/repositories/PariRepository.java new file mode 100644 index 0000000..b4b837a --- /dev/null +++ b/src/main/java/com/pmumali/plr/repositories/PariRepository.java @@ -0,0 +1,26 @@ +package com.pmumali.plr.repositories; + +import java.math.BigDecimal; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import com.pmumali.plr.enums.PariType; +import com.pmumali.plr.models.Pari; + +public interface PariRepository extends JpaRepository { + List findByCourseIdAndPariType(Long courseId, PariType pariType); + + List findByCourseIdAndPariTypeAndChevalId(Long courseId, PariType pariType, Long chevalId); + + List findByPariType(PariType pariType); + + @Query("select coalesce(sum(p.mise),0) from Pari p where p.course.id=:courseId and p.pariType=:pariType") + BigDecimal sumMiseByCourseIdAndPariType(Long courseId, PariType pariType); + + @Query("select coalesce(sum(p.mise),0) from Pari p where p.course.id=:courseId and p.pariType=:pariType and p.cheval.id=:chevalId") + BigDecimal sumMiseByCourseIdAndPariTypeAndChevalId(Long courseId, PariType pariType, Long chevalId); + + int countByCourseId(Long courseId); +} diff --git a/src/main/java/com/pmumali/plr/services/ChevalService.java b/src/main/java/com/pmumali/plr/services/ChevalService.java new file mode 100644 index 0000000..dcea465 --- /dev/null +++ b/src/main/java/com/pmumali/plr/services/ChevalService.java @@ -0,0 +1,45 @@ +package com.pmumali.plr.services; + +import java.util.List; + +import org.springframework.stereotype.Service; + +import com.pmumali.plr.models.Cheval; +import com.pmumali.plr.repositories.ChevalRepository; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Service +@Data +@AllArgsConstructor +public class ChevalService { + private final ChevalRepository chevalRepository; + + public Cheval create(Cheval cheval) { + return chevalRepository.save(cheval); + } + + public List all(){ + return chevalRepository.findAll(); + } + + public Cheval get(Long id){ + return chevalRepository.findById(id).orElseThrow(); + } + + public Cheval update(Long id, Cheval data){ + Cheval h = get(id); + + h.setNom(data.getNom()); + h.setNumero(data.getNumero()); + h.setNomEcurie(data.getNomEcurie()); + h.setBirthYear(data.getBirthYear()); + + return chevalRepository.save(h); + } + + public void delete(Long id){ + chevalRepository.deleteById(id); + } +} diff --git a/src/main/java/com/pmumali/plr/services/CourseService.java b/src/main/java/com/pmumali/plr/services/CourseService.java new file mode 100644 index 0000000..f2ecfc3 --- /dev/null +++ b/src/main/java/com/pmumali/plr/services/CourseService.java @@ -0,0 +1,238 @@ +package com.pmumali.plr.services; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.pmumali.plr.dtos.BulkChevalCourseRequest; +import com.pmumali.plr.enums.CourseStatue; +import com.pmumali.plr.models.Cheval; +import com.pmumali.plr.models.ChevalCourse; +import com.pmumali.plr.models.Course; +import com.pmumali.plr.repositories.ChevalCourseRepository; +import com.pmumali.plr.repositories.ChevalRepository; +import com.pmumali.plr.repositories.CourseRepository; +import com.pmumali.plr.repositories.PariRepository; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Service +@Data +@AllArgsConstructor +public class CourseService { + private final ChevalRepository chevalRepository; + private final CourseRepository courseRepository; + private final ChevalCourseRepository chevalCourseRepository; + private final PariRepository pariRepository; + + // Create a course + public Course create(Course course) { + return courseRepository.save(course); + } + + // Get a course by id + public Course get(Long id) { + return courseRepository.findById(id).orElseThrow(); + } + + // Get all courses + @Transactional(readOnly = true) + public List getAllCourses() { + return courseRepository.findAll(); + } + + // Get all courses by statue + @Transactional(readOnly = true) + public List getCoursesByStatus(CourseStatue status) { + return courseRepository.findByStatus(status); + } + + // Update a course + @Transactional + public Course updateCourse(Long id, Course data) { + Course existing = get(id); + + // Apply editable fields only + if (Objects.nonNull(data.getNom())) + existing.setNom(data.getNom()); + if (Objects.nonNull(data.getLieu())) + existing.setLieu(data.getLieu()); + if (Objects.nonNull(data.getDepartureDateTime())) + existing.setDepartureDateTime(data.getDepartureDateTime()); + if (Objects.nonNull(data.getStatus())) + existing.setStatus(data.getStatus()); + + return courseRepository.save(existing); + } + + @Transactional + public void deleteCourse(Long id, boolean hard) { + Course course = get(id); + + if (!hard) { + // soft delete: mark as canceled + course.setStatus(CourseStatue.ANNULEE); + courseRepository.save(course); + return; + } + + // hard delete: check constraints + int pariCount = pariRepository.countByCourseId(id); + int inscriptionCount = chevalCourseRepository.countByCourse(course); + + // optional: block if race already started or closed + if (course.getStatus() == CourseStatue.EN_COURS || course.getStatus() == CourseStatue.CLOTUREE) { + throw new DataIntegrityViolationException( + "Cannot hard delete a course which is in progress or already closed."); + } + + if (pariCount > 0) { + throw new DataIntegrityViolationException( + "Cannot hard delete course: there are " + pariCount + " pari(s) linked to this course."); + } + + if (inscriptionCount > 0) { + throw new DataIntegrityViolationException("Cannot hard delete course: there are " + inscriptionCount + + " cheval-course inscriptions linked to this course."); + } + + // safe to delete + courseRepository.deleteById(id); + } + + // Get all horses by a course (asc) + public List getInscriptions(Long courseId) { + Course course = get(courseId); + return chevalCourseRepository.findByCourseOrderByNumeroChevalAsc(course); + } + + public List getNonPartants(Long courseId) { + Course course = get(courseId); + return chevalCourseRepository.findByCourseAndNonPartantTrue(course); + } + + public int countNonPartants(Long courseId) { + Course course = get(courseId); + return chevalCourseRepository.countByCourseAndNonPartantTrue(course); + } + + public int countValidParticipants(Long courseId) { + Course course = get(courseId); + return chevalCourseRepository.countByCourseAndNonPartantFalseAndEstDisqualifieFalse(course); + } + + // Add a horse to a course + @Transactional + public ChevalCourse ajouterCheval(Long courseId, Long chevalId, Integer numeroCheval) { + Course course = get(courseId); + Cheval cheval = chevalRepository.findById(chevalId).orElseThrow(); + + ChevalCourse cc = new ChevalCourse(); + + cc.setCourse(course); + cc.setCheval(cheval); + cc.setNumeroCheval(numeroCheval); + + return chevalCourseRepository.save(cc); + } + + @Transactional + public void estNonPartant(Long chevalCourseId, Boolean nonPartant) { + ChevalCourse cc = chevalCourseRepository.findById(chevalCourseId).orElseThrow(); + + cc.setNonPartant(nonPartant); + + chevalCourseRepository.save(cc); + } + + @Transactional + public void declarerDisqualifie(Long chevalCourseId, Boolean disqualifie) { + ChevalCourse cc = chevalCourseRepository.findById(chevalCourseId).orElseThrow(); + + cc.setEstDisqualifie(disqualifie); + + chevalCourseRepository.save(cc); + } + + @Transactional + public void removeChevalFromCourse(Long chevalCourseId) { + chevalCourseRepository.deleteById(chevalCourseId); + } + + @Transactional(readOnly = true) + public List getCoursesByCourseStatue(CourseStatue courseStatue) { + return courseRepository.findByStatus(courseStatue); + } + + @Transactional + public List ajouterChevauxBulk(Long courseId, BulkChevalCourseRequest request) { + Course course = courseRepository.findById(courseId).orElseThrow(); + + List entries = request.entries(); + if (entries == null || entries.isEmpty()) { + return Collections.emptyList(); + } + + // 1) vérifier doublons dans la requête (par numeroCheval) + Set seenNum = new HashSet<>(); + List duplicateNums = entries.stream() + .map(BulkChevalCourseRequest.ChevalEntry::numeroCheval) + .filter(Objects::nonNull) + .filter(n -> !seenNum.add(n)) + .distinct() + .collect(Collectors.toList()); + + if (!duplicateNums.isEmpty()) { + throw new IllegalArgumentException("Duplicate numeroCheval in request: " + duplicateNums); + } + + // 2) vérifier si un numero est déjà utilisé dans la course + List numsToCheck = entries.stream() + .map(BulkChevalCourseRequest.ChevalEntry::numeroCheval) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + List conflicts = numsToCheck.stream() + .filter(n -> chevalCourseRepository.existsByCourseAndNumeroCheval(course, n)) + .distinct() + .collect(Collectors.toList()); + + if (!conflicts.isEmpty()) { + throw new DataIntegrityViolationException("Numero(s) already used for course: " + conflicts); + } + + // 3) Construire les entités ChevalCourse + List toSave = new ArrayList<>(entries.size()); + for (BulkChevalCourseRequest.ChevalEntry e : entries) { + Long chevalId = e.chevalId(); + Integer numero = e.numeroCheval(); + + Cheval cheval = chevalRepository.findById(chevalId).orElseThrow(); + + ChevalCourse cc = new ChevalCourse(); + cc.setCourse(course); + cc.setCheval(cheval); + cc.setNumeroCheval(numero); + // nonPartant et estDisqualifie restent par défaut false + + toSave.add(cc); + } + + // 4) saveAll (transactionnel) + try { + return chevalCourseRepository.saveAll(toSave); + } catch (DataIntegrityViolationException ex) { + throw new DataIntegrityViolationException( + "Constraint violation while saving bulk inscriptions: " + ex.getMessage(), ex); + } + } +} diff --git a/src/main/java/com/pmumali/plr/services/PariService.java b/src/main/java/com/pmumali/plr/services/PariService.java new file mode 100644 index 0000000..0c53a84 --- /dev/null +++ b/src/main/java/com/pmumali/plr/services/PariService.java @@ -0,0 +1,65 @@ +package com.pmumali.plr.services; + +import java.math.BigDecimal; +import java.util.List; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.pmumali.plr.enums.PariType; +import com.pmumali.plr.models.Cheval; +import com.pmumali.plr.models.Course; +import com.pmumali.plr.models.Pari; +import com.pmumali.plr.repositories.ChevalCourseRepository; +import com.pmumali.plr.repositories.ChevalRepository; +import com.pmumali.plr.repositories.CourseRepository; +import com.pmumali.plr.repositories.PariRepository; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Service +@Data +@AllArgsConstructor +public class PariService { + private final PariRepository pariRepository; + private final CourseRepository courseRepository; + private final ChevalRepository chevalRepository; + private final ChevalCourseRepository chevalCourseRepository; + + @Transactional + public Pari create(Long courseId, Long chevalId, PariType pariType, BigDecimal mise, String bettorRef) { + Cheval cheval = chevalRepository.findById(chevalId).orElseThrow(); + Course course = courseRepository.findById(courseId).orElseThrow(); + + Pari p = new Pari(); + + p.setCheval(cheval); + p.setCourse(course); + p.setPariType(pariType); + p.setMise(mise); + p.setBettorRef(bettorRef); + + return pariRepository.save(p); + } + + public Pari get(Long id) { + return pariRepository.findById(id).orElseThrow(); + } + + public List all() { + return pariRepository.findAll(); + } + + public List getParisByPariType(PariType pariType) { + return pariRepository.findByPariType(pariType); + } + + public List getParisByCourseAndType(Long courseId, PariType pariType) { + return pariRepository.findByCourseIdAndPariType(courseId, pariType); + } + + public java.math.BigDecimal sumMiseByCourseIdAndPariType(Long courseId, PariType pariType) { + return pariRepository.sumMiseByCourseIdAndPariType(courseId, pariType); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..38855dc --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,28 @@ +server: + port: 8080 + +spring: + application: + name: plr + datasource: + url: jdbc:postgresql://localhost:5432/pmu + username: postgres + password: + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + jdbc: + time_zone: UTC + open-in-view: false + flyway: + enabled: false + locations: classpath:db/migration + +springdoc: + api-docs: + path: /v3/api-docs + enabled: true + swagger-ui: + path: /swagger-ui.html diff --git a/src/test/java/com/pmumali/plr/PlrApplicationTests.java b/src/test/java/com/pmumali/plr/PlrApplicationTests.java new file mode 100644 index 0000000..48438ab --- /dev/null +++ b/src/test/java/com/pmumali/plr/PlrApplicationTests.java @@ -0,0 +1,13 @@ +package com.pmumali.plr; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class PlrApplicationTests { + + @Test + void contextLoads() { + } + +}