diff --git a/README.md b/README.md index b067a71026..c40502487c 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,4 @@ -# Yape Code Challenge :rocket: - -Our code challenge will let you marvel us with your Jedi coding skills :smile:. - -Don't forget that the proper way to submit your work is to fork the repo and create a PR :wink: ... have fun !! - -- [Problem](#problem) -- [Tech Stack](#tech_stack) -- [Send us your challenge](#send_us_your_challenge) +# Solución: Yape Code Challenge :rocket: # Problem @@ -30,53 +22,320 @@ Every transaction with a value greater than 1000 should be rejected. Transaction -- Update transaction Status event--> transactionDatabase[(Database)] ``` -# Tech Stack +# Solución -
    -
  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. -
+### Diagrama de flujo +```mermaid +--- +config: + layout: elk +--- +flowchart LR + API-Transaction["API-Transaction"] -- "1. Save Transaction with pending Status" --> transactionDatabase[("Database")] + transactionDatabase -- "2. Confirm Register" --> API-Transaction + API-Transaction -- "3. Produce a Transaction Event with Pending Status" --> transactionCreatedTopic[("Topic: transaction.created")] + API-Anti-Fraud["API-Anti-Fraud"] -- "4. Consume the Transaction Event" --> transactionCreatedTopic + API-Anti-Fraud -- "5.1. If not error: Produce a Transaction Validated Event" --> transactionValidatedTopic[("Topic: transaction.validated")] + API-Anti-Fraud -- "5.2. If error: produce an event on DLT" --> transactionCreatedDLTTopic[("Topic: transaction.created.dlt")] + API-Transaction -- "6. Consume the Transaction Validated Event" --> transactionValidatedTopic + API-Transaction -- "7.1. If not error: Update Transaction Status" --> transactionDatabase + API-Transaction -- "7.2. If error: produce an event on DLT" --> transactionEvaluatedDLTTopic[("Topic: transaction.evaluated.dlt")] +``` + +## 📋 Requisitos Previos + +- **Docker Desktop** 4.x o superior +- **Docker Compose** 3.9 o superior +- Al menos **8GB de RAM** disponible para Docker +- Puertos disponibles: `1435`, `2181`, `9092`, `8080`, `8081` + +## 🏗️ Arquitectura del Sistema + +El proyecto contiene los siguientes servicios: + +### Infraestructura Base +- **SQL Server 2022**: Base de datos principal (Puerto: 1435) +- **Zookeeper**: Coordinación de Kafka (Puerto: 2181) +- **Kafka**: Message broker para eventos (Puerto: 9092) +- **Kafka Init**: Inicializador de topics de Kafka + +### Aplicaciones +- **yape-transactions-api**: API de transacciones (Puerto: 8080) +- **yape-anti-fraud-api**: API de detección de fraude (Puerto: 8081) + +## 📂 Estructura del Proyecto + +``` +app-nodejs-codechallenge/ +├── docker-compose.yml # Orquestación de servicios +├── sqlserver/ +│ ├── data/ # Archivos de base de datos +│ ├── log/ # Logs de SQL Server +│ └── init/ +│ ├── init-yape.sh # Script de inicialización +│ └── init-yape.sql # DDL y datos iniciales +├── kafka/ +│ └── create-topics.sh # Creación de topics de Kafka +├── yape-transactions-api/ +│ └── Dockerfile # Imagen de API de transacciones +└── yape-anti-fraud-api/ + └── Dockerfile # Imagen de API anti-fraude +``` + +## 🚀 Despliegue Paso a Paso + +### Paso 1: Clonar o Descargar el Proyecto + +```powershell +# Si usas Git +git clone https://github.com/yaperos/app-nodejs-codechallenge.git +cd app-nodejs-codechallenge + +# O simplemente navega a la carpeta del proyecto +cd f:\tu_path\app-nodejs-codechallenge +``` + +### Paso 2: Verificar Docker Desktop + +Asegúrate de que Docker Desktop esté ejecutándose: + +```powershell +docker --version +docker-compose --version +``` + +### Paso 3: Limpiar Contenedores Anteriores (Opcional) + +Si ya ejecutaste el proyecto antes: + +```powershell +docker-compose down -v +``` + +### Paso 4: Construir las Imágenes + +```powershell +docker-compose build +``` + +Este proceso puede tardar varios minutos la primera vez. + +### Paso 5: Iniciar los Servicios + +```powershell +docker-compose up -d +``` + +El flag `-d` ejecuta los contenedores en segundo plano. + +### Paso 6: Verificar el Estado de los Servicios + +```powershell +docker-compose ps +``` + +Todos los servicios deben mostrar estado `Up` o `healthy` con excepción del kafka-init que debe estar en `exited (0)`. + +### Paso 7: Monitorear los Logs (Opcional) + +```powershell +# Ver logs de todos los servicios +docker-compose logs -f + +# Ver logs de un servicio específico +docker-compose logs -f yape-transactions-api +docker-compose logs -f yape-anti-fraud-api +docker-compose logs -f sqlserver +``` + +Presiona `Ctrl+C` para salir de los logs. + +## ✅ Verificación del Despliegue + +### Verificar SQL Server + +```powershell +docker exec -it sqlserver2022-docker /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P 'Yape2025.' -C -Q "SELECT name FROM sys.databases" +``` + +### Verificar Kafka Topics + +```powershell +docker exec -it kafka kafka-topics --bootstrap-server localhost:9092 --list +``` + +### Verificar APIs + +**API de Transacciones:** +```powershell +Invoke-WebRequest -Uri 'http://localhost:8090/actuator/health' -Method Get +``` + +**API Anti-Fraude:** +```powershell +Invoke-WebRequest -Uri 'http://localhost:8091/actuator/health' -Method Get +``` + +## 🧪 Pruebas del Sistema + +### Crear una Transacción + +```powershell +$body = @{ + accountExternalIdDebit = "db0123" + accountExternalIdCredit = "cr1235" + tranferTypeId = 1 + value = 920 +} | ConvertTo-Json + +Invoke-RestMethod -Uri 'http://localhost:8090/v1/transactions' -Method Post -ContentType 'application/json' -Body $body +``` + +### Consultar una Transacción + +```powershell +# Reemplaza {transactionExternalId} con el ID devuelto en la creación +Invoke-RestMethod -Uri 'http://localhost:8090/v1/transactions/{transactionExternalId}' -Method Get +``` + +## 🔧 Configuración + +### Credenciales de SQL Server +- **Usuario**: `sa` +- **Contraseña**: `Yape2025.` +- **Puerto Host**: `1435` +- **Base de Datos**: `YAPE` + +### Kafka +- **Bootstrap Server (Externo)**: `localhost:9092` +- **Bootstrap Server (Interno)**: `kafka:29092` + +### Variables de Entorno de las APIs + +Ambas APIs comparten la misma configuración: +- `SPRING_THREADS_VIRTUAL_ENABLED`: `true` +- `SPRING_DATASOURCE_URL`: Conexión a SQL Server +- `SPRING_KAFKA_BOOTSTRAP_SERVERS`: `kafka:29092` + +## 🛑 Detener el Sistema + +### Detener servicios (conservar datos) + +```powershell +docker-compose stop +``` + +### Detener y eliminar contenedores (conservar volúmenes) + +```powershell +docker-compose down +``` + +### Detener y eliminar todo (incluye volúmenes y datos) + +```powershell +docker-compose down -v +``` + +## 🔄 Reiniciar Servicios + +```powershell +# Reiniciar todos los servicios +docker-compose restart -We do provide a `Dockerfile` to help you get started with a dev environment. +# Reiniciar un servicio específico +docker-compose restart yape-transactions-api +``` + +## 📊 Monitoreo y Debugging + +### Ver recursos utilizados + +```powershell +docker stats +``` + +### Acceder a un contenedor + +```powershell +# SQL Server +docker exec -it sqlserver2022-docker bash + +# Kafka +docker exec -it kafka bash + +# Aplicaciones +docker exec -it yape-transactions-api bash +docker exec -it yape-anti-fraud-api bash +``` + +### Ver logs en tiempo real + +```powershell +docker-compose logs -f --tail=100 +``` + +## ⚠️ Troubleshooting -You must have two resources: +### Problema: Puertos en uso -1. Resource to create a transaction that must containt: +Si los puertos están ocupados, modifica `docker-compose.yml`: -```json -{ - "accountExternalIdDebit": "Guid", - "accountExternalIdCredit": "Guid", - "tranferTypeId": 1, - "value": 120 -} +```yaml +ports: + - "NUEVO_PUERTO:PUERTO_INTERNO" ``` -2. Resource to retrieve a transaction +### Problema: SQL Server no inicia -```json -{ - "transactionExternalId": "Guid", - "transactionType": { - "name": "" - }, - "transactionStatus": { - "name": "" - }, - "value": 120, - "createdAt": "Date" -} +Verifica que tienes suficiente RAM disponible y que los archivos de datos no estén corruptos: + +```powershell +docker-compose logs sqlserver +``` + +### Problema: Kafka no está listo + +Espera a que el healthcheck de Kafka esté `healthy`: + +```powershell +docker-compose ps kafka +``` + +### Problema: APIs no se conectan a la BD + +Verifica que SQL Server esté saludable antes de iniciar las APIs: + +```powershell +docker-compose up -d sqlserver +# Espera ~30 segundos +docker-compose up -d ``` -## Optional +## 📝 Notas Adicionales + +- Los datos de SQL Server persisten en `./sqlserver/data` +- Los logs de SQL Server se almacenan en `./sqlserver/log` +- La inicialización de la BD se ejecuta automáticamente con `init-yape.sh` +- Los topics de Kafka se crean automáticamente con el servicio `kafka-init` +- Las APIs usan hilos virtuales de Java (Project Loom) habilitados + +## 🔗 Endpoints Principales -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? +- **Transactions API**: http://localhost:8090 + - Health: http://localhost:8090/actuator/health -You can use Graphql; +- **Anti-Fraud API**: http://localhost:8091 + - Health: http://localhost:8091/actuator/health -# Send us your challenge +## 👥 Soporte + +Para problemas o consultas, revisa los logs de los servicios: + +```powershell +docker-compose logs -f +``` -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. +**Última actualización**: Diciembre 2025 diff --git a/docker-compose.yml b/docker-compose.yml index 0e8807f21c..00ea8afef7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,25 +1,128 @@ -version: "3.7" +version: "3.9" + services: - postgres: - image: postgres:14 - ports: - - "5432:5432" + sqlserver: + image: mcr.microsoft.com/mssql/server:2022-latest + container_name: sqlserver2022-docker environment: - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=postgres + ACCEPT_EULA: "Y" + MSSQL_SA_PASSWORD: "Yape2025." + ports: + - "1435:1433" + volumes: + - ./sqlserver/data:/var/opt/mssql/data + - ./sqlserver/log:/var/opt/mssql/log + - ./sqlserver/init:/usr/src/init + command: ["/bin/bash", "-c", "/usr/src/init/init-yape.sh"] + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P 'Yape2025.' -C -Q \"SELECT 1\" >/dev/null 2>&1 || exit 1"] + interval: 10s + timeout: 5s + retries: 20 + networks: + - yape-net + zookeeper: - image: confluentinc/cp-zookeeper:5.5.3 + image: confluentinc/cp-zookeeper:7.7.7 + container_name: zookeeper + ports: + - "2181:2181" environment: ZOOKEEPER_CLIENT_PORT: 2181 + ZOOKEEPER_TICK_TIME: 2000 + networks: + - yape-net + kafka: - image: confluentinc/cp-enterprise-kafka:5.5.3 - depends_on: [zookeeper] + image: confluentinc/cp-kafka:7.7.7 + container_name: kafka + depends_on: + - zookeeper + ports: + - "9092:9092" environment: - KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" - KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT KAFKA_BROKER_ID: 1 + KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" + KAFKA_LISTENERS: "PLAINTEXT://0.0.0.0:29092,PLAINTEXT_HOST://0.0.0.0:9092" + KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092" + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: "PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT" + KAFKA_INTER_BROKER_LISTENER_NAME: "PLAINTEXT" KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 - KAFKA_JMX_PORT: 9991 + KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false" + healthcheck: + test: ["CMD-SHELL", "kafka-topics --bootstrap-server localhost:9092 --list >/dev/null 2>&1"] + interval: 5s + timeout: 5s + retries: 30 + restart: unless-stopped + networks: + - yape-net + + # --------------------------- + # Kafka init (create topics) + # --------------------------- + kafka-init: + image: confluentinc/cp-kafka:7.7.7 + container_name: kafka-init + depends_on: + kafka: + condition: service_healthy + volumes: + - ./kafka/create-topics.sh:/scripts/create-topics.sh:ro + command: ["bash", "-lc", "BOOTSTRAP_SERVER=kafka:29092 bash /scripts/create-topics.sh"] + restart: "no" + networks: + - yape-net + + yape-transactions-api: + build: + context: ./yape-transactions-api + dockerfile: Dockerfile + container_name: yape-transactions-api + depends_on: + sqlserver: + condition: service_healthy + kafka: + condition: service_healthy + kafka-init: + condition: service_completed_successfully + ports: + - "8090:8080" + environment: + SPRING_THREADS_VIRTUAL_ENABLED: "true" + SPRING_DATASOURCE_URL: "jdbc:sqlserver://sqlserver2022-docker:1433;databaseName=YAPE;encrypt=true;trustServerCertificate=true" + SPRING_DATASOURCE_USERNAME: "sa" + SPRING_DATASOURCE_PASSWORD: "Yape2025." + SPRING_KAFKA_BOOTSTRAP_SERVERS: "kafka:29092" + restart: unless-stopped + networks: + - yape-net + + yape-anti-fraud-api: + build: + context: ./yape-anti-fraud-api + dockerfile: Dockerfile + container_name: yape-anti-fraud-api + depends_on: + sqlserver: + condition: service_healthy + kafka: + condition: service_healthy + kafka-init: + condition: service_completed_successfully ports: - - 9092:9092 + - "8091:8080" + environment: + SPRING_THREADS_VIRTUAL_ENABLED: "true" + SPRING_DATASOURCE_URL: "jdbc:sqlserver://sqlserver2022-docker:1433;databaseName=YAPE;encrypt=true;trustServerCertificate=true" + SPRING_DATASOURCE_USERNAME: "sa" + SPRING_DATASOURCE_PASSWORD: "Yape2025." + SPRING_KAFKA_BOOTSTRAP_SERVERS: "kafka:29092" + restart: unless-stopped + networks: + - yape-net + +networks: + yape-net: + driver: bridge diff --git a/kafka/create-topics.sh b/kafka/create-topics.sh new file mode 100644 index 0000000000..e316059f0f --- /dev/null +++ b/kafka/create-topics.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +BOOTSTRAP="${BOOTSTRAP_SERVER:-kafka:29092}" + +echo "Waiting for Kafka at ${BOOTSTRAP}..." +for i in {1..120}; do + if kafka-topics --bootstrap-server "$BOOTSTRAP" --list >/dev/null 2>&1; then + echo "Kafka is ready." + break + fi + sleep 1 +done + +# Si después de 120s no estuvo listo, fallamos explícito +kafka-topics --bootstrap-server "$BOOTSTRAP" --list >/dev/null 2>&1 || { + echo "Kafka did not become ready in time" + exit 1 +} + +create_topic () { + local topic="$1" + local partitions="${2:-3}" + local rf="${3:-1}" + + if kafka-topics --bootstrap-server "$BOOTSTRAP" --describe --topic "$topic" >/dev/null 2>&1; then + echo "Topic already exists: $topic" + else + echo "Creating topic: $topic (partitions=$partitions, rf=$rf)" + kafka-topics --bootstrap-server "$BOOTSTRAP" \ + --create --topic "$topic" \ + --partitions "$partitions" \ + --replication-factor "$rf" + fi +} + +create_topic "transaction.created" 3 1 +create_topic "transaction.validated" 3 1 +create_topic "transaction.created.dlt" 3 1 +create_topic "transaction.validated.dlt" 3 1 + +echo "Topics created/verified OK:" +kafka-topics --bootstrap-server "$BOOTSTRAP" --list diff --git a/source-code/yape-anti-fraud-api/.mvn/wrapper/maven-wrapper.properties b/source-code/yape-anti-fraud-api/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..c0bcafe984 --- /dev/null +++ b/source-code/yape-anti-fraud-api/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/source-code/yape-anti-fraud-api/HELP.md b/source-code/yape-anti-fraud-api/HELP.md new file mode 100644 index 0000000000..cc322724b4 --- /dev/null +++ b/source-code/yape-anti-fraud-api/HELP.md @@ -0,0 +1,23 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.5.8/maven-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.8/maven-plugin/build-image.html) +* [Spring for Apache Kafka](https://docs.spring.io/spring-boot/3.5.8/reference/messaging/kafka.html) +* [Spring Data JPA](https://docs.spring.io/spring-boot/3.5.8/reference/data/sql.html#data.sql.jpa-and-spring-data) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) + +### Maven Parent overrides + +Due to Maven's design, elements are inherited from the parent POM to the project POM. +While most of the inheritance is fine, it also inherits unwanted elements like `` and `` from the parent. +To prevent this, the project POM contains empty overrides for these elements. +If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides. + diff --git a/source-code/yape-anti-fraud-api/mvnw b/source-code/yape-anti-fraud-api/mvnw new file mode 100644 index 0000000000..bd8896bf22 --- /dev/null +++ b/source-code/yape-anti-fraud-api/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/source-code/yape-anti-fraud-api/mvnw.cmd b/source-code/yape-anti-fraud-api/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/source-code/yape-anti-fraud-api/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/source-code/yape-anti-fraud-api/pom.xml b/source-code/yape-anti-fraud-api/pom.xml new file mode 100644 index 0000000000..df77db1fe2 --- /dev/null +++ b/source-code/yape-anti-fraud-api/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.8 + + + com.yape.antifraud + yape-anti-fraud-api + 0.0.1-SNAPSHOT + yape-anti-fraud-api + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.kafka + spring-kafka + + + org.springframework.boot + spring-boot-starter-actuator + + + com.microsoft.sqlserver + mssql-jdbc + 12.8.1.jre11 + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/YapeAntiFraudApiApplication.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/YapeAntiFraudApiApplication.java new file mode 100644 index 0000000000..65f8eda4a1 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/YapeAntiFraudApiApplication.java @@ -0,0 +1,13 @@ +package com.yape.antifraud; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class YapeAntiFraudApiApplication { + + public static void main(String[] args) { + SpringApplication.run(YapeAntiFraudApiApplication.class, args); + } + +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/config/KafkaConfig.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/config/KafkaConfig.java new file mode 100644 index 0000000000..c99f572faf --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/config/KafkaConfig.java @@ -0,0 +1,54 @@ +package com.yape.antifraud.config; + +import com.yape.antifraud.dto.TransactionCreatedEvent; +import org.apache.kafka.common.TopicPartition; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.listener.CommonErrorHandler; +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.listener.DeadLetterPublishingRecoverer; +import org.springframework.kafka.listener.DefaultErrorHandler; +import org.springframework.util.backoff.FixedBackOff; + +@Configuration +@EnableKafka +public class KafkaConfig { + + @Bean + public ConcurrentKafkaListenerContainerFactory transactionCreatedListenerFactory( + ConsumerFactory consumerFactory, + CommonErrorHandler commonErrorHandler, + @Value("${app.kafka.listener.concurrency:3}") int concurrency + ) { + ConcurrentKafkaListenerContainerFactory factory = + new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory); + factory.setConcurrency(concurrency); + factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL); + factory.setCommonErrorHandler(commonErrorHandler); + return factory; + } + + @Bean + public CommonErrorHandler commonErrorHandler( + KafkaTemplate kafkaTemplate, + @Value("${app.retry.backoff-ms}") long backoffMs, + @Value("${app.retry.max-attempts}") long maxAttempts, + @Value("${app.topics.transaction-created-dlt}") String dltTransactionTopic + ) { + var recoverer = new DeadLetterPublishingRecoverer( + kafkaTemplate, + (record, ex) -> new TopicPartition(dltTransactionTopic, record.partition()) + ); + + DefaultErrorHandler handler = + new DefaultErrorHandler(recoverer, new FixedBackOff(backoffMs, maxAttempts - 1)); + handler.setAckAfterHandle(true); + return handler; + } +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/domain/TransactionStatus.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/domain/TransactionStatus.java new file mode 100644 index 0000000000..3b57b725f3 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/domain/TransactionStatus.java @@ -0,0 +1,5 @@ +package com.yape.antifraud.domain; + +public enum TransactionStatus { + PENDING, APPROVED, REJECTED +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/dto/TransactionCreatedEvent.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/dto/TransactionCreatedEvent.java new file mode 100644 index 0000000000..8c9ee742ae --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/dto/TransactionCreatedEvent.java @@ -0,0 +1,14 @@ +package com.yape.antifraud.dto; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +public record TransactionCreatedEvent( + UUID transactionExternalId, + String accountExternalIdDebit, + String accountExternalIdCredit, + Integer transferTypeId, + BigDecimal value, + Instant createdAt +) {} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/dto/TransactionValidatedEvent.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/dto/TransactionValidatedEvent.java new file mode 100644 index 0000000000..413f7360b1 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/dto/TransactionValidatedEvent.java @@ -0,0 +1,11 @@ +package com.yape.antifraud.dto; + +import java.time.Instant; +import java.util.UUID; + +public record TransactionValidatedEvent( + UUID transactionExternalId, + String status, + String reason, + Instant validatedAt +) {} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/entity/TransactionEntity.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/entity/TransactionEntity.java new file mode 100644 index 0000000000..b5c5f922b7 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/entity/TransactionEntity.java @@ -0,0 +1,44 @@ +package com.yape.antifraud.entity; + +import com.yape.antifraud.domain.TransactionStatus; +import jakarta.persistence.*; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "transactions", schema = "dbo") +@Data +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, length = 36) + private String accountExternalIdDebit; + + @Column(name = "account_external_id_credit", nullable = false, length = 36) + private String accountExternalIdCredit; + + @Column(name = "transaction_type_id", nullable = false) + private Integer transactionTypeId; + + @Enumerated(EnumType.STRING) + @Column(name = "transaction_status", nullable = false, length = 20) + private TransactionStatus transactionStatus; + + @Column(name = "value", nullable = false, precision = 18, scale = 2) + private BigDecimal value; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + @Column(name = "updated_at") + private Instant updatedAt; +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/repository/TransactionRepository.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/repository/TransactionRepository.java new file mode 100644 index 0000000000..02cf059fa0 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/repository/TransactionRepository.java @@ -0,0 +1,12 @@ +package com.yape.antifraud.repository; + +import com.yape.antifraud.entity.TransactionEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; +import java.util.UUID; + +public interface TransactionRepository extends JpaRepository { + + Optional findByTransactionExternalId(UUID transactionExternalId); +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionCreatedListener.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionCreatedListener.java new file mode 100644 index 0000000000..ae50900586 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionCreatedListener.java @@ -0,0 +1,77 @@ +package com.yape.antifraud.service; + +import com.yape.antifraud.domain.TransactionStatus; +import com.yape.antifraud.dto.TransactionCreatedEvent; +import com.yape.antifraud.dto.TransactionValidatedEvent; +import com.yape.antifraud.entity.TransactionEntity; +import lombok.extern.log4j.Log4j2; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.time.Instant; + +import static com.yape.antifraud.util.Constant.ERROR_INVALID_PAYLOAD; +import static com.yape.antifraud.util.Constant.REASON_EXCEEDS_THRESHOLD; +import static com.yape.antifraud.util.Constant.MESSAGE_EVENT_ALREADY_PRECESSED; +import static com.yape.antifraud.util.Constant.REASON_UNDER_THRESHOLD; + +@Log4j2 +@Service +public class TransactionCreatedListener { + + private final TransactionPersistence transactionPersistence; + private final TransactionValidatedEventPublisher transactionValidatedEventPublisher; + private final BigDecimal threshold; + + public TransactionCreatedListener( + TransactionPersistence transactionPersistence, + TransactionValidatedEventPublisher transactionValidatedEventPublisher, + @Value("${app.validation.threshold}") BigDecimal threshold + ) { + this.transactionPersistence = transactionPersistence; + this.transactionValidatedEventPublisher = transactionValidatedEventPublisher; + this.threshold = threshold; + } + + @KafkaListener( + topics = "${app.topics.transaction-created}", + containerFactory = "transactionCreatedListenerFactory" + ) + public void onMessage(ConsumerRecord transactionCreatedRecord, + Acknowledgment ack) throws Exception { + TransactionCreatedEvent transactionCreatedEvent = transactionCreatedRecord.value(); + if (transactionCreatedEvent == null || transactionCreatedEvent.transactionExternalId() == null + || transactionCreatedEvent.value() == null) { + throw new IllegalArgumentException(ERROR_INVALID_PAYLOAD); + } + log.info("Trying publish event with key: {}", transactionCreatedEvent.transactionExternalId()); + + TransactionEntity existingTransaction = transactionPersistence + .findByTransactionExternalId(transactionCreatedEvent.transactionExternalId()); + + if (existingTransaction != null && + !existingTransaction.getTransactionStatus().name().equals(TransactionStatus.PENDING.name())) { + log.info(MESSAGE_EVENT_ALREADY_PRECESSED, transactionCreatedEvent.transactionExternalId()); + ack.acknowledge(); + return; + } + + boolean approved = transactionCreatedEvent.value().compareTo(threshold) <= 0; + String status = approved ? TransactionStatus.APPROVED.name() : TransactionStatus.REJECTED.name(); + String reason = approved ? REASON_UNDER_THRESHOLD : REASON_EXCEEDS_THRESHOLD; + + TransactionValidatedEvent transactionValidatedEvent = new TransactionValidatedEvent( + transactionCreatedEvent.transactionExternalId(), + status, + reason, + Instant.now() + ); + + transactionValidatedEventPublisher.createTransactionValidatedEvent(transactionValidatedEvent); + ack.acknowledge(); + } +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionPersistence.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionPersistence.java new file mode 100644 index 0000000000..d53514d6d4 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionPersistence.java @@ -0,0 +1,11 @@ +package com.yape.antifraud.service; + + +import com.yape.antifraud.entity.TransactionEntity; + +import java.util.UUID; + +public interface TransactionPersistence { + + TransactionEntity findByTransactionExternalId(UUID transactionExternalId); +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionValidatedEventPublisher.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionValidatedEventPublisher.java new file mode 100644 index 0000000000..9aa8383a8d --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/TransactionValidatedEventPublisher.java @@ -0,0 +1,9 @@ +package com.yape.antifraud.service; + +import com.yape.antifraud.dto.TransactionValidatedEvent; + +public interface TransactionValidatedEventPublisher { + + void createTransactionValidatedEvent(TransactionValidatedEvent transactionValidatedEvent) + throws Exception; +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/impl/TransactionPersistenceImpl.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/impl/TransactionPersistenceImpl.java new file mode 100644 index 0000000000..8c8d2c4e51 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/impl/TransactionPersistenceImpl.java @@ -0,0 +1,24 @@ +package com.yape.antifraud.service.impl; + +import com.yape.antifraud.entity.TransactionEntity; +import com.yape.antifraud.repository.TransactionRepository; +import com.yape.antifraud.service.TransactionPersistence; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +public class TransactionPersistenceImpl implements TransactionPersistence { + + private final TransactionRepository transactionRepository; + + public TransactionPersistenceImpl(TransactionRepository transactionRepository) { + this.transactionRepository = transactionRepository; + } + + @Override + public TransactionEntity findByTransactionExternalId(UUID transactionExternalId) { + return transactionRepository.findByTransactionExternalId(transactionExternalId) + .orElse(null); + } +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/impl/TransactionValidatedEventPublisherImpl.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/impl/TransactionValidatedEventPublisherImpl.java new file mode 100644 index 0000000000..fe0bc68a89 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/service/impl/TransactionValidatedEventPublisherImpl.java @@ -0,0 +1,29 @@ +package com.yape.antifraud.service.impl; + +import com.yape.antifraud.dto.TransactionValidatedEvent; +import com.yape.antifraud.service.TransactionValidatedEventPublisher; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class TransactionValidatedEventPublisherImpl implements TransactionValidatedEventPublisher { + + private final KafkaTemplate kafkaTemplate; + private final String transactionValidatedTopic; + + public TransactionValidatedEventPublisherImpl( + KafkaTemplate kafkaTemplate, + @Value("${app.topics.transaction-validated}") String transactionValidatedTopic + ) { + this.kafkaTemplate = kafkaTemplate; + this.transactionValidatedTopic = transactionValidatedTopic; + } + + @Override + public void createTransactionValidatedEvent(TransactionValidatedEvent transactionValidatedEvent) + throws Exception { + String key = transactionValidatedEvent.transactionExternalId().toString(); + kafkaTemplate.send(transactionValidatedTopic, key, transactionValidatedEvent).get(); + } +} diff --git a/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/util/Constant.java b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/util/Constant.java new file mode 100644 index 0000000000..7d3423e9f9 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/java/com/yape/antifraud/util/Constant.java @@ -0,0 +1,14 @@ +package com.yape.antifraud.util; + +public class Constant { + + public static final String ERROR_INVALID_PAYLOAD = "Invalid payload TransactionCreatedEvent"; + + public static final String REASON_UNDER_THRESHOLD = "Amount under threshold"; + + public static final String REASON_EXCEEDS_THRESHOLD = "Amount exceeds threshold"; + + public static final String MESSAGE_EVENT_ALREADY_PRECESSED = + "Transaction with external id {} has already been processed. Skipping validation."; + +} diff --git a/source-code/yape-anti-fraud-api/src/main/resources/application.yaml b/source-code/yape-anti-fraud-api/src/main/resources/application.yaml new file mode 100644 index 0000000000..56249567a8 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/main/resources/application.yaml @@ -0,0 +1,66 @@ +server: + port: 8080 + +spring: + application: + name: yape-anti-fraud-api + + threads: + virtual: + enabled: true + + datasource: + url: jdbc:sqlserver://localhost:1435;databaseName=YAPE;encrypt=true;trustServerCertificate=true + username: sa + password: Yape2025. + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + + jpa: + hibernate: + ddl-auto: none + properties: + hibernate: + dialect: org.hibernate.dialect.SQLServerDialect + + kafka: + bootstrap-servers: localhost:9092 + + consumer: + group-id: yape-anti-fraud-group + auto-offset-reset: earliest + enable-auto-commit: false + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer + properties: + spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer + spring.json.value.default.type: com.yape.antifraud.dto.TransactionCreatedEvent + spring.json.use.type.headers: false + spring.json.trusted.packages: "com.yape.transactions.dto" + + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.springframework.kafka.support.serializer.JsonSerializer + acks: all + enable.idempotence: true + +app: + topics: + transaction-created: transaction.created + transaction-validated: transaction.validated + transaction-created-dlt: transaction.created.dlt + kafka: + listener: + concurrency: 3 + + validation: + threshold: 1000 + + retry: + max-attempts: 5 + backoff-ms: 500 + +management: + endpoints: + web: + exposure: + include: health diff --git a/source-code/yape-anti-fraud-api/src/test/java/com/yape/antifraud/YapeAntiFraudApiApplicationTests.java b/source-code/yape-anti-fraud-api/src/test/java/com/yape/antifraud/YapeAntiFraudApiApplicationTests.java new file mode 100644 index 0000000000..dc96d077c1 --- /dev/null +++ b/source-code/yape-anti-fraud-api/src/test/java/com/yape/antifraud/YapeAntiFraudApiApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.antifraud; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class YapeAntiFraudApiApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/source-code/yape-transactions-api/.mvn/wrapper/maven-wrapper.properties b/source-code/yape-transactions-api/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..c0bcafe984 --- /dev/null +++ b/source-code/yape-transactions-api/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/source-code/yape-transactions-api/HELP.md b/source-code/yape-transactions-api/HELP.md new file mode 100644 index 0000000000..73a5239ccb --- /dev/null +++ b/source-code/yape-transactions-api/HELP.md @@ -0,0 +1,29 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.5.8/maven-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.8/maven-plugin/build-image.html) +* [Spring Web](https://docs.spring.io/spring-boot/3.5.8/reference/web/servlet.html) +* [Spring Data JPA](https://docs.spring.io/spring-boot/3.5.8/reference/data/sql.html#data.sql.jpa-and-spring-data) +* [Spring for Apache Kafka](https://docs.spring.io/spring-boot/3.5.8/reference/messaging/kafka.html) +* [Validation](https://docs.spring.io/spring-boot/3.5.8/reference/io/validation.html) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) +* [Validation](https://spring.io/guides/gs/validating-form-input/) + +### Maven Parent overrides + +Due to Maven's design, elements are inherited from the parent POM to the project POM. +While most of the inheritance is fine, it also inherits unwanted elements like `` and `` from the parent. +To prevent this, the project POM contains empty overrides for these elements. +If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides. + diff --git a/source-code/yape-transactions-api/mvnw b/source-code/yape-transactions-api/mvnw new file mode 100644 index 0000000000..bd8896bf22 --- /dev/null +++ b/source-code/yape-transactions-api/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/source-code/yape-transactions-api/mvnw.cmd b/source-code/yape-transactions-api/mvnw.cmd new file mode 100644 index 0000000000..92450f9327 --- /dev/null +++ b/source-code/yape-transactions-api/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/source-code/yape-transactions-api/pom.xml b/source-code/yape-transactions-api/pom.xml new file mode 100644 index 0000000000..66776c63ce --- /dev/null +++ b/source-code/yape-transactions-api/pom.xml @@ -0,0 +1,111 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.8 + + + com.yape.transactions + yape-transactions-api + 0.0.1-SNAPSHOT + yape-transactions-api + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.kafka + spring-kafka + + + org.springframework.boot + spring-boot-starter-actuator + + + com.microsoft.sqlserver + mssql-jdbc + 12.8.1.jre11 + + + com.fasterxml.jackson.core + jackson-databind + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/YapeTransactionsApiApplication.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/YapeTransactionsApiApplication.java new file mode 100644 index 0000000000..6e0bd0bfc1 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/YapeTransactionsApiApplication.java @@ -0,0 +1,13 @@ +package com.yape.transactions; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class YapeTransactionsApiApplication { + + public static void main(String[] args) { + SpringApplication.run(YapeTransactionsApiApplication.class, args); + } + +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/builder/TransactionBuilder.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/builder/TransactionBuilder.java new file mode 100644 index 0000000000..3d3fb22f3c --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/builder/TransactionBuilder.java @@ -0,0 +1,52 @@ +package com.yape.transactions.builder; + +import com.yape.transactions.domain.TransactionStatus; +import com.yape.transactions.dto.CreateTransactionRequest; +import com.yape.transactions.dto.TransactionCreatedEvent; +import com.yape.transactions.dto.TransactionResponse; +import com.yape.transactions.entity.TransactionEntity; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.util.UUID; + +@Component +public class TransactionBuilder { + + public TransactionEntity transactionEntityBuilder(CreateTransactionRequest createTransactionRequest) { + Instant now = Instant.now(); + UUID transactionExternalId = UUID.randomUUID(); + + TransactionEntity transactionEntity = new TransactionEntity(); + transactionEntity.setTransactionExternalId(transactionExternalId); + transactionEntity.setAccountExternalIdDebit(createTransactionRequest.accountExternalIdDebit()); + transactionEntity.setAccountExternalIdCredit(createTransactionRequest.accountExternalIdCredit()); + transactionEntity.setTransactionTypeId(createTransactionRequest.tranferTypeId()); + transactionEntity.setTransactionStatus(TransactionStatus.PENDING); + transactionEntity.setValue(createTransactionRequest.value()); + transactionEntity.setCreatedAt(now); + return transactionEntity; + } + + public TransactionCreatedEvent transactionCreatedEventBuilder( + TransactionEntity transactionEntity, CreateTransactionRequest createTransactionRequest) { + return new TransactionCreatedEvent( + transactionEntity.getTransactionExternalId(), + createTransactionRequest.accountExternalIdDebit(), + createTransactionRequest.accountExternalIdCredit(), + createTransactionRequest.tranferTypeId(), + createTransactionRequest.value(), + transactionEntity.getCreatedAt() + ); + } + + public TransactionResponse transactionResponseBuilder( + TransactionEntity transactionEntity) { + return new TransactionResponse( + transactionEntity.getTransactionExternalId(), + new TransactionResponse.TransactionStatusDto(transactionEntity.getTransactionStatus().name()), + transactionEntity.getValue(), + transactionEntity.getCreatedAt() + ); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/config/KafkaConfig.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/config/KafkaConfig.java new file mode 100644 index 0000000000..e07f5c0101 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/config/KafkaConfig.java @@ -0,0 +1,54 @@ +package com.yape.transactions.config; + +import com.yape.transactions.dto.TransactionValidatedEvent; +import org.apache.kafka.common.TopicPartition; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.listener.CommonErrorHandler; +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.listener.DeadLetterPublishingRecoverer; +import org.springframework.kafka.listener.DefaultErrorHandler; +import org.springframework.util.backoff.FixedBackOff; + +@Configuration +@EnableKafka +public class KafkaConfig { + + @Bean + public ConcurrentKafkaListenerContainerFactory transactionValidatedListenerFactory( + ConsumerFactory consumerFactory, + CommonErrorHandler commonErrorHandler, + @Value("${app.kafka.listener.concurrency:3}") int concurrency + ) { + ConcurrentKafkaListenerContainerFactory factory = + new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory); + factory.setConcurrency(concurrency); + factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL); + factory.setCommonErrorHandler(commonErrorHandler); + return factory; + } + + @Bean + public CommonErrorHandler commonErrorHandler( + KafkaTemplate kafkaTemplate, + @Value("${app.retry.backoff-ms}") long backoffMs, + @Value("${app.retry.max-attempts}") long maxAttempts, + @Value("${app.topics.transaction-validated-dlt}") String dltTransactionValidatedTopic + ) { + var recoverer = new DeadLetterPublishingRecoverer( + kafkaTemplate, + (record, ex) -> new TopicPartition(dltTransactionValidatedTopic, record.partition()) + ); + + DefaultErrorHandler handler = + new DefaultErrorHandler(recoverer, new FixedBackOff(backoffMs, maxAttempts - 1)); + handler.setAckAfterHandle(true); + return handler; + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/controller/TransactionController.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/controller/TransactionController.java new file mode 100644 index 0000000000..1a15751873 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/controller/TransactionController.java @@ -0,0 +1,36 @@ +package com.yape.transactions.controller; + +import com.yape.transactions.dto.CreateTransactionRequest; +import com.yape.transactions.dto.TransactionResponse; +import com.yape.transactions.service.TransactionService; +import jakarta.validation.Valid; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.UUID; + +@RestController +@RequestMapping("/v1/transactions") +public class TransactionController { + + private final TransactionService transactionService; + + public TransactionController(TransactionService transactionService) { + this.transactionService = transactionService; + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public TransactionResponse createTransactionEvent( + @Valid @RequestBody CreateTransactionRequest createTransactionRequest) { + return transactionService.createTransactionEvent(createTransactionRequest); + } + + @GetMapping(value = "/{transactionExternalId}", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseStatus(HttpStatus.OK) + public TransactionResponse readTransaction( + @PathVariable UUID transactionExternalId) { + return transactionService.readTransaction(transactionExternalId); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/domain/TransactionStatus.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/domain/TransactionStatus.java new file mode 100644 index 0000000000..ea9490672e --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/domain/TransactionStatus.java @@ -0,0 +1,5 @@ +package com.yape.transactions.domain; + +public enum TransactionStatus { + PENDING, APPROVED, REJECTED +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/CreateTransactionRequest.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/CreateTransactionRequest.java new file mode 100644 index 0000000000..341363b3a7 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/CreateTransactionRequest.java @@ -0,0 +1,14 @@ +package com.yape.transactions.dto; + +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.math.BigDecimal; + +public record CreateTransactionRequest( + @NotBlank String accountExternalIdDebit, + @NotBlank String accountExternalIdCredit, + @NotNull Integer tranferTypeId, + @NotNull @DecimalMin("0.01") BigDecimal value +) {} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionCreatedEvent.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionCreatedEvent.java new file mode 100644 index 0000000000..93da223058 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionCreatedEvent.java @@ -0,0 +1,14 @@ +package com.yape.transactions.dto; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +public record TransactionCreatedEvent( + UUID transactionExternalId, + String accountExternalIdDebit, + String accountExternalIdCredit, + Integer transferTypeId, + BigDecimal value, + Instant createdAt +) {} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionResponse.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionResponse.java new file mode 100644 index 0000000000..de7e04fa1f --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionResponse.java @@ -0,0 +1,14 @@ +package com.yape.transactions.dto; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +public record TransactionResponse( + UUID transactionExternalId, + TransactionStatusDto transactionStatus, + BigDecimal value, + Instant createdAt +) { + public record TransactionStatusDto(String name) {} +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionValidatedEvent.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionValidatedEvent.java new file mode 100644 index 0000000000..99b47addd2 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/dto/TransactionValidatedEvent.java @@ -0,0 +1,11 @@ +package com.yape.transactions.dto; + +import java.time.Instant; +import java.util.UUID; + +public record TransactionValidatedEvent( + UUID transactionExternalId, + String status, + String reason, + Instant validatedAt +) {} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/entity/TransactionEntity.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/entity/TransactionEntity.java new file mode 100644 index 0000000000..56f7f5972d --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/entity/TransactionEntity.java @@ -0,0 +1,51 @@ +package com.yape.transactions.entity; + +import com.yape.transactions.domain.TransactionStatus; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Enumerated; +import jakarta.persistence.EnumType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "transactions", schema = "dbo") +@Data +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, length = 36) + private String accountExternalIdDebit; + + @Column(name = "account_external_id_credit", nullable = false, length = 36) + private String accountExternalIdCredit; + + @Column(name = "transaction_type_id", nullable = false) + private Integer transactionTypeId; + + @Enumerated(EnumType.STRING) + @Column(name = "transaction_status", nullable = false, length = 20) + private TransactionStatus transactionStatus; + + @Column(name = "value", nullable = false, precision = 18, scale = 2) + private BigDecimal value; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + @Column(name = "updated_at") + private Instant updatedAt; +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/exception/GlobalExceptionHandler.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000000..f462cd0ee2 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/exception/GlobalExceptionHandler.java @@ -0,0 +1,33 @@ +package com.yape.transactions.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import java.util.Map; + +@ControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(TransactionException.class) + public ResponseEntity> handleTransaction(TransactionException ex){ + return ResponseEntity.status(ex.getStatus()).body(Map.of("mensaje", ex.getMessage())); + } + + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidation(MethodArgumentNotValidException ex){ + String msg = ex.getBindingResult().getFieldErrors().stream() + .map(err -> err.getField()+": "+err.getDefaultMessage()) + .findFirst().orElse("Solicitud inválida"); + return ResponseEntity.badRequest().body(Map.of("mensaje", msg)); + } + + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGeneric(Exception ex){ + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(Map.of("mensaje", "Error no controlado")); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/exception/TransactionException.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/exception/TransactionException.java new file mode 100644 index 0000000000..1c0e56d1a1 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/exception/TransactionException.java @@ -0,0 +1,17 @@ +package com.yape.transactions.exception; + +import org.springframework.http.HttpStatus; + +public class TransactionException extends RuntimeException { + + private final HttpStatus status; + + public TransactionException(HttpStatus status, String message) { + super(message); + this.status = status; + } + + public HttpStatus getStatus() { + return status; + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/repository/TransactionRepository.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/repository/TransactionRepository.java new file mode 100644 index 0000000000..5817879bd5 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/repository/TransactionRepository.java @@ -0,0 +1,12 @@ +package com.yape.transactions.repository; + +import com.yape.transactions.entity.TransactionEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; +import java.util.UUID; + +public interface TransactionRepository extends JpaRepository { + + Optional findByTransactionExternalId(UUID transactionExternalId); +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionEventPublisher.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionEventPublisher.java new file mode 100644 index 0000000000..8eada23906 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionEventPublisher.java @@ -0,0 +1,11 @@ +package com.yape.transactions.service; + +import com.yape.transactions.dto.TransactionCreatedEvent; + +import java.util.concurrent.ExecutionException; + +public interface TransactionEventPublisher { + + void createTransactionEvent(TransactionCreatedEvent transactionCreatedEvent) + throws ExecutionException, InterruptedException; +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionPersistence.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionPersistence.java new file mode 100644 index 0000000000..7824ddc771 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionPersistence.java @@ -0,0 +1,14 @@ +package com.yape.transactions.service; + +import com.yape.transactions.entity.TransactionEntity; + +import java.util.UUID; + +public interface TransactionPersistence { + + TransactionEntity saveTransaction(TransactionEntity transactionEntity); + + TransactionEntity findByTransactionExternalId(UUID transactionExternalId); + + TransactionEntity updateTransactionStatus(TransactionEntity transactionEntity, String status); +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionService.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionService.java new file mode 100644 index 0000000000..d0faa4850e --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionService.java @@ -0,0 +1,13 @@ +package com.yape.transactions.service; + +import com.yape.transactions.dto.CreateTransactionRequest; +import com.yape.transactions.dto.TransactionResponse; + +import java.util.UUID; + +public interface TransactionService { + + TransactionResponse createTransactionEvent(CreateTransactionRequest createTransactionRequest); + + TransactionResponse readTransaction(UUID transactionExternalId); +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionValidatedListener.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionValidatedListener.java new file mode 100644 index 0000000000..0ac58c7477 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/TransactionValidatedListener.java @@ -0,0 +1,59 @@ +package com.yape.transactions.service; + +import com.yape.transactions.domain.TransactionStatus; +import com.yape.transactions.dto.TransactionValidatedEvent; +import com.yape.transactions.entity.TransactionEntity; +import lombok.extern.log4j.Log4j2; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.stereotype.Service; + +import static com.yape.transactions.util.Constant.ERROR_INVALID_PAYLOAD; +import static com.yape.transactions.util.Constant.MESSAGE_EVENT_ALREADY_PRECESSED; +import static com.yape.transactions.util.Constant.MESSAGE_NOT_EXIST_TRANSACTION; + +@Log4j2 +@Service +public class TransactionValidatedListener { + + private final TransactionPersistence transactionPersistence; + + public TransactionValidatedListener( + TransactionPersistence transactionPersistence + ) { + this.transactionPersistence = transactionPersistence; + } + + @KafkaListener( + topics = "${app.topics.transaction-validated}", + containerFactory = "transactionValidatedListenerFactory" + ) + public void onMessage(ConsumerRecord transactionValidatedRecord, + Acknowledgment ack) throws Exception { + TransactionValidatedEvent transactionValidatedEvent = transactionValidatedRecord.value(); + if (transactionValidatedEvent == null || transactionValidatedEvent.transactionExternalId() == null + || transactionValidatedEvent.status() == null) { + throw new IllegalArgumentException(ERROR_INVALID_PAYLOAD); + } + log.info("Trying update transaction with key: {}", transactionValidatedEvent.transactionExternalId()); + + TransactionEntity existingTransaction = transactionPersistence + .findByTransactionExternalId(transactionValidatedEvent.transactionExternalId()); + + if (existingTransaction == null) { + log.info(MESSAGE_NOT_EXIST_TRANSACTION, transactionValidatedEvent.transactionExternalId()); + ack.acknowledge(); + return; + } + if (existingTransaction != null && + !existingTransaction.getTransactionStatus().name().equals(TransactionStatus.PENDING.name())) { + log.info(MESSAGE_EVENT_ALREADY_PRECESSED, transactionValidatedEvent.transactionExternalId()); + ack.acknowledge(); + return; + } + + transactionPersistence.updateTransactionStatus(existingTransaction,transactionValidatedEvent.status()); + ack.acknowledge(); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionEventPublisherImpl.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionEventPublisherImpl.java new file mode 100644 index 0000000000..b213809400 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionEventPublisherImpl.java @@ -0,0 +1,30 @@ +package com.yape.transactions.service.impl; + +import com.yape.transactions.dto.TransactionCreatedEvent; +import com.yape.transactions.service.TransactionEventPublisher; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +import java.util.concurrent.ExecutionException; + +@Component +public class TransactionEventPublisherImpl implements TransactionEventPublisher { + + private final KafkaTemplate kafkaTemplate; + private final String transactionTopic; + + public TransactionEventPublisherImpl( + KafkaTemplate kafkaTemplate, + @Value("${app.topics.transaction-created}") String transactionTopic) { + this.kafkaTemplate = kafkaTemplate; + this.transactionTopic = transactionTopic; + } + + @Override + public void createTransactionEvent(TransactionCreatedEvent transactionCreatedEvent) + throws ExecutionException, InterruptedException { + String key = transactionCreatedEvent.transactionExternalId().toString(); + kafkaTemplate.send(transactionTopic, key, transactionCreatedEvent).get(); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionPersistenceImpl.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionPersistenceImpl.java new file mode 100644 index 0000000000..41b1db0809 --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionPersistenceImpl.java @@ -0,0 +1,36 @@ +package com.yape.transactions.service.impl; + +import com.yape.transactions.domain.TransactionStatus; +import com.yape.transactions.entity.TransactionEntity; +import com.yape.transactions.repository.TransactionRepository; +import com.yape.transactions.service.TransactionPersistence; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +public class TransactionPersistenceImpl implements TransactionPersistence { + + private final TransactionRepository transactionRepository; + + public TransactionPersistenceImpl(TransactionRepository transactionRepository) { + this.transactionRepository = transactionRepository; + } + + @Override + public TransactionEntity saveTransaction(TransactionEntity transactionEntity) { + return transactionRepository.save(transactionEntity); + } + + @Override + public TransactionEntity findByTransactionExternalId(UUID transactionExternalId) { + return transactionRepository.findByTransactionExternalId(transactionExternalId) + .orElse(null); + } + + @Override + public TransactionEntity updateTransactionStatus(TransactionEntity transactionEntity, String status) { + transactionEntity.setTransactionStatus(TransactionStatus.valueOf(status)); + return transactionRepository.save(transactionEntity); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionServiceImpl.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionServiceImpl.java new file mode 100644 index 0000000000..7c722fd22b --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/service/impl/TransactionServiceImpl.java @@ -0,0 +1,68 @@ +package com.yape.transactions.service.impl; + +import com.yape.transactions.builder.TransactionBuilder; +import com.yape.transactions.dto.CreateTransactionRequest; +import com.yape.transactions.dto.TransactionResponse; +import com.yape.transactions.entity.TransactionEntity; +import com.yape.transactions.exception.TransactionException; +import com.yape.transactions.service.TransactionEventPublisher; +import com.yape.transactions.service.TransactionPersistence; +import com.yape.transactions.service.TransactionService; +import lombok.extern.log4j.Log4j2; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +@Log4j2 +@Service +public class TransactionServiceImpl implements TransactionService { + + private final TransactionBuilder transactionBuilder; + private final TransactionPersistence transactionPersistence; + private final TransactionEventPublisher transactionEventPublisher; + + public TransactionServiceImpl( + TransactionBuilder transactionBuilder, + TransactionPersistence transactionPersistence, + TransactionEventPublisher transactionEventPublisher) { + this.transactionBuilder = transactionBuilder; + this.transactionPersistence = transactionPersistence; + this.transactionEventPublisher = transactionEventPublisher; + } + + @Override + public TransactionResponse createTransactionEvent( + CreateTransactionRequest createTransactionRequest) { + try { + TransactionEntity transactionEntity = transactionPersistence.saveTransaction( + transactionBuilder.transactionEntityBuilder(createTransactionRequest)); + + transactionEventPublisher.createTransactionEvent( + transactionBuilder.transactionCreatedEventBuilder(transactionEntity, createTransactionRequest)); + + return transactionBuilder.transactionResponseBuilder(transactionEntity); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + log.error(ex.getMessage()); + throw new TransactionException(HttpStatus.SERVICE_UNAVAILABLE, "Transaction service was interrupted"); + } catch (ExecutionException ex) { + log.error(ex.getMessage()); + throw new TransactionException(HttpStatus.SERVICE_UNAVAILABLE, "Transaction service is unavailable"); + } catch (Exception ex) { + log.error(ex.getMessage()); + throw ex; + } + } + + @Override + public TransactionResponse readTransaction(UUID transactionExternalId) { + TransactionEntity transactionEntity = + transactionPersistence.findByTransactionExternalId(transactionExternalId); + if (transactionEntity == null) { + throw new TransactionException(HttpStatus.NOT_FOUND, "Transaction not found" ); + } + return transactionBuilder.transactionResponseBuilder(transactionEntity); + } +} diff --git a/source-code/yape-transactions-api/src/main/java/com/yape/transactions/util/Constant.java b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/util/Constant.java new file mode 100644 index 0000000000..9184761eee --- /dev/null +++ b/source-code/yape-transactions-api/src/main/java/com/yape/transactions/util/Constant.java @@ -0,0 +1,12 @@ +package com.yape.transactions.util; + +public class Constant { + + public static final String ERROR_INVALID_PAYLOAD = "Invalid payload TransactionValidatedEvent"; + + public static final String MESSAGE_NOT_EXIST_TRANSACTION = "Transaction with external id {} does not exist."; + + public static final String MESSAGE_EVENT_ALREADY_PRECESSED = + "Transaction with external id {} has already been processed. Skipping validation."; + +} diff --git a/source-code/yape-transactions-api/src/main/resources/application.yml b/source-code/yape-transactions-api/src/main/resources/application.yml new file mode 100644 index 0000000000..696041b47d --- /dev/null +++ b/source-code/yape-transactions-api/src/main/resources/application.yml @@ -0,0 +1,62 @@ +server: + port: 8080 + +spring: + application: + name: yape-transactions-api + threads: + virtual: + enabled: true + + datasource: + url: jdbc:sqlserver://localhost:1435;databaseName=YAPE;encrypt=true;trustServerCertificate=true + username: sa + password: Yape2025. + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + + jpa: + hibernate: + ddl-auto: none + properties: + hibernate: + dialect: org.hibernate.dialect.SQLServerDialect + + kafka: + bootstrap-servers: localhost:9092 + + consumer: + group-id: yape-transactions-group + auto-offset-reset: earliest + enable-auto-commit: false + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer + properties: + spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer + spring.json.value.default.type: com.yape.transactions.dto.TransactionValidatedEvent + spring.json.use.type.headers: false + spring.json.trusted.packages: "com.yape.antifraud.dto" + + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.springframework.kafka.support.serializer.JsonSerializer + acks: all + enable-idempotence: true + +app: + topics: + transaction-created: transaction.created + transaction-validated: transaction.validated + transaction-validated-dlt: transaction.validated.dlt + kafka: + listener: + concurrency: 3 + + retry: + max-attempts: 5 + backoff-ms: 500 + +management: + endpoints: + web: + exposure: + include: health \ No newline at end of file diff --git a/source-code/yape-transactions-api/src/test/java/com/yape/transactions/YapeTransactionsApiApplicationTests.java b/source-code/yape-transactions-api/src/test/java/com/yape/transactions/YapeTransactionsApiApplicationTests.java new file mode 100644 index 0000000000..1b67d23ece --- /dev/null +++ b/source-code/yape-transactions-api/src/test/java/com/yape/transactions/YapeTransactionsApiApplicationTests.java @@ -0,0 +1,13 @@ +package com.yape.transactions; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class YapeTransactionsApiApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/sqlserver/init/init-yape.sh b/sqlserver/init/init-yape.sh new file mode 100644 index 0000000000..812bf57b6e --- /dev/null +++ b/sqlserver/init/init-yape.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -e + +# Detectar la ruta correcta de sqlcmd +if [ -x /opt/mssql-tools18/bin/sqlcmd ]; then + SQLCMD="/opt/mssql-tools18/bin/sqlcmd" +elif [ -x /opt/mssql-tools/bin/sqlcmd ]; then + SQLCMD="/opt/mssql-tools/bin/sqlcmd" +else + echo "ERROR: sqlcmd no encontrado en /opt/mssql-tools*/bin" + exit 1 +fi + +# Arrancar SQL Server en background +/opt/mssql/bin/sqlservr & + +echo "Waiting for SQL Server to be ready..." +# Esperar hasta que responda +until $SQLCMD -C -S localhost -U sa -P "$MSSQL_SA_PASSWORD" -Q "SELECT 1" > /dev/null 2>&1 +do + sleep 1 +done + +echo "Sleep for 20 seconds to wait all in database is ready..." +sleep 20 + +echo "Running init-yape.sql..." +$SQLCMD -C -S localhost -U sa -P "$MSSQL_SA_PASSWORD" -d master -i /usr/src/init/init-yape.sql + +echo "Init script finished successfully. SQL Server continues running." +wait \ No newline at end of file diff --git a/sqlserver/init/init-yape.sql b/sqlserver/init/init-yape.sql new file mode 100644 index 0000000000..11145a7c33 --- /dev/null +++ b/sqlserver/init/init-yape.sql @@ -0,0 +1,116 @@ +------------------------------------------------------------ +-- 1. Crear BD YAPE si no existe +------------------------------------------------------------ +IF DB_ID(N'YAPE') IS NULL +BEGIN + PRINT 'Creating database YAPE...'; + CREATE DATABASE [YAPE]; +END +ELSE +BEGIN + PRINT 'Database YAPE already exists.'; +END +GO + +------------------------------------------------------------ +-- 2. Esperar a que la BD YAPE esté ONLINE +------------------------------------------------------------ +PRINT 'Ensuring database YAPE is ONLINE...'; + +-- Esperar a que aparezca en sys.databases +WHILE DB_ID(N'YAPE') IS NULL +BEGIN + PRINT 'Database YAPE not created yet. Waiting 1 second...'; + WAITFOR DELAY '00:00:01'; +END + +-- Esperar a que su estado sea ONLINE +WHILE EXISTS ( + SELECT 1 + FROM sys.databases + WHERE name = N'YAPE' + AND state_desc <> 'ONLINE' -- state_desc = ONLINE, RESTORING, RECOVERING, etc. +) +BEGIN + PRINT 'Database YAPE is not ONLINE yet. Waiting 1 second...'; + WAITFOR DELAY '00:00:01'; +END + +PRINT 'Database YAPE is ONLINE.'; +GO + +------------------------------------------------------------ +-- 3. Cambiar el contexto a YAPE +------------------------------------------------------------ +USE [YAPE]; +GO + +------------------------------------------------------------ +-- 4. Crear tabla dbo.transactions si no existe +------------------------------------------------------------ +IF NOT EXISTS ( + SELECT 1 FROM YAPE.sys.tables WHERE name = N'transactions' AND schema_id = SCHEMA_ID('dbo') +) +BEGIN + PRINT 'Creating table dbo.transactions...'; + + CREATE TABLE YAPE.dbo.[transactions] ( + id BIGINT IDENTITY(1,1) NOT NULL CONSTRAINT PK_transactions PRIMARY KEY, + transaction_external_id UNIQUEIDENTIFIER NOT NULL, + account_external_id_debit VARCHAR(36) NOT NULL, + account_external_id_credit VARCHAR(36) NOT NULL, + transaction_type_id INT NOT NULL, + transaction_status VARCHAR(20) NOT NULL, + value DECIMAL(18,2) NOT NULL, + created_at DATETIME2(0) NOT NULL CONSTRAINT DF_transactions_created_at DEFAULT SYSUTCDATETIME(), + updated_at DATETIME2(0) NULL + ); + + -- UNIQUE en transaction_external_id + ALTER TABLE YAPE.dbo.[transactions] + ADD CONSTRAINT UQ_transactions_transaction_external_id + UNIQUE (transaction_external_id); + + -- CHECK para los estados válidos + ALTER TABLE YAPE.dbo.[transactions] + ADD CONSTRAINT CK_transactions_status + CHECK (transaction_status IN ('PENDING','APPROVED','REJECTED')); +END +ELSE +BEGIN + PRINT 'Table YAPE.dbo.transactions already exists.'; +END +GO + +------------------------------------------------------------ +-- 5. Trigger para updated_at en cada UPDATE +------------------------------------------------------------ +IF NOT EXISTS ( + SELECT 1 + FROM YAPE.sys.triggers + WHERE name = N'trg_transactions_set_updated_at' + AND parent_id = OBJECT_ID(N'[YAPE].dbo.[transactions]') +) +BEGIN + PRINT 'Creating trigger YAPE.dbo.trg_transactions_set_updated_at...'; + + EXEC (' + CREATE TRIGGER dbo.trg_transactions_set_updated_at + ON YAPE.dbo.[transactions] + AFTER UPDATE + AS + BEGIN + SET NOCOUNT ON; + + UPDATE t + SET updated_at = SYSUTCDATETIME() + FROM YAPE.dbo.[transactions] t + JOIN inserted i ON t.id = i.id; + END + '); +END +ELSE +BEGIN + PRINT 'Trigger YAPE.dbo.trg_transactions_set_updated_at already exists.'; +END +GO \ No newline at end of file diff --git a/yape-anti-fraud-api/Dockerfile b/yape-anti-fraud-api/Dockerfile new file mode 100644 index 0000000000..6670e873ad --- /dev/null +++ b/yape-anti-fraud-api/Dockerfile @@ -0,0 +1,12 @@ +FROM eclipse-temurin:21-jre + +WORKDIR /app + +RUN useradd -r -u 1001 appuser +USER appuser + +COPY yape-anti-fraud-api-0.0.1-SNAPSHOT.jar /app/app.jar + +EXPOSE 8080 + +ENTRYPOINT ["sh", "-c", "java -jar /app/app.jar"] diff --git a/yape-anti-fraud-api/yape-anti-fraud-api-0.0.1-SNAPSHOT.jar b/yape-anti-fraud-api/yape-anti-fraud-api-0.0.1-SNAPSHOT.jar new file mode 100644 index 0000000000..e90d1f7444 Binary files /dev/null and b/yape-anti-fraud-api/yape-anti-fraud-api-0.0.1-SNAPSHOT.jar differ diff --git a/yape-transactions-api/Dockerfile b/yape-transactions-api/Dockerfile new file mode 100644 index 0000000000..676b3e800c --- /dev/null +++ b/yape-transactions-api/Dockerfile @@ -0,0 +1,12 @@ +FROM eclipse-temurin:21-jre + +WORKDIR /app + +RUN useradd -r -u 1001 appuser +USER appuser + +COPY yape-transactions-api-0.0.1-SNAPSHOT.jar /app/app.jar + +EXPOSE 8080 + +ENTRYPOINT ["sh", "-c", "java -jar /app/app.jar"] diff --git a/yape-transactions-api/yape-transactions-api-0.0.1-SNAPSHOT.jar b/yape-transactions-api/yape-transactions-api-0.0.1-SNAPSHOT.jar new file mode 100644 index 0000000000..77ad5ebe38 Binary files /dev/null and b/yape-transactions-api/yape-transactions-api-0.0.1-SNAPSHOT.jar differ