From d8f23c0cf57a73cb709e3b7cde9d7255624b4d5c Mon Sep 17 00:00:00 2001 From: Kevin Date: Wed, 28 Jan 2026 12:33:38 -0500 Subject: [PATCH] feat: implementar microservicios transaction y anti-fraud MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Agregar transaction-service con API REST (crear/consultar transacciones) - Agregar anti-fraud-service para validar transacciones (rechaza si value > 1000) - Integración con Kafka para comunicación asíncrona entre servicios - PostgreSQL para persistencia de transacciones - Spring Boot Actuator para health checks - Soporte Docker/Podman con docker-compose --- anti-fraud-service/.gitattributes | 2 + anti-fraud-service/.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + anti-fraud-service/Dockerfile | 28 ++ anti-fraud-service/mvnw | 295 ++++++++++++++++++ anti-fraud-service/mvnw.cmd | 189 +++++++++++ anti-fraud-service/pom.xml | 90 ++++++ .../AntiFraudServiceApplication.java | 13 + .../antifraudservice/config/KafkaConfig.java | 10 + .../dto/TransactionCreatedEvent.java | 18 ++ .../dto/TransactionStatusUpdateEvent.java | 17 + .../kafka/TransactionCreatedConsumer.java | 42 +++ .../kafka/TransactionStatusProducer.java | 31 ++ .../service/FraudValidationService.java | 20 ++ .../src/main/resources/application.yml | 33 ++ .../AntiFraudServiceApplicationTests.java | 13 + docker-compose.yml | 96 +++++- transaction-service/.gitattributes | 2 + transaction-service/.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + transaction-service/Dockerfile | 28 ++ transaction-service/mvnw | 295 ++++++++++++++++++ transaction-service/mvnw.cmd | 189 +++++++++++ transaction-service/pom.xml | 101 ++++++ .../TransactionServiceApplication.java | 13 + .../config/KafkaConfig.java | 29 ++ .../controller/TransactionController.java | 34 ++ .../dto/CreateTransactionRequest.java | 31 ++ .../dto/TransactionCreatedEvent.java | 18 ++ .../dto/TransactionResponse.java | 39 +++ .../dto/TransactionStatusUpdateEvent.java | 17 + .../entity/Transaction.java | 60 ++++ .../entity/TransactionStatus.java | 7 + .../entity/TransactionType.java | 27 ++ .../kafka/TransactionProducer.java | 30 ++ .../kafka/TransactionStatusConsumer.java | 35 +++ .../repository/TransactionRepository.java | 11 + .../service/TransactionService.java | 80 +++++ .../src/main/resources/application.yml | 49 +++ .../TransactionServiceApplicationTests.java | 13 + 40 files changed, 2061 insertions(+), 16 deletions(-) create mode 100644 anti-fraud-service/.gitattributes create mode 100644 anti-fraud-service/.gitignore create mode 100644 anti-fraud-service/.mvn/wrapper/maven-wrapper.properties create mode 100644 anti-fraud-service/Dockerfile create mode 100755 anti-fraud-service/mvnw create mode 100644 anti-fraud-service/mvnw.cmd create mode 100644 anti-fraud-service/pom.xml create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/AntiFraudServiceApplication.java create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/config/KafkaConfig.java create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionCreatedEvent.java create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionStatusUpdateEvent.java create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionCreatedConsumer.java create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionStatusProducer.java create mode 100644 anti-fraud-service/src/main/java/com/yape/antifraudservice/service/FraudValidationService.java create mode 100644 anti-fraud-service/src/main/resources/application.yml create mode 100644 anti-fraud-service/src/test/java/com/yape/antifraudservice/AntiFraudServiceApplicationTests.java create mode 100644 transaction-service/.gitattributes create mode 100644 transaction-service/.gitignore create mode 100644 transaction-service/.mvn/wrapper/maven-wrapper.properties create mode 100644 transaction-service/Dockerfile create mode 100755 transaction-service/mvnw create mode 100644 transaction-service/mvnw.cmd create mode 100644 transaction-service/pom.xml create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/TransactionServiceApplication.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/config/KafkaConfig.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/controller/TransactionController.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/dto/CreateTransactionRequest.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionCreatedEvent.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionResponse.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionStatusUpdateEvent.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/entity/Transaction.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionStatus.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionType.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionProducer.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionStatusConsumer.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/repository/TransactionRepository.java create mode 100644 transaction-service/src/main/java/com/yape/transactionservice/service/TransactionService.java create mode 100644 transaction-service/src/main/resources/application.yml create mode 100644 transaction-service/src/test/java/com/yape/transactionservice/TransactionServiceApplicationTests.java diff --git a/anti-fraud-service/.gitattributes b/anti-fraud-service/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/anti-fraud-service/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/anti-fraud-service/.gitignore b/anti-fraud-service/.gitignore new file mode 100644 index 0000000000..667aaef0c8 --- /dev/null +++ b/anti-fraud-service/.gitignore @@ -0,0 +1,33 @@ +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/ diff --git a/anti-fraud-service/.mvn/wrapper/maven-wrapper.properties b/anti-fraud-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..8dea6c227c --- /dev/null +++ b/anti-fraud-service/.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.12/apache-maven-3.9.12-bin.zip diff --git a/anti-fraud-service/Dockerfile b/anti-fraud-service/Dockerfile new file mode 100644 index 0000000000..a762137436 --- /dev/null +++ b/anti-fraud-service/Dockerfile @@ -0,0 +1,28 @@ +FROM docker.io/eclipse-temurin:21-jdk-alpine AS build + +WORKDIR /app + +COPY .mvn/ .mvn/ +COPY mvnw pom.xml ./ +RUN chmod +x mvnw && ./mvnw dependency:go-offline -B + +COPY src ./src +RUN ./mvnw package -DskipTests -B + +FROM docker.io/eclipse-temurin:21-jre-alpine + +WORKDIR /app + +RUN apk add --no-cache curl && \ + addgroup -g 1001 -S appgroup && \ + adduser -u 1001 -S appuser -G appgroup + +COPY --from=build /app/target/*.jar app.jar + +RUN chown -R appuser:appgroup /app + +USER appuser + +EXPOSE 8081 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/anti-fraud-service/mvnw b/anti-fraud-service/mvnw new file mode 100755 index 0000000000..bd8896bf22 --- /dev/null +++ b/anti-fraud-service/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/anti-fraud-service/mvnw.cmd b/anti-fraud-service/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/anti-fraud-service/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/anti-fraud-service/pom.xml b/anti-fraud-service/pom.xml new file mode 100644 index 0000000000..fc5f880724 --- /dev/null +++ b/anti-fraud-service/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.2 + + + com.yape + anti-fraud-service + 0.0.1-SNAPSHOT + anti-fraud-service + Anti-fraud microservice for Yape Code Challenge + + + 21 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-json + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.kafka + spring-kafka + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/AntiFraudServiceApplication.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/AntiFraudServiceApplication.java new file mode 100644 index 0000000000..e070376356 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/AntiFraudServiceApplication.java @@ -0,0 +1,13 @@ +package com.yape.antifraudservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AntiFraudServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(AntiFraudServiceApplication.class, args); + } + +} diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/config/KafkaConfig.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/config/KafkaConfig.java new file mode 100644 index 0000000000..743b75dfb0 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/config/KafkaConfig.java @@ -0,0 +1,10 @@ +package com.yape.antifraudservice.config; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class KafkaConfig { + + public static final String TRANSACTION_CREATED_TOPIC = "transaction-created"; + public static final String TRANSACTION_STATUS_TOPIC = "transaction-status"; +} diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionCreatedEvent.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionCreatedEvent.java new file mode 100644 index 0000000000..c07031e80e --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionCreatedEvent.java @@ -0,0 +1,18 @@ +package com.yape.antifraudservice.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TransactionCreatedEvent { + private UUID transactionId; + private BigDecimal value; +} diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionStatusUpdateEvent.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionStatusUpdateEvent.java new file mode 100644 index 0000000000..763c559d31 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/dto/TransactionStatusUpdateEvent.java @@ -0,0 +1,17 @@ +package com.yape.antifraudservice.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TransactionStatusUpdateEvent { + private UUID transactionId; + private String status; +} diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionCreatedConsumer.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionCreatedConsumer.java new file mode 100644 index 0000000000..d63003c0bc --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionCreatedConsumer.java @@ -0,0 +1,42 @@ +package com.yape.antifraudservice.kafka; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.antifraudservice.config.KafkaConfig; +import com.yape.antifraudservice.dto.TransactionCreatedEvent; +import com.yape.antifraudservice.dto.TransactionStatusUpdateEvent; +import com.yape.antifraudservice.service.FraudValidationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionCreatedConsumer { + + private final FraudValidationService fraudValidationService; + private final TransactionStatusProducer transactionStatusProducer; + private final ObjectMapper objectMapper; + + @KafkaListener(topics = KafkaConfig.TRANSACTION_CREATED_TOPIC, groupId = "anti-fraud-service") + public void consumeTransactionCreated(String message) { + try { + TransactionCreatedEvent event = objectMapper.readValue(message, TransactionCreatedEvent.class); + log.info("Received transaction created event for transaction: {}", event.getTransactionId()); + + boolean isValid = fraudValidationService.isTransactionValid(event.getValue()); + String status = isValid ? "APPROVED" : "REJECTED"; + + TransactionStatusUpdateEvent statusEvent = TransactionStatusUpdateEvent.builder() + .transactionId(event.getTransactionId()) + .status(status) + .build(); + + transactionStatusProducer.sendStatusUpdate(statusEvent); + } catch (JsonProcessingException e) { + log.error("Error deserializing transaction created event", e); + } + } +} diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionStatusProducer.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionStatusProducer.java new file mode 100644 index 0000000000..5163666c95 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/kafka/TransactionStatusProducer.java @@ -0,0 +1,31 @@ +package com.yape.antifraudservice.kafka; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.antifraudservice.config.KafkaConfig; +import com.yape.antifraudservice.dto.TransactionStatusUpdateEvent; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionStatusProducer { + + private final KafkaTemplate kafkaTemplate; + private final ObjectMapper objectMapper; + + public void sendStatusUpdate(TransactionStatusUpdateEvent event) { + try { + String message = objectMapper.writeValueAsString(event); + kafkaTemplate.send(KafkaConfig.TRANSACTION_STATUS_TOPIC, event.getTransactionId().toString(), message); + log.info("Sent status update for transaction: {} with status: {}", + event.getTransactionId(), event.getStatus()); + } catch (JsonProcessingException e) { + log.error("Error serializing status update event", e); + throw new RuntimeException("Error serializing event", e); + } + } +} diff --git a/anti-fraud-service/src/main/java/com/yape/antifraudservice/service/FraudValidationService.java b/anti-fraud-service/src/main/java/com/yape/antifraudservice/service/FraudValidationService.java new file mode 100644 index 0000000000..9a022e4097 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/antifraudservice/service/FraudValidationService.java @@ -0,0 +1,20 @@ +package com.yape.antifraudservice.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; + +@Service +@Slf4j +public class FraudValidationService { + + private static final BigDecimal MAX_ALLOWED_VALUE = new BigDecimal("1000"); + + public boolean isTransactionValid(BigDecimal value) { + boolean isValid = value.compareTo(MAX_ALLOWED_VALUE) <= 0; + log.info("Transaction validation result: {} (value: {}, max: {})", + isValid ? "APPROVED" : "REJECTED", value, MAX_ALLOWED_VALUE); + return isValid; + } +} diff --git a/anti-fraud-service/src/main/resources/application.yml b/anti-fraud-service/src/main/resources/application.yml new file mode 100644 index 0000000000..274cd3a87c --- /dev/null +++ b/anti-fraud-service/src/main/resources/application.yml @@ -0,0 +1,33 @@ +server: + port: 8081 + +spring: + application: + name: anti-fraud-service + + kafka: + bootstrap-servers: ${SPRING_KAFKA_BOOTSTRAP_SERVERS:localhost:9092} + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + consumer: + group-id: anti-fraud-service + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + +management: + endpoints: + web: + exposure: + include: health + endpoint: + health: + show-details: always + +logging: + level: + root: WARN + com.yape: INFO + org.springframework.kafka: WARN + org.apache.kafka: WARN diff --git a/anti-fraud-service/src/test/java/com/yape/antifraudservice/AntiFraudServiceApplicationTests.java b/anti-fraud-service/src/test/java/com/yape/antifraudservice/AntiFraudServiceApplicationTests.java new file mode 100644 index 0000000000..7a99f1ddc7 --- /dev/null +++ b/anti-fraud-service/src/test/java/com/yape/antifraudservice/AntiFraudServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.antifraudservice; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AntiFraudServiceApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/docker-compose.yml b/docker-compose.yml index 0e8807f21c..ec24d45970 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,25 +1,89 @@ -version: "3.7" +version: "3.8" + services: postgres: - image: postgres:14 + image: docker.io/postgres:18.1-alpine3.23 + container_name: postgres ports: - "5432:5432" environment: - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=postgres - zookeeper: - image: confluentinc/cp-zookeeper:5.5.3 - environment: - ZOOKEEPER_CLIENT_PORT: 2181 + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: transactions_db + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 10s + timeout: 5s + retries: 5 + kafka: - image: confluentinc/cp-enterprise-kafka:5.5.3 - depends_on: [zookeeper] + image: docker.io/apache/kafka:4.1.1 + container_name: kafka + ports: + - "9092:9092" environment: - KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" - KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT - KAFKA_BROKER_ID: 1 + KAFKA_NODE_ID: 1 + KAFKA_PROCESS_ROLES: broker,controller + KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093 + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092 + KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT + KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 - KAFKA_JMX_PORT: 9991 + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 + KAFKA_LOG_DIRS: /tmp/kraft-combined-logs + CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk + healthcheck: + test: ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 || exit 1"] + interval: 30s + timeout: 10s + retries: 5 + + transaction-service: + build: + context: ./transaction-service + dockerfile: Dockerfile + container_name: transaction-service ports: - - 9092:9092 + - "8080:8080" + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/transactions_db + SPRING_DATASOURCE_USERNAME: postgres + SPRING_DATASOURCE_PASSWORD: postgres + SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092 + healthcheck: + test: ["CMD-SHELL", "curl -f http://localhost:8080/actuator/health || exit 1"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 30s + depends_on: + postgres: + condition: service_healthy + kafka: + condition: service_healthy + + anti-fraud-service: + build: + context: ./anti-fraud-service + dockerfile: Dockerfile + container_name: anti-fraud-service + ports: + - "8081:8081" + environment: + SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092 + healthcheck: + test: ["CMD-SHELL", "curl -f http://localhost:8081/actuator/health || exit 1"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 30s + depends_on: + kafka: + condition: service_healthy + +volumes: + postgres_data: diff --git a/transaction-service/.gitattributes b/transaction-service/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/transaction-service/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/transaction-service/.gitignore b/transaction-service/.gitignore new file mode 100644 index 0000000000..667aaef0c8 --- /dev/null +++ b/transaction-service/.gitignore @@ -0,0 +1,33 @@ +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/ diff --git a/transaction-service/.mvn/wrapper/maven-wrapper.properties b/transaction-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..8dea6c227c --- /dev/null +++ b/transaction-service/.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.12/apache-maven-3.9.12-bin.zip diff --git a/transaction-service/Dockerfile b/transaction-service/Dockerfile new file mode 100644 index 0000000000..6f15251982 --- /dev/null +++ b/transaction-service/Dockerfile @@ -0,0 +1,28 @@ +FROM docker.io/eclipse-temurin:21-jdk-alpine AS build + +WORKDIR /app + +COPY .mvn/ .mvn/ +COPY mvnw pom.xml ./ +RUN chmod +x mvnw && ./mvnw dependency:go-offline -B + +COPY src ./src +RUN ./mvnw package -DskipTests -B + +FROM docker.io/eclipse-temurin:21-jre-alpine + +WORKDIR /app + +RUN apk add --no-cache curl && \ + addgroup -g 1001 -S appgroup && \ + adduser -u 1001 -S appuser -G appgroup + +COPY --from=build /app/target/*.jar app.jar + +RUN chown -R appuser:appgroup /app + +USER appuser + +EXPOSE 8080 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/transaction-service/mvnw b/transaction-service/mvnw new file mode 100755 index 0000000000..bd8896bf22 --- /dev/null +++ b/transaction-service/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/transaction-service/mvnw.cmd b/transaction-service/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/transaction-service/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/transaction-service/pom.xml b/transaction-service/pom.xml new file mode 100644 index 0000000000..36d5a122b9 --- /dev/null +++ b/transaction-service/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.2 + + + com.yape + transaction-service + 0.0.1-SNAPSHOT + transaction-service + Transaction microservice for Yape Code Challenge + + + 21 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.kafka + spring-kafka + + + + org.postgresql + postgresql + runtime + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-validation + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/transaction-service/src/main/java/com/yape/transactionservice/TransactionServiceApplication.java b/transaction-service/src/main/java/com/yape/transactionservice/TransactionServiceApplication.java new file mode 100644 index 0000000000..2835f524f6 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/TransactionServiceApplication.java @@ -0,0 +1,13 @@ +package com.yape.transactionservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TransactionServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(TransactionServiceApplication.class, args); + } + +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/config/KafkaConfig.java b/transaction-service/src/main/java/com/yape/transactionservice/config/KafkaConfig.java new file mode 100644 index 0000000000..044ddbaecf --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/config/KafkaConfig.java @@ -0,0 +1,29 @@ +package com.yape.transactionservice.config; + +import org.apache.kafka.clients.admin.NewTopic; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.TopicBuilder; + +@Configuration +public class KafkaConfig { + + public static final String TRANSACTION_CREATED_TOPIC = "transaction-created"; + public static final String TRANSACTION_STATUS_TOPIC = "transaction-status"; + + @Bean + public NewTopic transactionCreatedTopic() { + return TopicBuilder.name(TRANSACTION_CREATED_TOPIC) + .partitions(1) + .replicas(1) + .build(); + } + + @Bean + public NewTopic transactionStatusTopic() { + return TopicBuilder.name(TRANSACTION_STATUS_TOPIC) + .partitions(1) + .replicas(1) + .build(); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/controller/TransactionController.java b/transaction-service/src/main/java/com/yape/transactionservice/controller/TransactionController.java new file mode 100644 index 0000000000..1fb54dc3f9 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/controller/TransactionController.java @@ -0,0 +1,34 @@ +package com.yape.transactionservice.controller; + +import com.yape.transactionservice.dto.CreateTransactionRequest; +import com.yape.transactionservice.dto.TransactionResponse; +import com.yape.transactionservice.service.TransactionService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.UUID; + +@RestController +@RequestMapping("/api/transactions") +@RequiredArgsConstructor +public class TransactionController { + + private final TransactionService transactionService; + + @PostMapping + public ResponseEntity createTransaction( + @Valid @RequestBody CreateTransactionRequest request) { + TransactionResponse response = transactionService.createTransaction(request); + return ResponseEntity.status(HttpStatus.CREATED).body(response); + } + + @GetMapping("/{transactionId}") + public ResponseEntity getTransaction( + @PathVariable UUID transactionId) { + TransactionResponse response = transactionService.getTransaction(transactionId); + return ResponseEntity.ok(response); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/dto/CreateTransactionRequest.java b/transaction-service/src/main/java/com/yape/transactionservice/dto/CreateTransactionRequest.java new file mode 100644 index 0000000000..0c6e5237c9 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/dto/CreateTransactionRequest.java @@ -0,0 +1,31 @@ +package com.yape.transactionservice.dto; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CreateTransactionRequest { + + @NotNull(message = "accountExternalIdDebit is required") + private UUID accountExternalIdDebit; + + @NotNull(message = "accountExternalIdCredit is required") + private UUID accountExternalIdCredit; + + @NotNull(message = "tranferTypeId is required") + private Integer tranferTypeId; + + @NotNull(message = "value is required") + @Positive(message = "value must be positive") + private BigDecimal value; +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionCreatedEvent.java b/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionCreatedEvent.java new file mode 100644 index 0000000000..95f89ecac3 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionCreatedEvent.java @@ -0,0 +1,18 @@ +package com.yape.transactionservice.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TransactionCreatedEvent { + private UUID transactionId; + private BigDecimal value; +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionResponse.java b/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionResponse.java new file mode 100644 index 0000000000..e8249523a1 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionResponse.java @@ -0,0 +1,39 @@ +package com.yape.transactionservice.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TransactionResponse { + + private UUID transactionExternalId; + private TransactionTypeDto transactionType; + private TransactionStatusDto transactionStatus; + private BigDecimal value; + private LocalDateTime createdAt; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class TransactionTypeDto { + private String name; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class TransactionStatusDto { + private String name; + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionStatusUpdateEvent.java b/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionStatusUpdateEvent.java new file mode 100644 index 0000000000..e4941f8a3f --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/dto/TransactionStatusUpdateEvent.java @@ -0,0 +1,17 @@ +package com.yape.transactionservice.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class TransactionStatusUpdateEvent { + private UUID transactionId; + private String status; +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/entity/Transaction.java b/transaction-service/src/main/java/com/yape/transactionservice/entity/Transaction.java new file mode 100644 index 0000000000..6b73d1cb41 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/entity/Transaction.java @@ -0,0 +1,60 @@ +package com.yape.transactionservice.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.UUID; + +@Entity +@Table(name = "transactions") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Transaction { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + @Column(name = "account_external_id_debit", nullable = false) + private UUID accountExternalIdDebit; + + @Column(name = "account_external_id_credit", nullable = false) + private UUID accountExternalIdCredit; + + @Enumerated(EnumType.STRING) + @Column(name = "transaction_type", nullable = false) + private TransactionType transactionType; + + @Column(nullable = false, precision = 19, scale = 2) + private BigDecimal value; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private TransactionStatus status; + + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + protected void onCreate() { + createdAt = LocalDateTime.now(); + if (status == null) { + status = TransactionStatus.PENDING; + } + } + + @PreUpdate + protected void onUpdate() { + updatedAt = LocalDateTime.now(); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionStatus.java b/transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionStatus.java new file mode 100644 index 0000000000..155e11e30a --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionStatus.java @@ -0,0 +1,7 @@ +package com.yape.transactionservice.entity; + +public enum TransactionStatus { + PENDING, + APPROVED, + REJECTED +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionType.java b/transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionType.java new file mode 100644 index 0000000000..ede2e428b8 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/entity/TransactionType.java @@ -0,0 +1,27 @@ +package com.yape.transactionservice.entity; + +import lombok.Getter; + +@Getter +public enum TransactionType { + TRANSFER(1, "Transfer"), + PAYMENT(2, "Payment"), + WITHDRAWAL(3, "Withdrawal"); + + private final int id; + private final String name; + + TransactionType(int id, String name) { + this.id = id; + this.name = name; + } + + public static TransactionType fromId(int id) { + for (TransactionType type : values()) { + if (type.getId() == id) { + return type; + } + } + throw new IllegalArgumentException("Invalid transaction type id: " + id); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionProducer.java b/transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionProducer.java new file mode 100644 index 0000000000..2c3b90142f --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionProducer.java @@ -0,0 +1,30 @@ +package com.yape.transactionservice.kafka; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.transactionservice.config.KafkaConfig; +import com.yape.transactionservice.dto.TransactionCreatedEvent; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionProducer { + + private final KafkaTemplate kafkaTemplate; + private final ObjectMapper objectMapper; + + public void sendTransactionCreatedEvent(TransactionCreatedEvent event) { + try { + String message = objectMapper.writeValueAsString(event); + kafkaTemplate.send(KafkaConfig.TRANSACTION_CREATED_TOPIC, event.getTransactionId().toString(), message); + log.info("Sent transaction created event for transaction: {}", event.getTransactionId()); + } catch (JsonProcessingException e) { + log.error("Error serializing transaction created event", e); + throw new RuntimeException("Error serializing event", e); + } + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionStatusConsumer.java b/transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionStatusConsumer.java new file mode 100644 index 0000000000..87683250a3 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/kafka/TransactionStatusConsumer.java @@ -0,0 +1,35 @@ +package com.yape.transactionservice.kafka; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.transactionservice.config.KafkaConfig; +import com.yape.transactionservice.dto.TransactionStatusUpdateEvent; +import com.yape.transactionservice.entity.TransactionStatus; +import com.yape.transactionservice.service.TransactionService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionStatusConsumer { + + private final TransactionService transactionService; + private final ObjectMapper objectMapper; + + @KafkaListener(topics = KafkaConfig.TRANSACTION_STATUS_TOPIC, groupId = "transaction-service") + public void consumeTransactionStatus(String message) { + try { + TransactionStatusUpdateEvent event = objectMapper.readValue(message, TransactionStatusUpdateEvent.class); + log.info("Received status update for transaction: {} with status: {}", + event.getTransactionId(), event.getStatus()); + + TransactionStatus status = TransactionStatus.valueOf(event.getStatus().toUpperCase()); + transactionService.updateTransactionStatus(event.getTransactionId(), status); + } catch (JsonProcessingException e) { + log.error("Error deserializing transaction status event", e); + } + } +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/repository/TransactionRepository.java b/transaction-service/src/main/java/com/yape/transactionservice/repository/TransactionRepository.java new file mode 100644 index 0000000000..fe9c7139f0 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/repository/TransactionRepository.java @@ -0,0 +1,11 @@ +package com.yape.transactionservice.repository; + +import com.yape.transactionservice.entity.Transaction; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface TransactionRepository extends JpaRepository { +} diff --git a/transaction-service/src/main/java/com/yape/transactionservice/service/TransactionService.java b/transaction-service/src/main/java/com/yape/transactionservice/service/TransactionService.java new file mode 100644 index 0000000000..36d6c7f43e --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactionservice/service/TransactionService.java @@ -0,0 +1,80 @@ +package com.yape.transactionservice.service; + +import com.yape.transactionservice.dto.CreateTransactionRequest; +import com.yape.transactionservice.dto.TransactionCreatedEvent; +import com.yape.transactionservice.dto.TransactionResponse; +import com.yape.transactionservice.entity.Transaction; +import com.yape.transactionservice.entity.TransactionStatus; +import com.yape.transactionservice.entity.TransactionType; +import com.yape.transactionservice.kafka.TransactionProducer; +import com.yape.transactionservice.repository.TransactionRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.UUID; + +@Service +@RequiredArgsConstructor +@Slf4j +public class TransactionService { + + private final TransactionRepository transactionRepository; + private final TransactionProducer transactionProducer; + + @Transactional + public TransactionResponse createTransaction(CreateTransactionRequest request) { + Transaction transaction = Transaction.builder() + .accountExternalIdDebit(request.getAccountExternalIdDebit()) + .accountExternalIdCredit(request.getAccountExternalIdCredit()) + .transactionType(TransactionType.fromId(request.getTranferTypeId())) + .value(request.getValue()) + .status(TransactionStatus.PENDING) + .build(); + + Transaction saved = transactionRepository.save(transaction); + log.info("Transaction created with id: {}", saved.getId()); + + TransactionCreatedEvent event = TransactionCreatedEvent.builder() + .transactionId(saved.getId()) + .value(saved.getValue()) + .build(); + + transactionProducer.sendTransactionCreatedEvent(event); + + return mapToResponse(saved); + } + + @Transactional(readOnly = true) + public TransactionResponse getTransaction(UUID transactionId) { + Transaction transaction = transactionRepository.findById(transactionId) + .orElseThrow(() -> new RuntimeException("Transaction not found: " + transactionId)); + + return mapToResponse(transaction); + } + + @Transactional + public void updateTransactionStatus(UUID transactionId, TransactionStatus status) { + Transaction transaction = transactionRepository.findById(transactionId) + .orElseThrow(() -> new RuntimeException("Transaction not found: " + transactionId)); + + transaction.setStatus(status); + transactionRepository.save(transaction); + log.info("Transaction {} status updated to: {}", transactionId, status); + } + + private TransactionResponse mapToResponse(Transaction transaction) { + return TransactionResponse.builder() + .transactionExternalId(transaction.getId()) + .transactionType(TransactionResponse.TransactionTypeDto.builder() + .name(transaction.getTransactionType().getName()) + .build()) + .transactionStatus(TransactionResponse.TransactionStatusDto.builder() + .name(transaction.getStatus().name().toLowerCase()) + .build()) + .value(transaction.getValue()) + .createdAt(transaction.getCreatedAt()) + .build(); + } +} diff --git a/transaction-service/src/main/resources/application.yml b/transaction-service/src/main/resources/application.yml new file mode 100644 index 0000000000..38e4ebdddb --- /dev/null +++ b/transaction-service/src/main/resources/application.yml @@ -0,0 +1,49 @@ +server: + port: 8080 + +spring: + application: + name: transaction-service + + datasource: + url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/transactions_db} + username: ${SPRING_DATASOURCE_USERNAME:postgres} + password: ${SPRING_DATASOURCE_PASSWORD:postgres} + driver-class-name: org.postgresql.Driver + + jpa: + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + dialect: org.hibernate.dialect.PostgreSQLDialect + format_sql: true + + kafka: + bootstrap-servers: ${SPRING_KAFKA_BOOTSTRAP_SERVERS:localhost:9092} + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + consumer: + group-id: transaction-service + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + +management: + endpoints: + web: + exposure: + include: health + endpoint: + health: + show-details: always + +logging: + level: + root: WARN + com.yape: INFO + org.springframework.kafka: WARN + org.apache.kafka: WARN + org.hibernate: WARN diff --git a/transaction-service/src/test/java/com/yape/transactionservice/TransactionServiceApplicationTests.java b/transaction-service/src/test/java/com/yape/transactionservice/TransactionServiceApplicationTests.java new file mode 100644 index 0000000000..33748584c9 --- /dev/null +++ b/transaction-service/src/test/java/com/yape/transactionservice/TransactionServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.transactionservice; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TransactionServiceApplicationTests { + + @Test + void contextLoads() { + } + +}