diff --git a/README.md b/README.md index b067a71026..069da6d444 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,82 @@ -# Yape Code Challenge :rocket: - -Our code challenge will let you marvel us with your Jedi coding skills :smile:. - -Don't forget that the proper way to submit your work is to fork the repo and create a PR :wink: ... have fun !! - -- [Problem](#problem) -- [Tech Stack](#tech_stack) -- [Send us your challenge](#send_us_your_challenge) - -# Problem - -Every time a financial transaction is created it must be validated by our anti-fraud microservice and then the same service sends a message back to update the transaction status. -For now, we have only three transaction statuses: - -
    -
  1. pending
  2. -
  3. approved
  4. -
  5. rejected
  6. -
- -Every transaction with a value greater than 1000 should be rejected. - -```mermaid - flowchart LR - Transaction -- Save Transaction with pending Status --> transactionDatabase[(Database)] - Transaction --Send transaction Created event--> Anti-Fraud - Anti-Fraud -- Send transaction Status Approved event--> Transaction - Anti-Fraud -- Send transaction Status Rejected event--> Transaction - Transaction -- Update transaction Status event--> transactionDatabase[(Database)] -``` - -# Tech Stack - -
    -
  1. Node. You can use any framework you want (i.e. Nestjs with an ORM like TypeOrm or Prisma)
  2. -
  3. Any database
  4. -
  5. Kafka
  6. -
- -We do provide a `Dockerfile` to help you get started with a dev environment. - -You must have two resources: - -1. Resource to create a transaction that must containt: - -```json -{ - "accountExternalIdDebit": "Guid", - "accountExternalIdCredit": "Guid", - "tranferTypeId": 1, - "value": 120 +# Yape Code Challenge + +This microservice handles the management of financial transactions, integrating asynchronous anti-fraud validation through an event-driven flow. The solution has been designed with a pragmatic and scalable approach, prioritizing data consistency and high performance in service-to-service communication. + +## Tech Stack +* **Java 17 / Spring Boot 4.0.3**: Leveraging the latest performance improvements. +* **GraphQL (Spring GraphQL)**: For a flexible and optimized API that prevents over-fetching. +* **PostgreSQL 14**: Robust relational persistence. +* **Apache Kafka**: Event bus for asynchronous and decoupled communication. +* **MapStruct**: High-performance object mapping (based on code generation, not reflection). +* **Docker & Docker Compose**: Complete infrastructure orchestration. + +--- + +## Engineering & Design Decisions + +### 1. Pragmatic Layered Architecture +A clear separation between `Controller`, `Service`, and `Repository` was implemented. +* **Justification:** For this specific domain, priority was given to reducing latency and code simplicity (KISS), avoiding excessive boilerplate while maintaining solid decoupling through Mappers and DTOs. + +### 2. Distributed Identity (Native UUID) +The `Transaction` entity uses a **UUID** as a natively generated primary key. +* **Scalability:** As a system designed for **High Volume**, using UUIDs avoids database contention caused by traditional sequences and facilitates future horizontal scaling. +* **Data Type:** The native Postgres UUID type is used to optimize storage and indexing. + +### 3. Persistence & Event Strategy +* **Atomicity:** `saveAndFlush` is used in the service to ensure the transaction is physically persisted before emitting the Kafka event. +* **Asynchrony:** The main flow is non-blocking. The transaction is created in a `PENDING` state, and the final state (`APPROVED`/`REJECTED`) is updated eventually by the Kafka consumer. + +--- + +## How to Run the Project + +### Prerequisites +* Docker and Docker Compose installed. + +### Steps +1. **Start infrastructure and microservices:** + From the repository root, run: + ```bash + docker-compose up --build -d + ``` + *This command will spin up PostgreSQL, Kafka, Zookeeper, the Transaction Service, and the Anti-fraud Service.* + +--- + +## API Reference (GraphQL) + +### Create Transaction (Mutation) +```graphql +mutation { + createTransaction(request: { + accountExternalIdDebit: "550e8400-e29b-41d4-a716-446655440000", + accountExternalIdCredit: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + transferTypeId: 1, + value: 120.50 + }) { + transactionExternalId + transactionStatus { + name + } + createdAt + } } ``` -2. Resource to retrieve a transaction - -```json -{ - "transactionExternalId": "Guid", - "transactionType": { - "name": "" - }, - "transactionStatus": { - "name": "" - }, - "value": 120, - "createdAt": "Date" +### Get Transaction (Query) +```graphql +query { + getTransaction(id: "YOUR_TRANSACTION_UUID") { + transactionExternalId + value + transactionStatus { + name + } + transactionType { + name + } + createdAt + } } -``` - -## Optional - -You can use any approach to store transaction data but you should consider that we may deal with high volume scenarios where we have a huge amount of writes and reads for the same data at the same time. How would you tackle this requirement? - -You can use Graphql; - -# Send us your challenge - -When you finish your challenge, after forking a repository, you **must** open a pull request to our repository. There are no limitations to the implementation, you can follow the programming paradigm, modularization, and style that you feel is the most appropriate solution. - -If you have any questions, please let us know. +``` \ No newline at end of file diff --git a/anti-fraud-service/Dockerfile b/anti-fraud-service/Dockerfile new file mode 100644 index 0000000000..8ea408f65e --- /dev/null +++ b/anti-fraud-service/Dockerfile @@ -0,0 +1,3 @@ +FROM eclipse-temurin:17-jre +COPY target/*.jar app.jar +ENTRYPOINT ["java", "-jar", "/app.jar"] \ No newline at end of file diff --git a/anti-fraud-service/HELP.md b/anti-fraud-service/HELP.md new file mode 100644 index 0000000000..f2b9a5738a --- /dev/null +++ b/anti-fraud-service/HELP.md @@ -0,0 +1,22 @@ +# Read Me First +The following was discovered as part of building this project: + +* The original package name 'com.yape.anti-fraud' is invalid and this project uses 'com.yape.anti_fraud' instead. + +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/4.0.3/maven-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/4.0.3/maven-plugin/build-image.html) +* [Spring for Apache Kafka](https://docs.spring.io/spring-boot/4.0.3/reference/messaging/kafka.html) + +### Maven Parent overrides + +Due to Maven's design, elements are inherited from the parent POM to the project POM. +While most of the inheritance is fine, it also inherits unwanted elements like `` and `` from the parent. +To prevent this, the project POM contains empty overrides for these elements. +If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides. + 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..f36c8242b5 --- /dev/null +++ b/anti-fraud-service/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.3 + + + com.yape + anti-fraud + 0.0.1-SNAPSHOT + anti-fraud + Code challenge for potential Yaperos + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-json + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.boot + spring-boot-starter-kafka + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-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/anti_fraud/AntiFraudApplication.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/AntiFraudApplication.java new file mode 100644 index 0000000000..ca95034274 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/AntiFraudApplication.java @@ -0,0 +1,13 @@ +package com.yape.anti_fraud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AntiFraudApplication { + + public static void main(String[] args) { + SpringApplication.run(AntiFraudApplication.class, args); + } + +} diff --git a/anti-fraud-service/src/main/java/com/yape/anti_fraud/dto/kafka/TransactionCreated.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/dto/kafka/TransactionCreated.java new file mode 100644 index 0000000000..b4b24c43d8 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/dto/kafka/TransactionCreated.java @@ -0,0 +1,8 @@ +package com.yape.anti_fraud.dto.kafka; + +import java.util.UUID; + +public record TransactionCreated( + UUID id, + Double value +) {} \ No newline at end of file diff --git a/anti-fraud-service/src/main/java/com/yape/anti_fraud/dto/kafka/TransactionValidated.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/dto/kafka/TransactionValidated.java new file mode 100644 index 0000000000..b7b445d00e --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/dto/kafka/TransactionValidated.java @@ -0,0 +1,10 @@ +package com.yape.anti_fraud.dto.kafka; + +import com.yape.anti_fraud.model.TransactionStatus; + +import java.util.UUID; + +public record TransactionValidated( + UUID id, + TransactionStatus status +) {} diff --git a/anti-fraud-service/src/main/java/com/yape/anti_fraud/kafka/TransactionConsumer.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/kafka/TransactionConsumer.java new file mode 100644 index 0000000000..d1f42b4528 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/kafka/TransactionConsumer.java @@ -0,0 +1,28 @@ +package com.yape.anti_fraud.kafka; + +import com.yape.anti_fraud.dto.kafka.TransactionCreated; +import com.yape.anti_fraud.service.ValidatorService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionConsumer { + + private final ValidatorService validatorService; + + @KafkaListener( + topics = "${spring.kafka.topic.transaction-created}", + groupId = "${spring.kafka.consumer.group-id}", + properties = { + "spring.json.value.default.type=com.yape.anti_fraud.dto.kafka.TransactionCreated" + } + ) + public void consumeTransaction(TransactionCreated response) { + log.info("Received transaction {} for validation", response.id()); + validatorService.validate(response); + } +} diff --git a/anti-fraud-service/src/main/java/com/yape/anti_fraud/kafka/TransactionProducer.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/kafka/TransactionProducer.java new file mode 100644 index 0000000000..0c2f3612ea --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/kafka/TransactionProducer.java @@ -0,0 +1,24 @@ +package com.yape.anti_fraud.kafka; + +import com.yape.anti_fraud.dto.kafka.TransactionValidated; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionProducer { + + private final KafkaTemplate kafkaTemplate; + + @Value("${spring.kafka.topic.transaction-validated}") + private String topicName; + + public void sendStatus(TransactionValidated event) { + log.info("Sending status for transaction {}", event.id()); + kafkaTemplate.send(topicName, event.id().toString(), event); + } +} diff --git a/anti-fraud-service/src/main/java/com/yape/anti_fraud/model/TransactionStatus.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/model/TransactionStatus.java new file mode 100644 index 0000000000..55213b0eaf --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/model/TransactionStatus.java @@ -0,0 +1,5 @@ +package com.yape.anti_fraud.model; + +public enum TransactionStatus { + APPROVED, REJECTED +} diff --git a/anti-fraud-service/src/main/java/com/yape/anti_fraud/service/ValidatorService.java b/anti-fraud-service/src/main/java/com/yape/anti_fraud/service/ValidatorService.java new file mode 100644 index 0000000000..4f7b8dce85 --- /dev/null +++ b/anti-fraud-service/src/main/java/com/yape/anti_fraud/service/ValidatorService.java @@ -0,0 +1,22 @@ +package com.yape.anti_fraud.service; + +import com.yape.anti_fraud.dto.kafka.TransactionCreated; +import com.yape.anti_fraud.dto.kafka.TransactionValidated; +import com.yape.anti_fraud.kafka.TransactionProducer; +import com.yape.anti_fraud.model.TransactionStatus; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class ValidatorService { + private final TransactionProducer transactionProducer; + + public void validate(TransactionCreated event) { + TransactionStatus status = TransactionStatus.APPROVED; + if (event.value() > 1000.0) { + status = TransactionStatus.REJECTED; + } + transactionProducer.sendStatus(new TransactionValidated(event.id(), status)); + } +} diff --git a/anti-fraud-service/src/main/resources/application.yaml b/anti-fraud-service/src/main/resources/application.yaml new file mode 100644 index 0000000000..a3e34e1b92 --- /dev/null +++ b/anti-fraud-service/src/main/resources/application.yaml @@ -0,0 +1,23 @@ +server: + port: 8081 + +spring: + application: + name: anti-fraud-service + kafka: + bootstrap-servers: localhost:9092 + topic: + transaction-created: "transactions.created" + transaction-validated: "transactions.validated" + consumer: + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer + properties: + spring.json.trusted.packages: "*" + group-id: antifraud-group + auto-offset-reset: earliest + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.springframework.kafka.support.serializer.JsonSerializer + properties: + spring.json.add.type.headers: false \ No newline at end of file diff --git a/anti-fraud-service/src/test/java/com/yape/anti_fraud/AntiFraudApplicationTests.java b/anti-fraud-service/src/test/java/com/yape/anti_fraud/AntiFraudApplicationTests.java new file mode 100644 index 0000000000..61fd0f1029 --- /dev/null +++ b/anti-fraud-service/src/test/java/com/yape/anti_fraud/AntiFraudApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.anti_fraud; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AntiFraudApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/docker-compose.yml b/docker-compose.yml index 0e8807f21c..04fcb89df7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,25 +1,53 @@ version: "3.7" + services: - postgres: + db: image: postgres:14 + container_name: yape-postgres ports: - "5432:5432" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres + - POSTGRES_DB=yape_db zookeeper: image: confluentinc/cp-zookeeper:5.5.3 + container_name: yape-zookeeper + platform: linux/amd64 environment: ZOOKEEPER_CLIENT_PORT: 2181 kafka: image: confluentinc/cp-enterprise-kafka:5.5.3 - depends_on: [zookeeper] + container_name: yape-kafka + platform: linux/amd64 + depends_on: + - zookeeper + ports: + - "9092:9092" environment: - KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" + KAFKA_BROKER_ID: 1 + 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_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_JMX_PORT: 9991 + transaction-service: + build: ./transaction-service + container_name: yape-transaction-app + depends_on: + - db + - kafka ports: - - 9092:9092 + - "8080:8080" + environment: + - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/postgres + - SPRING_KAFKA_BOOTSTRAP_SERVERS=kafka:29092 + anti-fraud-service: + build: ./anti-fraud-service + container_name: yape-antifraud-app + depends_on: + - kafka + ports: + - "8081:8081" + environment: + - SPRING_KAFKA_BOOTSTRAP_SERVERS=kafka:29092 \ No newline at end of file diff --git a/transaction-service/Dockerfile b/transaction-service/Dockerfile new file mode 100644 index 0000000000..8ea408f65e --- /dev/null +++ b/transaction-service/Dockerfile @@ -0,0 +1,3 @@ +FROM eclipse-temurin:17-jre +COPY target/*.jar app.jar +ENTRYPOINT ["java", "-jar", "/app.jar"] \ No newline at end of file diff --git a/transaction-service/HELP.md b/transaction-service/HELP.md new file mode 100644 index 0000000000..bd496709c7 --- /dev/null +++ b/transaction-service/HELP.md @@ -0,0 +1,29 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/4.0.3/maven-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/4.0.3/maven-plugin/build-image.html) +* [Spring Web](https://docs.spring.io/spring-boot/4.0.3/reference/web/servlet.html) +* [Spring for Apache Kafka](https://docs.spring.io/spring-boot/4.0.3/reference/messaging/kafka.html) +* [Spring Data JPA](https://docs.spring.io/spring-boot/4.0.3/reference/data/sql.html#data.sql.jpa-and-spring-data) +* [Validation](https://docs.spring.io/spring-boot/4.0.3/reference/io/validation.html) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) +* [Validation](https://spring.io/guides/gs/validating-form-input/) + +### Maven Parent overrides + +Due to Maven's design, elements are inherited from the parent POM to the project POM. +While most of the inheritance is fine, it also inherits unwanted elements like `` and `` from the parent. +To prevent this, the project POM contains empty overrides for these elements. +If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides. + 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..22631a8ea6 --- /dev/null +++ b/transaction-service/pom.xml @@ -0,0 +1,141 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.3 + + + com.yape + transaction + 0.0.1-SNAPSHOT + transaction + Code challenge for potential Yaperos + + + + + + + + + + + + + + + 17 + 1.5.5.Final + + + + com.graphql-java + graphql-java-extended-scalars + 21.0 + + + org.springframework.boot + spring-boot-starter-graphql + + + org.mapstruct + mapstruct + ${org.mapstruct.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-kafka + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-webmvc + + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.springframework.boot + spring-boot-starter-kafka-test + test + + + org.springframework.boot + spring-boot-starter-validation-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + 1.18.30 + + + org.projectlombok + lombok-mapstruct-binding + 0.2.0 + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/transaction-service/src/main/java/com/yape/transactions/TransactionApplication.java b/transaction-service/src/main/java/com/yape/transactions/TransactionApplication.java new file mode 100644 index 0000000000..1c489a946a --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/TransactionApplication.java @@ -0,0 +1,13 @@ +package com.yape.transactions; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TransactionApplication { + + public static void main(String[] args) { + SpringApplication.run(TransactionApplication.class, args); + } + +} diff --git a/transaction-service/src/main/java/com/yape/transactions/config/GraphQlConfig.java b/transaction-service/src/main/java/com/yape/transactions/config/GraphQlConfig.java new file mode 100644 index 0000000000..2cb8b1595c --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/config/GraphQlConfig.java @@ -0,0 +1,16 @@ +package com.yape.transactions.config; + +import graphql.scalars.ExtendedScalars; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.graphql.execution.RuntimeWiringConfigurer; + +@Configuration +public class GraphQlConfig { + @Bean + public RuntimeWiringConfigurer runtimeWiringConfigurer() { + return wiringBuilder -> wiringBuilder + .scalar(ExtendedScalars.UUID) + .scalar(ExtendedScalars.DateTime); + } +} \ No newline at end of file diff --git a/transaction-service/src/main/java/com/yape/transactions/controller/TransactionController.java b/transaction-service/src/main/java/com/yape/transactions/controller/TransactionController.java new file mode 100644 index 0000000000..d551a54081 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/controller/TransactionController.java @@ -0,0 +1,31 @@ +package com.yape.transactions.controller; + +import com.yape.transactions.dto.request.TransactionRequest; +import com.yape.transactions.dto.response.TransactionResponse; +import com.yape.transactions.service.TransactionService; +import lombok.RequiredArgsConstructor; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.graphql.data.method.annotation.MutationMapping; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; + +import java.util.UUID; + +@Controller +@RequiredArgsConstructor +public class TransactionController { + + private final TransactionService transactionService; + + @MutationMapping + public TransactionResponse createTransaction(@Argument TransactionRequest request) { + return transactionService.create(request); + } + + @QueryMapping + public TransactionResponse getTransaction(@Argument UUID id) { + return transactionService.getById(id); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactions/dto/kafka/TransactionCreated.java b/transaction-service/src/main/java/com/yape/transactions/dto/kafka/TransactionCreated.java new file mode 100644 index 0000000000..a2d7c2cf57 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/dto/kafka/TransactionCreated.java @@ -0,0 +1,9 @@ +package com.yape.transactions.dto.kafka; + +import java.math.BigDecimal; +import java.util.UUID; + +public record TransactionCreated( + UUID id, + BigDecimal value +) {} \ No newline at end of file diff --git a/transaction-service/src/main/java/com/yape/transactions/dto/kafka/TransactionValidated.java b/transaction-service/src/main/java/com/yape/transactions/dto/kafka/TransactionValidated.java new file mode 100644 index 0000000000..ab27a6b615 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/dto/kafka/TransactionValidated.java @@ -0,0 +1,10 @@ +package com.yape.transactions.dto.kafka; + +import com.yape.transactions.model.TransactionStatus; + +import java.util.UUID; + +public record TransactionValidated( + UUID id, + TransactionStatus status +) {} diff --git a/transaction-service/src/main/java/com/yape/transactions/dto/request/TransactionRequest.java b/transaction-service/src/main/java/com/yape/transactions/dto/request/TransactionRequest.java new file mode 100644 index 0000000000..6ac7b7c2cc --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/dto/request/TransactionRequest.java @@ -0,0 +1,11 @@ +package com.yape.transactions.dto.request; + +import java.math.BigDecimal; +import java.util.UUID; + +public record TransactionRequest( + UUID accountExternalIdDebit, + UUID accountExternalIdCredit, + Integer transferTypeId, + BigDecimal value +) {} diff --git a/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionResponse.java b/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionResponse.java new file mode 100644 index 0000000000..d6eb0cfb8c --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionResponse.java @@ -0,0 +1,14 @@ +package com.yape.transactions.dto.response; + +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.UUID; + +public record TransactionResponse( + UUID transactionExternalId, + TransactionTypeResponse transactionType, + TransactionStatusResponse transactionStatus, + BigDecimal value, + OffsetDateTime createdAt +) {} + diff --git a/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionStatusResponse.java b/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionStatusResponse.java new file mode 100644 index 0000000000..ee70b4cec0 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionStatusResponse.java @@ -0,0 +1,3 @@ +package com.yape.transactions.dto.response; + +public record TransactionStatusResponse(String name) {} diff --git a/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionTypeResponse.java b/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionTypeResponse.java new file mode 100644 index 0000000000..ff054fffdc --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/dto/response/TransactionTypeResponse.java @@ -0,0 +1,3 @@ +package com.yape.transactions.dto.response; + +public record TransactionTypeResponse(String name) {} diff --git a/transaction-service/src/main/java/com/yape/transactions/kafka/TransactionConsumer.java b/transaction-service/src/main/java/com/yape/transactions/kafka/TransactionConsumer.java new file mode 100644 index 0000000000..8d0118f967 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/kafka/TransactionConsumer.java @@ -0,0 +1,29 @@ +package com.yape.transactions.kafka; + +import com.yape.transactions.dto.kafka.TransactionValidated; +import com.yape.transactions.service.ITransactionService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionConsumer { + + private final ITransactionService transactionService; + + @KafkaListener( + topics = "${spring.kafka.topic.transaction-validated}", + groupId = "${spring.kafka.consumer.group-id}", + properties = { + "spring.json.value.default.type=com.yape.transactions.dto.kafka.TransactionValidated" + } + ) + public void consumeValidationResult(TransactionValidated response) { + log.info("Received result of transaction {}: {}", + response.id(), response.status()); + transactionService.updateStatus(response.id(), response.status()); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactions/kafka/TransactionProducer.java b/transaction-service/src/main/java/com/yape/transactions/kafka/TransactionProducer.java new file mode 100644 index 0000000000..74c8ed1596 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/kafka/TransactionProducer.java @@ -0,0 +1,24 @@ +package com.yape.transactions.kafka; + +import com.yape.transactions.dto.kafka.TransactionCreated; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +@Slf4j +public class TransactionProducer { + + private final KafkaTemplate kafkaTemplate; + + @Value("${spring.kafka.topic.transaction-created}") + private String topicName; + + public void sendToValidation(TransactionCreated transaction) { + log.info("Sending transaction {} for anti-fraud process", transaction.id()); + kafkaTemplate.send(topicName, transaction.id().toString(), transaction); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactions/mapper/TransactionMapper.java b/transaction-service/src/main/java/com/yape/transactions/mapper/TransactionMapper.java new file mode 100644 index 0000000000..1c1dc45961 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/mapper/TransactionMapper.java @@ -0,0 +1,28 @@ +package com.yape.transactions.mapper; + +import com.yape.transactions.dto.request.TransactionRequest; +import com.yape.transactions.dto.response.TransactionResponse; +import com.yape.transactions.model.Transaction; +import com.yape.transactions.model.TransactionType; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring") +public interface TransactionMapper { + + @Mapping(target = "id", ignore = true) + @Mapping(target = "status", ignore = true) + @Mapping(source = "transferTypeId", target = "type") + @Mapping(target = "createdAt", ignore = true) + Transaction toEntity(TransactionRequest request); + + @Mapping(source = "id", target = "transactionExternalId") + @Mapping(source = "type.name", target = "transactionType.name") + @Mapping(source = "status.name", target = "transactionStatus.name") + TransactionResponse toResponse(Transaction entity); + + default TransactionType mapType(Integer value) { + if (value == null) return null; + return TransactionType.fromId(value); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactions/model/Transaction.java b/transaction-service/src/main/java/com/yape/transactions/model/Transaction.java new file mode 100644 index 0000000000..067187089a --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/model/Transaction.java @@ -0,0 +1,31 @@ +package com.yape.transactions.model; + +import jakarta.persistence.*; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.UUID; + +@Entity +@Table(name = "transactions") +@Data +public class Transaction { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private UUID id; + + private UUID accountExternalIdDebit; + private UUID accountExternalIdCredit; + private BigDecimal value; + + @Enumerated(EnumType.STRING) + private TransactionStatus status = TransactionStatus.PENDING; + + @Enumerated(EnumType.STRING) + private TransactionType type; + + @CreationTimestamp + private OffsetDateTime createdAt; +} \ No newline at end of file diff --git a/transaction-service/src/main/java/com/yape/transactions/model/TransactionStatus.java b/transaction-service/src/main/java/com/yape/transactions/model/TransactionStatus.java new file mode 100644 index 0000000000..a77bfcbd10 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/model/TransactionStatus.java @@ -0,0 +1,16 @@ +package com.yape.transactions.model; + +import lombok.Getter; + +@Getter +public enum TransactionStatus { + PENDING("pending"), + APPROVED("approved"), + REJECTED("rejected"); + + private final String name; + + TransactionStatus(String name) { + this.name = name; + } +} diff --git a/transaction-service/src/main/java/com/yape/transactions/model/TransactionType.java b/transaction-service/src/main/java/com/yape/transactions/model/TransactionType.java new file mode 100644 index 0000000000..c8683dc6df --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/model/TransactionType.java @@ -0,0 +1,25 @@ +package com.yape.transactions.model; + +import lombok.Getter; + +@Getter +public enum TransactionType { + WEB(1, "web"), + MOBILE(2, "mobile"), + ATM(3, "ATM"); + + 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.id == id) return type; + } + throw new IllegalArgumentException("Invalid Transfer Type ID: " + id); + } +} diff --git a/transaction-service/src/main/java/com/yape/transactions/repository/transaction/TransactionRepository.java b/transaction-service/src/main/java/com/yape/transactions/repository/transaction/TransactionRepository.java new file mode 100644 index 0000000000..2c1398e67b --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/repository/transaction/TransactionRepository.java @@ -0,0 +1,9 @@ +package com.yape.transactions.repository.transaction; + +import com.yape.transactions.model.Transaction; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.UUID; + +public interface TransactionRepository extends JpaRepository { +} \ No newline at end of file diff --git a/transaction-service/src/main/java/com/yape/transactions/service/ITransactionService.java b/transaction-service/src/main/java/com/yape/transactions/service/ITransactionService.java new file mode 100644 index 0000000000..22e49da1c1 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/service/ITransactionService.java @@ -0,0 +1,13 @@ +package com.yape.transactions.service; + +import com.yape.transactions.dto.request.TransactionRequest; +import com.yape.transactions.dto.response.TransactionResponse; +import com.yape.transactions.model.TransactionStatus; + +import java.util.UUID; + +public interface ITransactionService { + TransactionResponse create(TransactionRequest transaction); + TransactionResponse getById(UUID id); + void updateStatus(UUID id, TransactionStatus status); +} diff --git a/transaction-service/src/main/java/com/yape/transactions/service/TransactionService.java b/transaction-service/src/main/java/com/yape/transactions/service/TransactionService.java new file mode 100644 index 0000000000..3f059c5316 --- /dev/null +++ b/transaction-service/src/main/java/com/yape/transactions/service/TransactionService.java @@ -0,0 +1,58 @@ +package com.yape.transactions.service; + +import com.yape.transactions.dto.kafka.TransactionCreated; +import com.yape.transactions.dto.request.TransactionRequest; +import com.yape.transactions.dto.response.TransactionResponse; +import com.yape.transactions.kafka.TransactionProducer; +import com.yape.transactions.mapper.TransactionMapper; +import com.yape.transactions.model.Transaction; +import com.yape.transactions.model.TransactionStatus; + +import com.yape.transactions.repository.transaction.TransactionRepository; +import jakarta.persistence.EntityNotFoundException; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class TransactionService implements ITransactionService { + private static final Logger log = LoggerFactory.getLogger(TransactionService.class); + private final TransactionRepository transactionRepository; + private final TransactionProducer transactionProducer; + private final TransactionMapper transactionMapper; + + @Override + @Transactional + public TransactionResponse create(TransactionRequest request) { + Transaction transaction = transactionMapper.toEntity(request); + transaction.setStatus(TransactionStatus.PENDING); + Transaction saved = transactionRepository.saveAndFlush(transaction); + transactionProducer.sendToValidation( + new TransactionCreated(saved.getId(), saved.getValue()) + ); + return transactionMapper.toResponse(saved); + } + + @Override + @Transactional + public TransactionResponse getById(UUID id) { + return transactionRepository.findById(id) + .map(transactionMapper::toResponse) + .orElseThrow(() -> new EntityNotFoundException(String.format("Transaction with id %s not found", id))); + } + + @Override + @Transactional + public void updateStatus(UUID id, TransactionStatus status) { + Transaction transaction = transactionRepository + .findById(id) + .orElseThrow(() -> new EntityNotFoundException(String.format("Transaction with id %s not found", id))); + transaction.setStatus(status); + transactionRepository.save(transaction); + } +} diff --git a/transaction-service/src/main/resources/application.yaml b/transaction-service/src/main/resources/application.yaml new file mode 100644 index 0000000000..7a2f25e166 --- /dev/null +++ b/transaction-service/src/main/resources/application.yaml @@ -0,0 +1,31 @@ +server: + port: 8080 +spring: + datasource: + url: jdbc:postgresql://localhost:5432/postgres + username: postgres + password: postgres + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: create + show-sql: true + properties: + hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect + kafka: + bootstrap-servers: localhost:9092 + topic: + transaction-created: "transactions.created" + transaction-validated: "transactions.validated" + consumer: + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer + properties: + spring.json.trusted.packages: "*" + group-id: yape-group + auto-offset-reset: earliest + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.springframework.kafka.support.serializer.JsonSerializer + properties: + spring.json.add.type.headers: false \ No newline at end of file diff --git a/transaction-service/src/main/resources/graphql/schema.graphqls b/transaction-service/src/main/resources/graphql/schema.graphqls new file mode 100644 index 0000000000..91460ff2c4 --- /dev/null +++ b/transaction-service/src/main/resources/graphql/schema.graphqls @@ -0,0 +1,10 @@ +scalar UUID +scalar DateTime + +type Query { + +} + +type Mutation { + +} \ No newline at end of file diff --git a/transaction-service/src/main/resources/graphql/transactionsSchema.graphqls b/transaction-service/src/main/resources/graphql/transactionsSchema.graphqls new file mode 100644 index 0000000000..6f9b13c8ae --- /dev/null +++ b/transaction-service/src/main/resources/graphql/transactionsSchema.graphqls @@ -0,0 +1,30 @@ +extend type Query { + getTransaction(id: UUID!): TransactionResponse +} + +extend type Mutation { + createTransaction(request: TransactionRequest!): TransactionResponse +} + +input TransactionRequest { + accountExternalIdDebit: UUID! + accountExternalIdCredit: UUID! + transferTypeId: Int! + value: Float! +} + +type TransactionResponse { + transactionExternalId: UUID! + transactionType: TransactionType! + transactionStatus: TransactionStatus! + value: Float! + createdAt: DateTime! +} + +type TransactionType { + name: String! +} + +type TransactionStatus { + name: String! +} \ No newline at end of file diff --git a/transaction-service/src/test/java/com/yape/transactions/TransactionApplicationTests.java b/transaction-service/src/test/java/com/yape/transactions/TransactionApplicationTests.java new file mode 100644 index 0000000000..06732fca8a --- /dev/null +++ b/transaction-service/src/test/java/com/yape/transactions/TransactionApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.transactions; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TransactionApplicationTests { + + @Test + void contextLoads() { + } + +}