From 41b19ef66cd5f973ca2c4473405814521a0bdf71 Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 03:19:36 -0500 Subject: [PATCH 1/7] chore: bootstrap java microservices layout and local infra --- .gitignore | 120 ++++-------------------- docker-compose.yml | 51 +++++++++- ms-payment-transaction-command/.gitkeep | 0 ms-risk-antifraud-evaluation/.gitkeep | 0 4 files changed, 70 insertions(+), 101 deletions(-) create mode 100644 ms-payment-transaction-command/.gitkeep create mode 100644 ms-risk-antifraud-evaluation/.gitkeep diff --git a/.gitignore b/.gitignore index 67045665db..23708b3cf4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,104 +1,24 @@ -# Logs -logs +### IntelliJ ### +.idea/ +*.iml +out/ +.vscode/ + +### Java / Maven ### +target/ +*.class +*.jar +*.war +*.ear +hs_err_pid* +replay_pid* *.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json +### OS ### +.DS_Store +Thumbs.db -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage -*.lcov - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ - -# TypeScript cache -*.tsbuildinfo - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Microbundle cache -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file +### Docker ### +*.env .env -.env.test - -# parcel-bundler cache (https://parceljs.org/) -.cache - -# Next.js build output -.next - -# Nuxt.js build / generate output -.nuxt -dist - -# Gatsby files -.cache/ -# Comment in the public line in if your project uses Gatsby and *not* Next.js -# https://nextjs.org/blog/next-9-1#public-directory-support -# public - -# vuepress build output -.vuepress/dist - -# Serverless directories -.serverless/ - -# FuseBox cache -.fusebox/ - -# DynamoDB Local files -.dynamodb/ - -# TernJS port file -.tern-port +.env.* \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 0e8807f21c..5b47c4032e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,19 +1,33 @@ version: "3.7" + services: postgres: image: postgres:14 + container_name: yape-postgres ports: - "5432:5432" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres + - POSTGRES_DB=yape + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d yape"] + interval: 10s + timeout: 5s + retries: 5 + zookeeper: image: confluentinc/cp-zookeeper:5.5.3 + container_name: yape-zookeeper environment: ZOOKEEPER_CLIENT_PORT: 2181 + kafka: image: confluentinc/cp-enterprise-kafka:5.5.3 + container_name: yape-kafka depends_on: [zookeeper] + ports: + - "9092:9092" environment: KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092 @@ -21,5 +35,40 @@ services: KAFKA_BROKER_ID: 1 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_JMX_PORT: 9991 + + kafka-ui: + image: provectuslabs/kafka-ui:latest + container_name: yape-kafka-ui + depends_on: [kafka] + ports: + - "8088:8080" + environment: + - KAFKA_CLUSTERS_0_NAME=yape + - KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS=kafka:29092 + - KAFKA_CLUSTERS_0_ZOOKEEPER=zookeeper:2181 + + ms-payment-transaction-command: + build: ./ms-payment-transaction-command + container_name: ms-payment-transaction-command + depends_on: + postgres: + condition: service_healthy + kafka: + condition: service_started ports: - - 9092:9092 + - "8081:8080" + environment: + - SPRING_PROFILES_ACTIVE=local + profiles: ["apps"] + + ms-risk-antifraud-evaluation: + build: ./ms-risk-antifraud-evaluation + container_name: ms-risk-antifraud-evaluation + depends_on: + kafka: + condition: service_started + ports: + - "8082:8080" + environment: + - SPRING_PROFILES_ACTIVE=local + profiles: ["apps"] \ No newline at end of file diff --git a/ms-payment-transaction-command/.gitkeep b/ms-payment-transaction-command/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ms-risk-antifraud-evaluation/.gitkeep b/ms-risk-antifraud-evaluation/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 From 064d260a0c09351e352d0c7c978c39ec14e32c37 Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 03:53:20 -0500 Subject: [PATCH 2/7] docs: add solution overview, architecture and run instructions --- README.md | 165 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 112 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index b067a71026..df38ae3a63 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,141 @@ -# Yape Code Challenge :rocket: +# Yape Code Challenge – Async Payment Transaction Platform (Java 21) -Our code challenge will let you marvel us with your Jedi coding skills :smile:. +## Overview -Don't forget that the proper way to submit your work is to fork the repo and create a PR :wink: ... have fun !! +This solution implements an event-driven microservices architecture for financial transaction processing and anti-fraud validation. -- [Problem](#problem) -- [Tech Stack](#tech_stack) -- [Send us your challenge](#send_us_your_challenge) +The platform is composed of two independent microservices communicating asynchronously through Apache Kafka: -# Problem +- **ms-payment-transaction-command** + - Exposes REST APIs to create and retrieve transactions. + - Persists transactions with initial `PENDING` status. + - Publishes `TransactionCreated` events. + - Consumes validation results and updates transaction status. -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: +- **ms-risk-antifraud-evaluation** + - Consumes created transaction events. + - Applies anti-fraud rules. + - Publishes validation results (`APPROVED` / `REJECTED`). -
    -
  1. pending
  2. -
  3. approved
  4. -
  5. rejected
  6. -
+The solution follows **Hexagonal Architecture** and applies the **Transactional Outbox Pattern** to guarantee consistency between database state and published Kafka events. -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)] -``` +## Architecture -# Tech Stack +- Java 21 / Spring Boot 3 +- Apache Kafka (event backbone) +- PostgreSQL (transactional persistence) +- Transactional Outbox Pattern +- Idempotent Kafka consumers +- Optimistic concurrency control +- Docker Compose local environment -
    -
  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. +## Event Flow -You must have two resources: +1. Client creates transaction → status `PENDING` +2. Transaction service stores transaction and outbox event +3. Outbox publisher emits `payment.transaction.created.v1` +4. Anti-fraud service validates business rule +5. Anti-fraud publishes `payment.transaction.validated.v1` +6. Transaction service consumes result and updates transaction status -1. Resource to create a transaction that must containt: +--- + +## Running locally + +### Start infrastructure only (Kafka + Postgres) + +```bash +docker compose up -d + +Kafka UI +http://localhost:8088 + +PostgreSQL +localhost:5432 +user: postgres +password: postgres +db: yape + + +Start full platform (infra + microservices) + +docker compose --profile apps up -d --build + + +REST API +Create transaction + +POST http://localhost:8081/transactions +json -```json { - "accountExternalIdDebit": "Guid", - "accountExternalIdCredit": "Guid", + "accountExternalIdDebit": "a1c1e3d4-1111-4bda-8c01-abc123", + "accountExternalIdCredit": "b2f2a3d4-2222-4bda-8c01-def456", "tranferTypeId": 1, "value": 120 } -``` -2. Resource to retrieve a transaction -```json +Get transaction + +GET http://localhost:8081/transactions/{transactionExternalId} + +Response: + { - "transactionExternalId": "Guid", - "transactionType": { - "name": "" - }, - "transactionStatus": { - "name": "" - }, + "transactionExternalId": "uuid", + "transactionType": { "name": "TRANSFER" }, + "transactionStatus": { "name": "APPROVED" }, "value": 120, - "createdAt": "Date" + "createdAt": "2026-01-06T13:10:00Z" } -``` -## Optional +Kafka Topics + +payment.transaction.created.v1 + +payment.transaction.validated.v1 + +payment.transaction.created.dlq.v1 + +payment.transaction.validated.dlq.v1 + +High concurrency & reliability strategy + +This solution is designed for high-write / high-read scenarios: + +Transactional outbox to avoid dual-write problems + +Kafka-based async processing + +Idempotent consumers + +Conditional updates (WHERE status = 'PENDING') + +Indexed reads + +Optimistic locking + +Horizontal scalability + +Design principles + +Hexagonal architecture + +Clear domain boundaries + +Infrastructure isolation + +Event-driven communication -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? +Production-oriented reliability patterns -You can use Graphql; +Notes -# Send us your challenge +This implementation prioritizes reliability, scalability and data consistency, following real-world banking-grade asynchronous processing patterns. -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. From 1e88903665eb64855e7444d5a59c1cc284239954 Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 04:49:06 -0500 Subject: [PATCH 3/7] chore: bootstrap ms-payment-transaction-command with Spring Boot 3 and Java 21 --- ms-payment-transaction-command/.gitattributes | 2 + ms-payment-transaction-command/.gitignore | 33 ++ ms-payment-transaction-command/.gitkeep | 0 .../.mvn/wrapper/maven-wrapper.properties | 3 + ms-payment-transaction-command/mvnw | 295 ++++++++++++++++++ ms-payment-transaction-command/mvnw.cmd | 189 +++++++++++ ms-payment-transaction-command/pom.xml | 108 +++++++ ...sPaymentTransactionCommandApplication.java | 13 + .../src/main/resources/application.yml | 34 ++ ...entTransactionCommandApplicationTests.java | 13 + 10 files changed, 690 insertions(+) create mode 100644 ms-payment-transaction-command/.gitattributes create mode 100644 ms-payment-transaction-command/.gitignore delete mode 100644 ms-payment-transaction-command/.gitkeep create mode 100644 ms-payment-transaction-command/.mvn/wrapper/maven-wrapper.properties create mode 100644 ms-payment-transaction-command/mvnw create mode 100644 ms-payment-transaction-command/mvnw.cmd create mode 100644 ms-payment-transaction-command/pom.xml create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java create mode 100644 ms-payment-transaction-command/src/main/resources/application.yml create mode 100644 ms-payment-transaction-command/src/test/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplicationTests.java diff --git a/ms-payment-transaction-command/.gitattributes b/ms-payment-transaction-command/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/ms-payment-transaction-command/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/ms-payment-transaction-command/.gitignore b/ms-payment-transaction-command/.gitignore new file mode 100644 index 0000000000..667aaef0c8 --- /dev/null +++ b/ms-payment-transaction-command/.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/ms-payment-transaction-command/.gitkeep b/ms-payment-transaction-command/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/ms-payment-transaction-command/.mvn/wrapper/maven-wrapper.properties b/ms-payment-transaction-command/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..8dea6c227c --- /dev/null +++ b/ms-payment-transaction-command/.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/ms-payment-transaction-command/mvnw b/ms-payment-transaction-command/mvnw new file mode 100644 index 0000000000..bd8896bf22 --- /dev/null +++ b/ms-payment-transaction-command/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/ms-payment-transaction-command/mvnw.cmd b/ms-payment-transaction-command/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/ms-payment-transaction-command/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/ms-payment-transaction-command/pom.xml b/ms-payment-transaction-command/pom.xml new file mode 100644 index 0000000000..009da5e0d9 --- /dev/null +++ b/ms-payment-transaction-command/pom.xml @@ -0,0 +1,108 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.1 + + + com.yape.payment + ms-payment-transaction-command + 0.0.1-SNAPSHOT + ms-payment-transaction-command + ms-payment-transaction-command + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-flyway + + + org.springframework.boot + spring-boot-starter-kafka + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.flywaydb + flyway-database-postgresql + + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-actuator-test + test + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + org.springframework.boot + spring-boot-starter-flyway-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.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java new file mode 100644 index 0000000000..3326494c45 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java @@ -0,0 +1,13 @@ +package com.yape.payment.transaction; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MsPaymentTransactionCommandApplication { + + public static void main(String[] args) { + SpringApplication.run(MsPaymentTransactionCommandApplication.class, args); + + } +} diff --git a/ms-payment-transaction-command/src/main/resources/application.yml b/ms-payment-transaction-command/src/main/resources/application.yml new file mode 100644 index 0000000000..7eac9a5ba6 --- /dev/null +++ b/ms-payment-transaction-command/src/main/resources/application.yml @@ -0,0 +1,34 @@ +server: + port: 8081 + +spring: + application: + name: ms-payment-transaction-command + + datasource: + url: jdbc:postgresql://localhost:5432/yape + username: postgres + password: postgres + driver-class-name: org.postgresql.Driver + + jpa: + hibernate: + ddl-auto: validate + open-in-view: false + show-sql: false + properties: + hibernate: + format_sql: true + + flyway: + enabled: true + baseline-on-migrate: true + + kafka: + bootstrap-servers: localhost:9092 + +management: + endpoints: + web: + exposure: + include: health,info \ No newline at end of file diff --git a/ms-payment-transaction-command/src/test/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplicationTests.java b/ms-payment-transaction-command/src/test/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplicationTests.java new file mode 100644 index 0000000000..6f189bf9d1 --- /dev/null +++ b/ms-payment-transaction-command/src/test/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.payment.transaction; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MsPaymentTransactionCommandApplicationTests { + + @Test + void contextLoads() { + } + +} From c637b623d9bdbbcb663cd18e33a5bb50d1cb44dd Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 05:41:06 -0500 Subject: [PATCH 4/7] feat(transaction-command): implement transaction API with outbox pattern --- ms-payment-transaction-command/pom.xml | 37 +++-- ...sPaymentTransactionCommandApplication.java | 2 + .../api/TransactionController.java | 31 +++++ .../api/dto/CreateTransactionRequest.java | 54 ++++++++ .../api/dto/TransactionResponse.java | 54 ++++++++ .../api/dto/TransactionStatusDto.java | 21 +++ .../api/dto/TransactionTypeDto.java | 21 +++ .../application/TransactionService.java | 110 +++++++++++++++ .../transaction/domain/TransactionStatus.java | 7 + .../transaction/domain/TransactionType.java | 5 + .../db/entity/OutboxEventEntity.java | 127 ++++++++++++++++++ .../db/entity/TransactionEntity.java | 105 +++++++++++++++ .../repository/OutboxEventJpaRepository.java | 11 ++ .../repository/TransactionJpaRepository.java | 10 ++ .../infrastructure/kafka/KafkaTopics.java | 10 ++ .../kafka/OutboxPublisherJob.java | 55 ++++++++ .../kafka/dto/TransactionCreatedEvent.java | 72 ++++++++++ .../shared/config/JacksonConfig.java | 19 +++ .../shared/exception/ApiErrorResponse.java | 28 ++++ .../exception/GlobalExceptionHandler.java | 41 ++++++ .../exception/ResourceNotFoundException.java | 8 ++ .../src/main/resources/application.yml | 25 ++-- .../db/migration/V1__create_transactions.sql | 16 +++ .../db/migration/V2__create_outbox_events.sql | 18 +++ .../migration/V3__outbox_payload_as_text.sql | 2 + 25 files changed, 858 insertions(+), 31 deletions(-) create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/TransactionController.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/CreateTransactionRequest.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionResponse.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionStatusDto.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionTypeDto.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionStatus.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionType.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/OutboxEventEntity.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/TransactionEntity.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/OutboxEventJpaRepository.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/TransactionJpaRepository.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/OutboxPublisherJob.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionCreatedEvent.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/config/JacksonConfig.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ApiErrorResponse.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/GlobalExceptionHandler.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ResourceNotFoundException.java create mode 100644 ms-payment-transaction-command/src/main/resources/db/migration/V1__create_transactions.sql create mode 100644 ms-payment-transaction-command/src/main/resources/db/migration/V2__create_outbox_events.sql create mode 100644 ms-payment-transaction-command/src/main/resources/db/migration/V3__outbox_payload_as_text.sql diff --git a/ms-payment-transaction-command/pom.xml b/ms-payment-transaction-command/pom.xml index 009da5e0d9..c54d6f6569 100644 --- a/ms-payment-transaction-command/pom.xml +++ b/ms-payment-transaction-command/pom.xml @@ -50,10 +50,7 @@ org.springframework.boot spring-boot-starter-validation - - org.springframework.boot - spring-boot-starter-webmvc - + org.flywaydb flyway-database-postgresql @@ -64,36 +61,32 @@ postgresql runtime + org.springframework.boot - spring-boot-starter-actuator-test - test - - - org.springframework.boot - spring-boot-starter-data-jpa-test - test + spring-boot-starter-web + - org.springframework.boot - spring-boot-starter-flyway-test - test + org.flywaydb + flyway-core + - org.springframework.boot - spring-boot-starter-kafka-test - test + org.springframework.kafka + spring-kafka + org.springframework.boot - spring-boot-starter-validation-test - test + spring-boot-starter-json + - org.springframework.boot - spring-boot-starter-webmvc-test - test + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java index 3326494c45..9b38b1aede 100644 --- a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/MsPaymentTransactionCommandApplication.java @@ -2,7 +2,9 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; +@EnableScheduling @SpringBootApplication public class MsPaymentTransactionCommandApplication { diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/TransactionController.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/TransactionController.java new file mode 100644 index 0000000000..2b7516afeb --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/TransactionController.java @@ -0,0 +1,31 @@ +package com.yape.payment.transaction.api; + +import com.yape.payment.transaction.api.dto.CreateTransactionRequest; +import com.yape.payment.transaction.api.dto.TransactionResponse; +import com.yape.payment.transaction.application.TransactionService; +import jakarta.validation.Valid; +import java.util.UUID; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/transactions") +public class TransactionController { + + private final TransactionService transactionService; + + public TransactionController(TransactionService transactionService) { + this.transactionService = transactionService; + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public TransactionResponse create(@Valid @RequestBody CreateTransactionRequest request) { + return transactionService.create(request); + } + + @GetMapping("/{transactionExternalId}") + public TransactionResponse get(@PathVariable UUID transactionExternalId) { + return transactionService.get(transactionExternalId); + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/CreateTransactionRequest.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/CreateTransactionRequest.java new file mode 100644 index 0000000000..a83c7b8403 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/CreateTransactionRequest.java @@ -0,0 +1,54 @@ +package com.yape.payment.transaction.api.dto; + +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.NotNull; +import java.math.BigDecimal; +import java.util.UUID; + +public class CreateTransactionRequest { + + @NotNull + private UUID accountExternalIdDebit; + + @NotNull + private UUID accountExternalIdCredit; + + @NotNull + private Integer tranferTypeId; + + @NotNull + @DecimalMin(value = "0.01") + private BigDecimal value; + + public UUID getAccountExternalIdDebit() { + return accountExternalIdDebit; + } + + public void setAccountExternalIdDebit(UUID accountExternalIdDebit) { + this.accountExternalIdDebit = accountExternalIdDebit; + } + + public UUID getAccountExternalIdCredit() { + return accountExternalIdCredit; + } + + public void setAccountExternalIdCredit(UUID accountExternalIdCredit) { + this.accountExternalIdCredit = accountExternalIdCredit; + } + + public Integer getTranferTypeId() { + return tranferTypeId; + } + + public void setTranferTypeId(Integer tranferTypeId) { + this.tranferTypeId = tranferTypeId; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionResponse.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionResponse.java new file mode 100644 index 0000000000..8776373c8f --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionResponse.java @@ -0,0 +1,54 @@ +package com.yape.payment.transaction.api.dto; + +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.UUID; + +public class TransactionResponse { + + private UUID transactionExternalId; + private TransactionTypeDto transactionType; + private TransactionStatusDto transactionStatus; + private BigDecimal value; + private OffsetDateTime createdAt; + + public UUID getTransactionExternalId() { + return transactionExternalId; + } + + public void setTransactionExternalId(UUID transactionExternalId) { + this.transactionExternalId = transactionExternalId; + } + + public TransactionTypeDto getTransactionType() { + return transactionType; + } + + public void setTransactionType(TransactionTypeDto transactionType) { + this.transactionType = transactionType; + } + + public TransactionStatusDto getTransactionStatus() { + return transactionStatus; + } + + public void setTransactionStatus(TransactionStatusDto transactionStatus) { + this.transactionStatus = transactionStatus; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(OffsetDateTime createdAt) { + this.createdAt = createdAt; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionStatusDto.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionStatusDto.java new file mode 100644 index 0000000000..d2e96e1d12 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionStatusDto.java @@ -0,0 +1,21 @@ +package com.yape.payment.transaction.api.dto; + +public class TransactionStatusDto { + + private String name; + + public TransactionStatusDto() { + } + + public TransactionStatusDto(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionTypeDto.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionTypeDto.java new file mode 100644 index 0000000000..c491e1e1c6 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/api/dto/TransactionTypeDto.java @@ -0,0 +1,21 @@ +package com.yape.payment.transaction.api.dto; + +public class TransactionTypeDto { + + private String name; + + public TransactionTypeDto() { + } + + public TransactionTypeDto(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java new file mode 100644 index 0000000000..22e86305fb --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java @@ -0,0 +1,110 @@ +package com.yape.payment.transaction.application; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.payment.transaction.api.dto.CreateTransactionRequest; +import com.yape.payment.transaction.api.dto.TransactionResponse; +import com.yape.payment.transaction.api.dto.TransactionStatusDto; +import com.yape.payment.transaction.api.dto.TransactionTypeDto; +import com.yape.payment.transaction.domain.TransactionStatus; +import com.yape.payment.transaction.domain.TransactionType; +import com.yape.payment.transaction.infrastructure.db.entity.OutboxEventEntity; +import com.yape.payment.transaction.infrastructure.db.entity.TransactionEntity; +import com.yape.payment.transaction.infrastructure.db.repository.OutboxEventJpaRepository; +import com.yape.payment.transaction.infrastructure.db.repository.TransactionJpaRepository; +import com.yape.payment.transaction.infrastructure.kafka.KafkaTopics; +import com.yape.payment.transaction.infrastructure.kafka.dto.TransactionCreatedEvent; +import com.yape.payment.transaction.shared.exception.ResourceNotFoundException; +import jakarta.transaction.Transactional; +import java.util.UUID; +import org.springframework.stereotype.Service; + +@Service +public class TransactionService { + + private final TransactionJpaRepository transactionRepository; + private final OutboxEventJpaRepository outboxRepository; + private final ObjectMapper objectMapper; + + public TransactionService( + TransactionJpaRepository transactionRepository, + OutboxEventJpaRepository outboxRepository, + ObjectMapper objectMapper) { + this.transactionRepository = transactionRepository; + this.outboxRepository = outboxRepository; + this.objectMapper = objectMapper; + } + + @Transactional + public TransactionResponse create(CreateTransactionRequest request) { + TransactionEntity entity = new TransactionEntity(); + entity.setTransactionExternalId(UUID.randomUUID()); + entity.setAccountExternalIdDebit(request.getAccountExternalIdDebit()); + entity.setAccountExternalIdCredit(request.getAccountExternalIdCredit()); + entity.setTransferTypeId(request.getTranferTypeId()); + entity.setValue(request.getValue()); + entity.setStatus(TransactionStatus.PENDING); + + TransactionEntity saved = transactionRepository.save(entity); + + enqueueTransactionCreated(saved); + + return toResponse(saved); + } + + public TransactionResponse get(UUID transactionExternalId) { + TransactionEntity entity = transactionRepository.findByTransactionExternalId(transactionExternalId) + .orElseThrow(() -> new ResourceNotFoundException( + "Transaction not found: " + transactionExternalId)); + + return toResponse(entity); + } + + private void enqueueTransactionCreated(TransactionEntity tx) { + TransactionCreatedEvent event = new TransactionCreatedEvent(); + event.setEventId(UUID.randomUUID()); + event.setTransactionExternalId(tx.getTransactionExternalId()); + event.setAccountExternalIdDebit(tx.getAccountExternalIdDebit()); + event.setAccountExternalIdCredit(tx.getAccountExternalIdCredit()); + event.setTranferTypeId(tx.getTransferTypeId()); + event.setValue(tx.getValue()); + event.setCreatedAt(tx.getCreatedAt()); + + String payload; + try { + payload = objectMapper.writeValueAsString(event); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Failed to serialize outbox payload", e); + } + + OutboxEventEntity outbox = new OutboxEventEntity(); + outbox.setAggregateType("TRANSACTION"); + outbox.setAggregateId(tx.getTransactionExternalId()); + outbox.setEventType("TransactionCreated"); + outbox.setTopic(KafkaTopics.PAYMENT_TRANSACTION_CREATED_V1); + outbox.setPayload(payload); + outbox.setStatus(OutboxEventEntity.OutboxStatus.PENDING); + + outboxRepository.save(outbox); + } + + private TransactionResponse toResponse(TransactionEntity entity) { + TransactionResponse response = new TransactionResponse(); + response.setTransactionExternalId(entity.getTransactionExternalId()); + response.setValue(entity.getValue()); + response.setCreatedAt(entity.getCreatedAt()); + + TransactionType type = mapType(entity.getTransferTypeId()); + response.setTransactionType(new TransactionTypeDto(type.name())); + response.setTransactionStatus(new TransactionStatusDto(entity.getStatus().name())); + + return response; + } + + private TransactionType mapType(Integer transferTypeId) { + if (transferTypeId != null && transferTypeId == 1) { + return TransactionType.TRANSFER; + } + return TransactionType.TRANSFER; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionStatus.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionStatus.java new file mode 100644 index 0000000000..6f7070354e --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionStatus.java @@ -0,0 +1,7 @@ +package com.yape.payment.transaction.domain; + +public enum TransactionStatus { + PENDING, + APPROVED, + REJECTED +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionType.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionType.java new file mode 100644 index 0000000000..15d499c258 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/domain/TransactionType.java @@ -0,0 +1,5 @@ +package com.yape.payment.transaction.domain; + +public enum TransactionType { + TRANSFER +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/OutboxEventEntity.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/OutboxEventEntity.java new file mode 100644 index 0000000000..32a546d4ce --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/OutboxEventEntity.java @@ -0,0 +1,127 @@ +package com.yape.payment.transaction.infrastructure.db.entity; + +import jakarta.persistence.*; +import java.time.OffsetDateTime; +import java.util.UUID; + +@Entity +@Table(name = "outbox_events") +public class OutboxEventEntity { + + public enum OutboxStatus { + PENDING, + PUBLISHED, + FAILED + } + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "aggregate_type", nullable = false) + private String aggregateType; + + @Column(name = "aggregate_id", nullable = false) + private UUID aggregateId; + + @Column(name = "event_type", nullable = false) + private String eventType; + + @Column(name = "topic", nullable = false) + private String topic; + + @Column(name = "payload", nullable = false, columnDefinition = "jsonb") + private String payload; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private OutboxStatus status; + + @Column(name = "error") + private String error; + + @Column(name = "created_at", nullable = false) + private OffsetDateTime createdAt; + + @Column(name = "published_at") + private OffsetDateTime publishedAt; + + @PrePersist + public void prePersist() { + if (createdAt == null) { + createdAt = OffsetDateTime.now(); + } + } + + public Long getId() { + return id; + } + + public String getAggregateType() { + return aggregateType; + } + + public void setAggregateType(String aggregateType) { + this.aggregateType = aggregateType; + } + + public UUID getAggregateId() { + return aggregateId; + } + + public void setAggregateId(UUID aggregateId) { + this.aggregateId = aggregateId; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public OutboxStatus getStatus() { + return status; + } + + public void setStatus(OutboxStatus status) { + this.status = status; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + public OffsetDateTime getPublishedAt() { + return publishedAt; + } + + public void setPublishedAt(OffsetDateTime publishedAt) { + this.publishedAt = publishedAt; + } +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/TransactionEntity.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/TransactionEntity.java new file mode 100644 index 0000000000..6fb0a54dfe --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/entity/TransactionEntity.java @@ -0,0 +1,105 @@ +package com.yape.payment.transaction.infrastructure.db.entity; + +import com.yape.payment.transaction.domain.TransactionStatus; +import jakarta.persistence.*; +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.UUID; + +@Entity +@Table(name = "transactions") +public class TransactionEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "transaction_external_id", nullable = false, unique = true) + private UUID transactionExternalId; + + @Column(name = "account_external_id_debit", nullable = false) + private UUID accountExternalIdDebit; + + @Column(name = "account_external_id_credit", nullable = false) + private UUID accountExternalIdCredit; + + @Column(name = "transfer_type_id", nullable = false) + private Integer transferTypeId; + + @Column(name = "value", nullable = false, precision = 18, scale = 2) + private BigDecimal value; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private TransactionStatus status; + + @Column(name = "created_at", nullable = false) + private OffsetDateTime createdAt; + + @PrePersist + public void prePersist() { + if (createdAt == null) { + createdAt = OffsetDateTime.now(); + } + } + + public Long getId() { + return id; + } + + public UUID getTransactionExternalId() { + return transactionExternalId; + } + + public void setTransactionExternalId(UUID transactionExternalId) { + this.transactionExternalId = transactionExternalId; + } + + public UUID getAccountExternalIdDebit() { + return accountExternalIdDebit; + } + + public void setAccountExternalIdDebit(UUID accountExternalIdDebit) { + this.accountExternalIdDebit = accountExternalIdDebit; + } + + public UUID getAccountExternalIdCredit() { + return accountExternalIdCredit; + } + + public void setAccountExternalIdCredit(UUID accountExternalIdCredit) { + this.accountExternalIdCredit = accountExternalIdCredit; + } + + public Integer getTransferTypeId() { + return transferTypeId; + } + + public void setTransferTypeId(Integer transferTypeId) { + this.transferTypeId = transferTypeId; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + public TransactionStatus getStatus() { + return status; + } + + public void setStatus(TransactionStatus status) { + this.status = status; + } + + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(OffsetDateTime createdAt) { + this.createdAt = createdAt; + } +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/OutboxEventJpaRepository.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/OutboxEventJpaRepository.java new file mode 100644 index 0000000000..5106844744 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/OutboxEventJpaRepository.java @@ -0,0 +1,11 @@ +package com.yape.payment.transaction.infrastructure.db.repository; + +import com.yape.payment.transaction.infrastructure.db.entity.OutboxEventEntity; +import com.yape.payment.transaction.infrastructure.db.entity.OutboxEventEntity.OutboxStatus; +import java.util.List; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OutboxEventJpaRepository extends JpaRepository { + List findByStatusOrderByCreatedAtAsc(OutboxStatus status, Pageable pageable); +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/TransactionJpaRepository.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/TransactionJpaRepository.java new file mode 100644 index 0000000000..f5bb79d3af --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/db/repository/TransactionJpaRepository.java @@ -0,0 +1,10 @@ +package com.yape.payment.transaction.infrastructure.db.repository; + +import com.yape.payment.transaction.infrastructure.db.entity.TransactionEntity; +import java.util.Optional; +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface TransactionJpaRepository extends JpaRepository { + Optional findByTransactionExternalId(UUID transactionExternalId); +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java new file mode 100644 index 0000000000..3a57f1084b --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java @@ -0,0 +1,10 @@ +package com.yape.payment.transaction.infrastructure.kafka; + +public final class KafkaTopics { + + private KafkaTopics() { + } + + public static final String PAYMENT_TRANSACTION_CREATED_V1 = + "payment.transaction.created.v1"; +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/OutboxPublisherJob.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/OutboxPublisherJob.java new file mode 100644 index 0000000000..4bee446bb9 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/OutboxPublisherJob.java @@ -0,0 +1,55 @@ +package com.yape.payment.transaction.infrastructure.kafka; + +import com.yape.payment.transaction.infrastructure.db.entity.OutboxEventEntity; +import com.yape.payment.transaction.infrastructure.db.entity.OutboxEventEntity.OutboxStatus; +import com.yape.payment.transaction.infrastructure.db.repository.OutboxEventJpaRepository; +import jakarta.transaction.Transactional; +import java.time.OffsetDateTime; +import java.util.List; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.PageRequest; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +public class OutboxPublisherJob { + + private final OutboxEventJpaRepository outboxRepository; + private final KafkaTemplate kafkaTemplate; + + private final int batchSize; + + public OutboxPublisherJob( + OutboxEventJpaRepository outboxRepository, + KafkaTemplate kafkaTemplate, + @Value("${outbox.publisher.batch-size:50}") int batchSize) { + this.outboxRepository = outboxRepository; + this.kafkaTemplate = kafkaTemplate; + this.batchSize = batchSize; + } + + @Scheduled(fixedDelayString = "${outbox.publisher.fixed-delay-ms:1000}") + @Transactional + public void publishPendingEvents() { + List events = outboxRepository.findByStatusOrderByCreatedAtAsc( + OutboxStatus.PENDING, + PageRequest.of(0, batchSize) + ); + + for (OutboxEventEntity event : events) { + try { + kafkaTemplate.send(event.getTopic(), event.getAggregateId().toString(), event.getPayload()) + .get(); + + event.setStatus(OutboxStatus.PUBLISHED); + event.setPublishedAt(OffsetDateTime.now()); + event.setError(null); + } catch (Exception ex) { + event.setStatus(OutboxStatus.FAILED); + event.setError(ex.getMessage()); + } + outboxRepository.save(event); + } + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionCreatedEvent.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionCreatedEvent.java new file mode 100644 index 0000000000..55198fb933 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionCreatedEvent.java @@ -0,0 +1,72 @@ +package com.yape.payment.transaction.infrastructure.kafka.dto; + +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.UUID; + +public class TransactionCreatedEvent { + + private UUID eventId; + private UUID transactionExternalId; + private UUID accountExternalIdDebit; + private UUID accountExternalIdCredit; + private Integer tranferTypeId; + private BigDecimal value; + private OffsetDateTime createdAt; + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public UUID getTransactionExternalId() { + return transactionExternalId; + } + + public void setTransactionExternalId(UUID transactionExternalId) { + this.transactionExternalId = transactionExternalId; + } + + public UUID getAccountExternalIdDebit() { + return accountExternalIdDebit; + } + + public void setAccountExternalIdDebit(UUID accountExternalIdDebit) { + this.accountExternalIdDebit = accountExternalIdDebit; + } + + public UUID getAccountExternalIdCredit() { + return accountExternalIdCredit; + } + + public void setAccountExternalIdCredit(UUID accountExternalIdCredit) { + this.accountExternalIdCredit = accountExternalIdCredit; + } + + public Integer getTranferTypeId() { + return tranferTypeId; + } + + public void setTranferTypeId(Integer tranferTypeId) { + this.tranferTypeId = tranferTypeId; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(OffsetDateTime createdAt) { + this.createdAt = createdAt; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/config/JacksonConfig.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/config/JacksonConfig.java new file mode 100644 index 0000000000..525c8e5f74 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/config/JacksonConfig.java @@ -0,0 +1,19 @@ +package com.yape.payment.transaction.shared.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class JacksonConfig { + + @Bean + public ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return mapper; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ApiErrorResponse.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ApiErrorResponse.java new file mode 100644 index 0000000000..22c36ac258 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ApiErrorResponse.java @@ -0,0 +1,28 @@ +package com.yape.payment.transaction.shared.exception; + +import java.time.OffsetDateTime; + +public class ApiErrorResponse { + + private String code; + private String message; + private OffsetDateTime timestamp; + + public ApiErrorResponse(String code, String message) { + this.code = code; + this.message = message; + this.timestamp = OffsetDateTime.now(); + } + + public String getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public OffsetDateTime getTimestamp() { + return timestamp; + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/GlobalExceptionHandler.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000000..027fc31b14 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/GlobalExceptionHandler.java @@ -0,0 +1,41 @@ +package com.yape.payment.transaction.shared.exception; + +import jakarta.validation.ConstraintViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity handleNotFound(ResourceNotFoundException ex) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new ApiErrorResponse("TRX-404", ex.getMessage())); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleBadRequest(MethodArgumentNotValidException ex) { + String message = ex.getBindingResult().getFieldErrors().stream() + .map(err -> err.getField() + ": " + err.getDefaultMessage()) + .findFirst() + .orElse("Invalid request"); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ApiErrorResponse("TRX-400", message)); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity handleConstraint(ConstraintViolationException ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ApiErrorResponse("TRX-400", ex.getMessage())); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGeneric(Exception ex) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ApiErrorResponse("TRX-500", "Unexpected error")); + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ResourceNotFoundException.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..02633c093c --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/shared/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.yape.payment.transaction.shared.exception; + +public class ResourceNotFoundException extends RuntimeException { + + public ResourceNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/application.yml b/ms-payment-transaction-command/src/main/resources/application.yml index 7eac9a5ba6..1fead79ffe 100644 --- a/ms-payment-transaction-command/src/main/resources/application.yml +++ b/ms-payment-transaction-command/src/main/resources/application.yml @@ -13,22 +13,29 @@ spring: jpa: hibernate: - ddl-auto: validate - open-in-view: false + ddl-auto: none show-sql: false properties: hibernate: - format_sql: true + jdbc: + time_zone: UTC flyway: enabled: true - baseline-on-migrate: true + locations: classpath:db/migration kafka: bootstrap-servers: localhost:9092 + producer: + acks: all + properties: + enable.idempotence: true -management: - endpoints: - web: - exposure: - include: health,info \ No newline at end of file +outbox: + publisher: + fixed-delay-ms: 1000 + batch-size: 50 + +logging: + level: + root: INFO \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/db/migration/V1__create_transactions.sql b/ms-payment-transaction-command/src/main/resources/db/migration/V1__create_transactions.sql new file mode 100644 index 0000000000..a4e01f7a35 --- /dev/null +++ b/ms-payment-transaction-command/src/main/resources/db/migration/V1__create_transactions.sql @@ -0,0 +1,16 @@ +create table if not exists transactions ( + id bigserial primary key, + transaction_external_id uuid not null, + account_external_id_debit uuid not null, + account_external_id_credit uuid not null, + transfer_type_id integer not null, + value numeric(18,2) not null, + status varchar(20) not null, + created_at timestamptz not null default now() + ); + +create unique index if not exists ux_transactions_external_id + on transactions (transaction_external_id); + +create index if not exists ix_transactions_status_created_at + on transactions (status, created_at); \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/db/migration/V2__create_outbox_events.sql b/ms-payment-transaction-command/src/main/resources/db/migration/V2__create_outbox_events.sql new file mode 100644 index 0000000000..8842dd0986 --- /dev/null +++ b/ms-payment-transaction-command/src/main/resources/db/migration/V2__create_outbox_events.sql @@ -0,0 +1,18 @@ +create table if not exists outbox_events ( + id bigserial primary key, + aggregate_type varchar(50) not null, + aggregate_id uuid not null, + event_type varchar(100) not null, + topic varchar(200) not null, + payload jsonb not null, + status varchar(20) not null, + error text null, + created_at timestamptz not null default now(), + published_at timestamptz null + ); + +create index if not exists ix_outbox_status_created_at + on outbox_events (status, created_at); + +create index if not exists ix_outbox_aggregate_event + on outbox_events (aggregate_id, event_type); \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/db/migration/V3__outbox_payload_as_text.sql b/ms-payment-transaction-command/src/main/resources/db/migration/V3__outbox_payload_as_text.sql new file mode 100644 index 0000000000..94f866fb95 --- /dev/null +++ b/ms-payment-transaction-command/src/main/resources/db/migration/V3__outbox_payload_as_text.sql @@ -0,0 +1,2 @@ +ALTER TABLE outbox_events +ALTER COLUMN payload TYPE TEXT; \ No newline at end of file From 3e67e403391909ca49b079ab020bd8278f2eb235 Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 08:45:21 -0500 Subject: [PATCH 5/7] feat(antifraud): add antifraud evaluation service and publish validation events --- ms-payment-transaction-command/Dockerfile | 16 + ms-payment-transaction-command/pom.xml | 12 + .../src/main/resources/application-local.yml | 12 + .../src/main/resources/application.yml | 2 +- ms-risk-antifraud-evaluation/.gitattributes | 2 + ms-risk-antifraud-evaluation/.gitignore | 33 ++ ms-risk-antifraud-evaluation/.gitkeep | 0 .../.mvn/wrapper/maven-wrapper.properties | 3 + ms-risk-antifraud-evaluation/Dockerfile | 16 + ms-risk-antifraud-evaluation/mvnw | 295 ++++++++++++++++++ ms-risk-antifraud-evaluation/mvnw.cmd | 189 +++++++++++ ms-risk-antifraud-evaluation/pom.xml | 91 ++++++ .../MsRiskAntifraudEvaluationApplication.java | 13 + .../AntifraudEvaluationService.java | 34 ++ .../risk/antifraud/config/KafkaConfig.java | 4 + .../antifraud/domain/FraudRuleEngine.java | 24 ++ .../risk/antifraud/domain/RiskDecision.java | 6 + .../infrastructure/kafka/KafkaTopics.java | 9 + .../consumer/TransactionCreatedListener.java | 39 +++ .../kafka/dto/TransactionCreatedEvent.java | 72 +++++ .../kafka/dto/TransactionValidatedEvent.java | 53 ++++ .../TransactionValidatedProducer.java | 33 ++ .../shared/config/JacksonConfig.java | 19 ++ .../src/main/resources/application-local.yml | 16 + .../src/main/resources/application.yml | 3 + ...skAntifraudEvaluationApplicationTests.java | 13 + pom.xml | 17 + 27 files changed, 1025 insertions(+), 1 deletion(-) create mode 100644 ms-payment-transaction-command/Dockerfile create mode 100644 ms-payment-transaction-command/src/main/resources/application-local.yml create mode 100644 ms-risk-antifraud-evaluation/.gitattributes create mode 100644 ms-risk-antifraud-evaluation/.gitignore delete mode 100644 ms-risk-antifraud-evaluation/.gitkeep create mode 100644 ms-risk-antifraud-evaluation/.mvn/wrapper/maven-wrapper.properties create mode 100644 ms-risk-antifraud-evaluation/Dockerfile create mode 100644 ms-risk-antifraud-evaluation/mvnw create mode 100644 ms-risk-antifraud-evaluation/mvnw.cmd create mode 100644 ms-risk-antifraud-evaluation/pom.xml create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplication.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/application/AntifraudEvaluationService.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/config/KafkaConfig.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/FraudRuleEngine.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/RiskDecision.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/KafkaTopics.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/consumer/TransactionCreatedListener.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionCreatedEvent.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionValidatedEvent.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/producer/TransactionValidatedProducer.java create mode 100644 ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/shared/config/JacksonConfig.java create mode 100644 ms-risk-antifraud-evaluation/src/main/resources/application-local.yml create mode 100644 ms-risk-antifraud-evaluation/src/main/resources/application.yml create mode 100644 ms-risk-antifraud-evaluation/src/test/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplicationTests.java create mode 100644 pom.xml diff --git a/ms-payment-transaction-command/Dockerfile b/ms-payment-transaction-command/Dockerfile new file mode 100644 index 0000000000..b8e7d9f72f --- /dev/null +++ b/ms-payment-transaction-command/Dockerfile @@ -0,0 +1,16 @@ +FROM maven:3.9.9-eclipse-temurin-21 AS build +WORKDIR /app + +COPY pom.xml . +RUN mvn -B -e -C -T 1C dependency:go-offline + +COPY src ./src +RUN mvn clean package -Dmaven.test.skip=true + +FROM eclipse-temurin:21-jre +WORKDIR /app + +COPY --from=build /app/target/*.jar app.jar + +EXPOSE 8080 +ENTRYPOINT ["java","-jar","app.jar"] \ No newline at end of file diff --git a/ms-payment-transaction-command/pom.xml b/ms-payment-transaction-command/pom.xml index c54d6f6569..22a787a3a3 100644 --- a/ms-payment-transaction-command/pom.xml +++ b/ms-payment-transaction-command/pom.xml @@ -87,6 +87,18 @@ jackson-datatype-jsr310 + + org.springframework.boot + spring-boot-starter-test + test + + + + org.junit.jupiter + junit-jupiter + test + + diff --git a/ms-payment-transaction-command/src/main/resources/application-local.yml b/ms-payment-transaction-command/src/main/resources/application-local.yml new file mode 100644 index 0000000000..3bde14ea91 --- /dev/null +++ b/ms-payment-transaction-command/src/main/resources/application-local.yml @@ -0,0 +1,12 @@ +server: + port: 8080 + +spring: + datasource: + url: jdbc:postgresql://postgres:5432/yape + username: postgres + password: postgres + driver-class-name: org.postgresql.Driver + + kafka: + bootstrap-servers: kafka:29092 \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/application.yml b/ms-payment-transaction-command/src/main/resources/application.yml index 1fead79ffe..b83b14e8d0 100644 --- a/ms-payment-transaction-command/src/main/resources/application.yml +++ b/ms-payment-transaction-command/src/main/resources/application.yml @@ -25,7 +25,7 @@ spring: locations: classpath:db/migration kafka: - bootstrap-servers: localhost:9092 + bootstrap-servers: kafka:29092 producer: acks: all properties: diff --git a/ms-risk-antifraud-evaluation/.gitattributes b/ms-risk-antifraud-evaluation/.gitattributes new file mode 100644 index 0000000000..3b41682ac5 --- /dev/null +++ b/ms-risk-antifraud-evaluation/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/ms-risk-antifraud-evaluation/.gitignore b/ms-risk-antifraud-evaluation/.gitignore new file mode 100644 index 0000000000..667aaef0c8 --- /dev/null +++ b/ms-risk-antifraud-evaluation/.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/ms-risk-antifraud-evaluation/.gitkeep b/ms-risk-antifraud-evaluation/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/ms-risk-antifraud-evaluation/.mvn/wrapper/maven-wrapper.properties b/ms-risk-antifraud-evaluation/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..8dea6c227c --- /dev/null +++ b/ms-risk-antifraud-evaluation/.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/ms-risk-antifraud-evaluation/Dockerfile b/ms-risk-antifraud-evaluation/Dockerfile new file mode 100644 index 0000000000..d361aca4f6 --- /dev/null +++ b/ms-risk-antifraud-evaluation/Dockerfile @@ -0,0 +1,16 @@ +FROM maven:3.9.9-eclipse-temurin-21 AS build +WORKDIR /app + +COPY pom.xml . +RUN mvn -B -e -C -T 1C dependency:go-offline + +COPY src ./src +RUN mvn clean package -DskipTests + +FROM eclipse-temurin:21-jre +WORKDIR /app + +COPY --from=build /app/target/*.jar app.jar + +EXPOSE 8080 +ENTRYPOINT ["java","-jar","app.jar"] \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/mvnw b/ms-risk-antifraud-evaluation/mvnw new file mode 100644 index 0000000000..bd8896bf22 --- /dev/null +++ b/ms-risk-antifraud-evaluation/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/ms-risk-antifraud-evaluation/mvnw.cmd b/ms-risk-antifraud-evaluation/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/ms-risk-antifraud-evaluation/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/ms-risk-antifraud-evaluation/pom.xml b/ms-risk-antifraud-evaluation/pom.xml new file mode 100644 index 0000000000..76faa1dfce --- /dev/null +++ b/ms-risk-antifraud-evaluation/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.1 + + + com.yape.risk + ms-risk-antifraud-evaluation + 0.0.1-SNAPSHOT + ms-risk-antifraud-evaluation + ms-risk-antifraud-evaluation + + + + + + + + + + + + + + + 21 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-kafka + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-json + + + + org.springframework.boot + spring-boot-starter-actuator-test + test + + + org.springframework.boot + spring-boot-starter-kafka-test + test + + + + org.projectlombok + lombok + true + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplication.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplication.java new file mode 100644 index 0000000000..c765bc65fc --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplication.java @@ -0,0 +1,13 @@ +package com.yape.risk.antifraud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MsRiskAntifraudEvaluationApplication { + + public static void main(String[] args) { + SpringApplication.run(MsRiskAntifraudEvaluationApplication.class, args); + } + +} diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/application/AntifraudEvaluationService.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/application/AntifraudEvaluationService.java new file mode 100644 index 0000000000..75864d132c --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/application/AntifraudEvaluationService.java @@ -0,0 +1,34 @@ +package com.yape.risk.antifraud.application; + +import com.yape.risk.antifraud.domain.FraudRuleEngine; +import com.yape.risk.antifraud.domain.RiskDecision; +import com.yape.risk.antifraud.infrastructure.kafka.dto.TransactionCreatedEvent; +import com.yape.risk.antifraud.infrastructure.kafka.dto.TransactionValidatedEvent; +import org.springframework.stereotype.Service; + +import java.time.OffsetDateTime; +import java.util.UUID; + +@Service +public class AntifraudEvaluationService { + + private final FraudRuleEngine ruleEngine; + + public AntifraudEvaluationService(FraudRuleEngine ruleEngine) { + this.ruleEngine = ruleEngine; + } + + public TransactionValidatedEvent evaluate(TransactionCreatedEvent event) { + + RiskDecision decision = ruleEngine.evaluate(event); + + TransactionValidatedEvent result = new TransactionValidatedEvent(); + result.setEventId(UUID.randomUUID()); + result.setTransactionExternalId(event.getTransactionExternalId()); + result.setResult(decision.name()); + result.setReason(decision == RiskDecision.APPROVED ? "OK" : "Risk rule triggered"); + result.setEvaluatedAt(OffsetDateTime.now()); + + return result; + } +} \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/config/KafkaConfig.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/config/KafkaConfig.java new file mode 100644 index 0000000000..6c23cc7c27 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/config/KafkaConfig.java @@ -0,0 +1,4 @@ +package com.yape.risk.antifraud.config; + +public class KafkaConfig { +} diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/FraudRuleEngine.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/FraudRuleEngine.java new file mode 100644 index 0000000000..d03b8c86d4 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/FraudRuleEngine.java @@ -0,0 +1,24 @@ +package com.yape.risk.antifraud.domain; + +import com.yape.risk.antifraud.infrastructure.kafka.dto.TransactionCreatedEvent; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; + +@Component +public class FraudRuleEngine { + + public RiskDecision evaluate(TransactionCreatedEvent event) { + + if (event.getValue() == null) { + return RiskDecision.REJECTED; + } + + // regla 1000 + if (event.getValue().compareTo(new BigDecimal("1000")) > 0) { + return RiskDecision.REJECTED; + } + + return RiskDecision.APPROVED; + } +} \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/RiskDecision.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/RiskDecision.java new file mode 100644 index 0000000000..76f61aed39 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/domain/RiskDecision.java @@ -0,0 +1,6 @@ +package com.yape.risk.antifraud.domain; + +public enum RiskDecision { + APPROVED, + REJECTED +} \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/KafkaTopics.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/KafkaTopics.java new file mode 100644 index 0000000000..a384091da1 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/KafkaTopics.java @@ -0,0 +1,9 @@ +package com.yape.risk.antifraud.infrastructure.kafka; + +public final class KafkaTopics { + + private KafkaTopics() {} + + public static final String PAYMENT_TRANSACTION_CREATED_V1 = "payment.transaction.created.v1"; + public static final String PAYMENT_TRANSACTION_VALIDATED_V1 = "payment.transaction.validated.v1"; +} diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/consumer/TransactionCreatedListener.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/consumer/TransactionCreatedListener.java new file mode 100644 index 0000000000..29465310f2 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/consumer/TransactionCreatedListener.java @@ -0,0 +1,39 @@ +package com.yape.risk.antifraud.infrastructure.kafka.consumer; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.risk.antifraud.application.AntifraudEvaluationService; +import com.yape.risk.antifraud.infrastructure.kafka.KafkaTopics; +import com.yape.risk.antifraud.infrastructure.kafka.dto.TransactionCreatedEvent; +import com.yape.risk.antifraud.infrastructure.kafka.producer.TransactionValidatedProducer; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +public class TransactionCreatedListener { + + private final ObjectMapper objectMapper; + private final AntifraudEvaluationService antifraudService; + private final TransactionValidatedProducer producer; + + public TransactionCreatedListener(ObjectMapper objectMapper, + AntifraudEvaluationService antifraudService, + TransactionValidatedProducer producer) { + this.objectMapper = objectMapper; + this.antifraudService = antifraudService; + this.producer = producer; + } + + @KafkaListener( + topics = KafkaTopics.PAYMENT_TRANSACTION_CREATED_V1, + groupId = "ms-risk-antifraud-evaluation" + ) + public void onMessage(String message) throws Exception { + + TransactionCreatedEvent event = + objectMapper.readValue(message, TransactionCreatedEvent.class); + + var result = antifraudService.evaluate(event); + + producer.publish(result); + } +} diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionCreatedEvent.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionCreatedEvent.java new file mode 100644 index 0000000000..e2cddddcb8 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionCreatedEvent.java @@ -0,0 +1,72 @@ +package com.yape.risk.antifraud.infrastructure.kafka.dto; + +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.UUID; + +public class TransactionCreatedEvent { + + private UUID eventId; + private UUID transactionExternalId; + private UUID accountExternalIdDebit; + private UUID accountExternalIdCredit; + private Integer tranferTypeId; + private BigDecimal value; + private OffsetDateTime createdAt; + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public UUID getTransactionExternalId() { + return transactionExternalId; + } + + public void setTransactionExternalId(UUID transactionExternalId) { + this.transactionExternalId = transactionExternalId; + } + + public UUID getAccountExternalIdDebit() { + return accountExternalIdDebit; + } + + public void setAccountExternalIdDebit(UUID accountExternalIdDebit) { + this.accountExternalIdDebit = accountExternalIdDebit; + } + + public UUID getAccountExternalIdCredit() { + return accountExternalIdCredit; + } + + public void setAccountExternalIdCredit(UUID accountExternalIdCredit) { + this.accountExternalIdCredit = accountExternalIdCredit; + } + + public Integer getTranferTypeId() { + return tranferTypeId; + } + + public void setTranferTypeId(Integer tranferTypeId) { + this.tranferTypeId = tranferTypeId; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(OffsetDateTime createdAt) { + this.createdAt = createdAt; + } +} diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionValidatedEvent.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionValidatedEvent.java new file mode 100644 index 0000000000..90d349a59a --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/dto/TransactionValidatedEvent.java @@ -0,0 +1,53 @@ +package com.yape.risk.antifraud.infrastructure.kafka.dto; + +import java.time.OffsetDateTime; +import java.util.UUID; + +public class TransactionValidatedEvent { + + private UUID eventId; + private UUID transactionExternalId; + private String result; // APPROVED / REJECTED + private String reason; + private OffsetDateTime evaluatedAt; + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public UUID getTransactionExternalId() { + return transactionExternalId; + } + + public void setTransactionExternalId(UUID transactionExternalId) { + this.transactionExternalId = transactionExternalId; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public OffsetDateTime getEvaluatedAt() { + return evaluatedAt; + } + + public void setEvaluatedAt(OffsetDateTime evaluatedAt) { + this.evaluatedAt = evaluatedAt; + } +} \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/producer/TransactionValidatedProducer.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/producer/TransactionValidatedProducer.java new file mode 100644 index 0000000000..1fcb5519af --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/infrastructure/kafka/producer/TransactionValidatedProducer.java @@ -0,0 +1,33 @@ +package com.yape.risk.antifraud.infrastructure.kafka.producer; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.risk.antifraud.infrastructure.kafka.KafkaTopics; +import com.yape.risk.antifraud.infrastructure.kafka.dto.TransactionValidatedEvent; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class TransactionValidatedProducer { + + private final KafkaTemplate kafkaTemplate; + private final ObjectMapper objectMapper; + + public TransactionValidatedProducer(KafkaTemplate kafkaTemplate, + ObjectMapper objectMapper) { + this.kafkaTemplate = kafkaTemplate; + this.objectMapper = objectMapper; + } + + public void publish(TransactionValidatedEvent event) { + try { + String payload = objectMapper.writeValueAsString(event); + kafkaTemplate.send( + KafkaTopics.PAYMENT_TRANSACTION_VALIDATED_V1, + event.getTransactionExternalId().toString(), + payload + ); + } catch (Exception e) { + throw new IllegalStateException("Error publishing antifraud result", e); + } + } +} diff --git a/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/shared/config/JacksonConfig.java b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/shared/config/JacksonConfig.java new file mode 100644 index 0000000000..58b625fbc9 --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/java/com/yape/risk/antifraud/shared/config/JacksonConfig.java @@ -0,0 +1,19 @@ +package com.yape.risk.antifraud.shared.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class JacksonConfig { + + @Bean + public ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return mapper; + } +} diff --git a/ms-risk-antifraud-evaluation/src/main/resources/application-local.yml b/ms-risk-antifraud-evaluation/src/main/resources/application-local.yml new file mode 100644 index 0000000000..25d698fced --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/resources/application-local.yml @@ -0,0 +1,16 @@ +server: + port: 8080 + +spring: + kafka: + bootstrap-servers: kafka:29092 + + consumer: + group-id: ms-risk-antifraud-evaluation + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/src/main/resources/application.yml b/ms-risk-antifraud-evaluation/src/main/resources/application.yml new file mode 100644 index 0000000000..d5d06c0b5b --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/main/resources/application.yml @@ -0,0 +1,3 @@ +spring: + application: + name: ms-risk-antifraud-evaluation \ No newline at end of file diff --git a/ms-risk-antifraud-evaluation/src/test/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplicationTests.java b/ms-risk-antifraud-evaluation/src/test/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplicationTests.java new file mode 100644 index 0000000000..b94002222e --- /dev/null +++ b/ms-risk-antifraud-evaluation/src/test/java/com/yape/risk/antifraud/MsRiskAntifraudEvaluationApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.risk.antifraud; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MsRiskAntifraudEvaluationApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000..a528af45d1 --- /dev/null +++ b/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + com.yape + app-nodejs-codechallenge + 1.0.0-SNAPSHOT + pom + + + ms-payment-transaction-command + ms-risk-antifraud-evaluation + + + \ No newline at end of file From 61f4d0063b59cdd76f9ce76a60b11f47286483a0 Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 09:15:37 -0500 Subject: [PATCH 6/7] feat(transaction): consume validation events and update transaction status --- .../application/TransactionService.java | 43 +++++++++++++++ .../infrastructure/kafka/KafkaTopics.java | 3 ++ .../kafka/TransactionValidatedConsumer.java | 44 +++++++++++++++ .../kafka/dto/TransactionValidatedEvent.java | 53 +++++++++++++++++++ .../src/main/resources/application-local.yml | 10 +++- .../src/main/resources/application.yml | 5 ++ 6 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/TransactionValidatedConsumer.java create mode 100644 ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionValidatedEvent.java diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java index 22e86305fb..290162cec0 100644 --- a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/application/TransactionService.java @@ -18,6 +18,8 @@ import jakarta.transaction.Transactional; import java.util.UUID; import org.springframework.stereotype.Service; +import com.yape.payment.transaction.infrastructure.kafka.dto.TransactionValidatedEvent; + @Service public class TransactionService { @@ -107,4 +109,45 @@ private TransactionType mapType(Integer transferTypeId) { } return TransactionType.TRANSFER; } + + @Transactional + public void applyValidationResult(TransactionValidatedEvent event) { + if (event == null || event.getTransactionExternalId() == null) { + return; + } + + TransactionEntity entity = transactionRepository + .findByTransactionExternalId(event.getTransactionExternalId()) + .orElse(null); + + if (entity == null) { + // Puede pasar si llega un validated de una tx inexistente o DB no sincronizada. + return; + } + + // Idempotencia mínima: si ya está final + if (entity.getStatus() == TransactionStatus.APPROVED + || entity.getStatus() == TransactionStatus.REJECTED) { + return; + } + + TransactionStatus newStatus = mapValidatedResult(event.getResult()); + entity.setStatus(newStatus); + + transactionRepository.save(entity); + } + + private TransactionStatus mapValidatedResult(String result) { + if (result == null) { + return TransactionStatus.REJECTED; + } + if ("APPROVED".equalsIgnoreCase(result)) { + return TransactionStatus.APPROVED; + } + if ("REJECTED".equalsIgnoreCase(result)) { + return TransactionStatus.REJECTED; + } + // safe default + return TransactionStatus.REJECTED; + } } diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java index 3a57f1084b..1f63a7564e 100644 --- a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/KafkaTopics.java @@ -7,4 +7,7 @@ private KafkaTopics() { public static final String PAYMENT_TRANSACTION_CREATED_V1 = "payment.transaction.created.v1"; + + public static final String PAYMENT_TRANSACTION_VALIDATED_V1 = "payment.transaction.validated.v1"; + } diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/TransactionValidatedConsumer.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/TransactionValidatedConsumer.java new file mode 100644 index 0000000000..614b402694 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/TransactionValidatedConsumer.java @@ -0,0 +1,44 @@ +package com.yape.payment.transaction.infrastructure.kafka; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yape.payment.transaction.application.TransactionService; +import com.yape.payment.transaction.infrastructure.kafka.dto.TransactionValidatedEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +public class TransactionValidatedConsumer { + + private static final Logger logger = LoggerFactory.getLogger(TransactionValidatedConsumer.class); + + private final ObjectMapper objectMapper; + private final TransactionService transactionService; + + public TransactionValidatedConsumer(ObjectMapper objectMapper, TransactionService transactionService) { + this.objectMapper = objectMapper; + this.transactionService = transactionService; + } + + @KafkaListener( + topics = KafkaTopics.PAYMENT_TRANSACTION_VALIDATED_V1, + groupId = "${spring.kafka.consumer.group-id}" + ) + public void consume(String message) { + try { + TransactionValidatedEvent event = + objectMapper.readValue(message, TransactionValidatedEvent.class); + + logger.info("Consumed validation event. transactionExternalId={}, result={}", + event.getTransactionExternalId(), event.getResult()); + + transactionService.applyValidationResult(event); + + } catch (Exception e) { + // log + rethrow para que Kafka reintente (si no tienes DLQ configurado) + logger.error("Failed to process validation event message={}", message, e); + throw new IllegalStateException("Failed to process validation event", e); + } + } +} diff --git a/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionValidatedEvent.java b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionValidatedEvent.java new file mode 100644 index 0000000000..6dbbea82b4 --- /dev/null +++ b/ms-payment-transaction-command/src/main/java/com/yape/payment/transaction/infrastructure/kafka/dto/TransactionValidatedEvent.java @@ -0,0 +1,53 @@ +package com.yape.payment.transaction.infrastructure.kafka.dto; + +import java.time.OffsetDateTime; +import java.util.UUID; + +public class TransactionValidatedEvent { + + private UUID eventId; + private UUID transactionExternalId; + private String result; // "APPROVED" | "REJECTED" + private String reason; + private OffsetDateTime evaluatedAt; + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public UUID getTransactionExternalId() { + return transactionExternalId; + } + + public void setTransactionExternalId(UUID transactionExternalId) { + this.transactionExternalId = transactionExternalId; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public OffsetDateTime getEvaluatedAt() { + return evaluatedAt; + } + + public void setEvaluatedAt(OffsetDateTime evaluatedAt) { + this.evaluatedAt = evaluatedAt; + } +} \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/application-local.yml b/ms-payment-transaction-command/src/main/resources/application-local.yml index 3bde14ea91..01dc60ac63 100644 --- a/ms-payment-transaction-command/src/main/resources/application-local.yml +++ b/ms-payment-transaction-command/src/main/resources/application-local.yml @@ -9,4 +9,12 @@ spring: driver-class-name: org.postgresql.Driver kafka: - bootstrap-servers: kafka:29092 \ No newline at end of file + bootstrap-servers: kafka:29092 + consumer: + group-id: ms-payment-transaction-command + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer \ No newline at end of file diff --git a/ms-payment-transaction-command/src/main/resources/application.yml b/ms-payment-transaction-command/src/main/resources/application.yml index b83b14e8d0..c4d03acbac 100644 --- a/ms-payment-transaction-command/src/main/resources/application.yml +++ b/ms-payment-transaction-command/src/main/resources/application.yml @@ -26,6 +26,11 @@ spring: kafka: bootstrap-servers: kafka:29092 + consumer: + group-id: ms-payment-transaction-command + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer producer: acks: all properties: From 27c3d1b553b52fb0075937951be5eeada9a1c78d Mon Sep 17 00:00:00 2001 From: jcflores Date: Tue, 6 Jan 2026 09:33:30 -0500 Subject: [PATCH 7/7] chore: dockerize microservices and integrate into docker-compose --- docker-compose.yml | 4 +++- .../src/main/resources/application.yml | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5b47c4032e..77ea2c8f97 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -39,7 +39,9 @@ services: kafka-ui: image: provectuslabs/kafka-ui:latest container_name: yape-kafka-ui - depends_on: [kafka] + depends_on: + - kafka + - zookeeper ports: - "8088:8080" environment: diff --git a/ms-payment-transaction-command/src/main/resources/application.yml b/ms-payment-transaction-command/src/main/resources/application.yml index c4d03acbac..680ed951ee 100644 --- a/ms-payment-transaction-command/src/main/resources/application.yml +++ b/ms-payment-transaction-command/src/main/resources/application.yml @@ -1,5 +1,5 @@ server: - port: 8081 + port: 8080 spring: application: