diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..528e7a5 --- /dev/null +++ b/readme.md @@ -0,0 +1,224 @@ +# Transaction Validation System +A backend service for validating financial transactions with deterministic scoring, risk classification, and reliable event publishing. + +![Java](https://img.shields.io/badge/java-%23ED8B00.svg?style=for-the-badge&logo=openjdk&logoColor=white) ![Spring](https://img.shields.io/badge/spring-%236DB33F.svg?style=for-the-badge&logo=spring&logoColor=white) ![Postgres](https://img.shields.io/badge/postgres-%23316192.svg?style=for-the-badge&logo=postgresql&logoColor=white) ![Apache Maven](https://img.shields.io/badge/Apache%20Maven-C71A36?style=for-the-badge&logo=Apache%20Maven&logoColor=white) ![Apache Kafka](https://img.shields.io/badge/Apache%20Kafka-000?style=for-the-badge&logo=apachekafka) ![Swagger](https://img.shields.io/badge/-Swagger-%23Clojure?style=for-the-badge&logo=swagger&logoColor=white) ![Git](https://img.shields.io/badge/git-%23F05033.svg?style=for-the-badge&logo=git&logoColor=white) + +[Introduction](#introduction) | [Features](#features) | [Tech Stack](#tech-stack) | [Installation](#installation) | [Quick start](#quick-start) | [Usage](#usage) | [Known issues and limitations](#known-issues-and-limitations) | [Getting help](#getting-help) | [Contributing](#contributing) | [License](#license) + + +## Introduction +This service exposes a set of REST API endpoints, with the primary endpoint responsible for scoring financial transactions and returning a validation result that includes a risk level and a final decision. The API is stateless, uses PostgreSQL for persistence, and provides OpenAPI documentation for straightforward integration by upstream systems. + + +## Features +- Extensible rule-based scoring pipeline with initial validation rules, including amount thresholds, nighttime activity, high-risk countries, high-risk merchant categories, velocity checks, and country mismatch detection. +- Persistent storage of transactions, validation results, and outbox events for audit and history tracking. +- REST API for querying validation history with pagination and filtering. +- OpenAPI specification and Swagger UI for interactive API documentation. +- Outbox-based message publishing for validation completed events. + + +## Tech stack +- Java 25 +- Spring Boot 3.5.x + - Spring Web (Tomcat) + - Spring Data JPA (Hibernate, HikariCP) + - Jackson + - Jakarta Bean Validation +- Maven +- PostgreSQL 17.x +- Liquibase +- Kafka +- Testcontainers + + +## Installation + +### Prerequisites + +- **Option A — Container run:** Docker + Docker Compose +- **Option B — Local run:** Java 25, Maven (optional), PostgreSQL, Kafka +- **Option C — Hybrid run:** Java 25, Maven (optional), Docker + Docker Compose + +--- + +### Option A: Docker Compose (recommended) + +Runs the application together with all required infrastructure in an isolated environment, with the application, database, and message broker running in separate containers. + +```sh +docker compose up --build +``` + +### Option B: Running locally + +For this approach, PostgreSQL and Kafka must be running on the host machine, and the application connection parameters must be configured accordingly. + +After the infrastructure is ready, run the application locally: + +```sh +./mvnw spring-boot:run +``` +or, if Maven is installed globally: + +```sh +mvn spring-boot:run +``` + +### Option C: Hybrid run + +PostgreSQL and Kafka are started in containers, while the application itself runs locally and connects to the containerized infrastructure. + +Start PostgreSQL and Kafka using Docker Compose: + +```sh +docker compose up -d postgres kafka +``` + +Then run the application locally: + +```sh +./mvnw spring-boot:run +``` +or + +```sh +mvn spring-boot:run +``` + + +## Quick start + +Run the service and submit a transaction for validation: + +```sh +curl -X POST "http://localhost:3000/api/v1/transaction/validate" \ + -H "Content-Type: application/json" \ + -d '{ + "externalId": 1, + "userId": "c1c3a7c0-1c3b-4a2b-9e5a-7b3c1b2a9f11", + "merchantId": "9a1d6f88-0f93-4e58-9dd7-1c9d4a7d6c22", + "deviceId": "android-13-pixel-7", + "amount": 12000.00, + "currency": "USD", + "initialized": 1735689600, + "merchantCategory": "GROCERIES", + "channel": "WEB", + "ipAddress": "203.0.113.10", + "country": "NGA", + "cardFingerprint": "fp_9d82kdk29d" + }' +``` + +Example response: + +```json +{ + "id": 843, + "transactionId": 1021, + "score": 90, + "riskLevel": "HIGH", + "decision": "BLOCK", + "validationResults": [ + { + "code": "VERY_HIGH_AMOUNT", + "description": "The transaction is above 9999 USD", + "scoreDelta": 60 + }, + { + "code": "HIGH_RISK_COUNTRY", + "description": "The transaction was made in high-risk country NGA", + "scoreDelta": 30 + } + ], + "createdAt": "2026-12-01T11:22:33Z", + "updatedAt": "2026-12-01T11:22:33Z" +} +``` + + +## Usage + +### Base URL + +All endpoints are served under the `/api` context path. + +### API endpoints + +- `POST /api/v1/transaction/validate` - validate a transaction and return score, risk level, decision, and triggered validators. +- `GET /api/v1/validation/{id}` - fetch a validation result by id. +- `GET /api/v1/validation` - list validation results with optional filters (`userId`, `riskLevel`, `decision`, `from`, `to`, `page`, `size`). +- `GET /api/v1/utility/health/liveness` - liveness probe. +- `GET /api/v1/utility/health/readiness` - readiness probe. + +OpenAPI and Swagger UI: + +- `GET /api/v1/openapi` - raw OpenAPI spec. +- `GET /api/swagger` - Swagger UI. + +### Scoring rules + +The default pipeline applies these validators and sums their score deltas: + +- High amount: amount > 4999 adds +40. +- Very high amount: amount > 9999 adds +60. +- Nighttime: 02:00-05:00 UTC adds +15. +- High-risk country: country code is in `RiskCountry` list (ISO alpha-3) adds +30. +- High-risk merchant: category in `GAMBLING`, `CRYPTO`, or `ADULT` adds +35. +- Velocity: more than 3 validations in the last 5 minutes adds +25. +- Country mismatch: user's recent history shows current country < 50% of last 30 days adds +20. + +### Risk level mapping + +Scores are mapped to risk levels and decisions using the configured thresholds: + +- `properties.risk.threshold.low` (default 30) => `LOW` / `ALLOW` +- `properties.risk.threshold.medium` (default 70) => `MEDIUM` / `REVIEW` +- Above the medium threshold => `HIGH` / `BLOCK` + +### Configuration + +Configuration lives under `src/main/resources/application*.yaml`. Key settings include: + +- Server: port `3000`, context path `/api`. +- Database: `spring.datasource.*` (overridden by Docker Compose env vars). +- Kafka: `spring.kafka.*` and `properties.kafka.*`. +- Scoring thresholds: `properties.risk.threshold.*`. + +To run with production settings: + +```sh +SPRING_PROFILES_ACTIVE=prod \ +DB_HOST=localhost \ +DB_PORT=5432 \ +DB_USER=postgres \ +DB_PASSWORD=postgres \ +./mvnw spring-boot:run +``` + +### Kafka outbox + +Each validation writes an outbox row and the scheduled publisher ships it to Kafka (topic `transaction.validation.completed`). The consumer is optional and only logs messages when `properties.kafka.consumer.enabled=true`. + + +## Known issues and limitations + +- No load or stress testing is included. +- Authentication and authorization are not implemented. +- Some rule thresholds are currently defined in code (e.g. amount limits, velocity window, country mismatch window). +- Kafka consumer logic is intentionally minimal and intended for demonstration purposes only. + + +## Getting help + +If you encounter a bug or have a question about the project, please use the repository issue tracker or reach me out directly. + + +## Contributing + +Pull requests are welcome. For substantial changes, please open an issue first to discuss the proposed approach. + + +## License + +This project is licensed under the MIT License. See the `LICENSE` file for details. \ No newline at end of file diff --git a/src/main/java/com/neo/tx/config/Properties.java b/src/main/java/com/neo/tx/config/Properties.java index a1099e3..b97d761 100644 --- a/src/main/java/com/neo/tx/config/Properties.java +++ b/src/main/java/com/neo/tx/config/Properties.java @@ -20,6 +20,9 @@ public class Properties { @Value("${properties.risk.threshold.high}") public int riskThresholdHigh; + @Value("${properties.kafka.producer.enabled}") + public boolean kafkaProducerEnabled; + @Value("${properties.kafka.consumer.enabled}") public boolean kafkaConsumerEnabled; diff --git a/src/main/java/com/neo/tx/message_broker/Publisher.java b/src/main/java/com/neo/tx/message_broker/Publisher.java index aee65b0..64c0e6e 100644 --- a/src/main/java/com/neo/tx/message_broker/Publisher.java +++ b/src/main/java/com/neo/tx/message_broker/Publisher.java @@ -3,6 +3,7 @@ import com.neo.tx.model.OutboxEvent; import com.neo.tx.repository.EventOutboxRepository; import jakarta.transaction.Transactional; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @@ -11,6 +12,7 @@ import java.util.List; @Component +@ConditionalOnProperty(prefix = "properties.kafka.producer", name = "enabled", havingValue = "true") public class Publisher { private static final int FIXED_DELAY = 5000; diff --git a/src/main/java/com/neo/tx/model/OutboxEvent.java b/src/main/java/com/neo/tx/model/OutboxEvent.java index b86f66f..b86321b 100644 --- a/src/main/java/com/neo/tx/model/OutboxEvent.java +++ b/src/main/java/com/neo/tx/model/OutboxEvent.java @@ -19,30 +19,42 @@ public enum Status {NEW, SENT, FAILED} @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(name = "aggregate_type", nullable = false, length = 64) private String aggregateType; + @Column(name = "aggregate_id", nullable = false, length = 64) private String aggregateId; + @Column(name = "event_type", nullable = false, length = 128) private String eventType; + @Column(name = "topic", nullable = false, length = 255) private String topic; + @Column(name = "event_key", nullable = false, length = 128) private String eventKey; + @JdbcTypeCode(SqlTypes.JSON) @Column(name = "payload", columnDefinition = "jsonb", nullable = false) private String payload; + @Enumerated(EnumType.STRING) @Column(name = "status", nullable = false, length = 16) private Status status; + @Column(name = "attempts", nullable = false) private Integer attempts; + @Column(name = "last_error") private String lastError; + @Column(name = "available_at", nullable = false) private Instant availableAt; + @Column(name = "created_at", nullable = false, updatable = false) private Instant createdAt; + @Column(name = "updated_at", nullable = false) private Instant updatedAt; @@ -169,23 +181,4 @@ public Instant getUpdatedAt() { public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } - - @Override - public String toString() { - return "OutboxEvent{" + - "id=" + id + - ", aggregateType='" + aggregateType + '\'' + - ", aggregateId='" + aggregateId + '\'' + - ", eventType='" + eventType + '\'' + - ", topic='" + topic + '\'' + - ", eventKey='" + eventKey + '\'' + - ", payload='" + payload + '\'' + - ", status=" + status + - ", attempts=" + attempts + - ", lastError='" + lastError + '\'' + - ", availableAt=" + availableAt + - ", createdAt=" + createdAt + - ", updatedAt=" + updatedAt + - '}'; - } } \ No newline at end of file diff --git a/src/main/java/com/neo/tx/model/Transaction.java b/src/main/java/com/neo/tx/model/Transaction.java index 6c6f358..809f013 100644 --- a/src/main/java/com/neo/tx/model/Transaction.java +++ b/src/main/java/com/neo/tx/model/Transaction.java @@ -202,26 +202,4 @@ public Instant getUpdatedAt() { public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } - - @Override - public String toString() { - return "Transaction{" + - "id=" + id + - ", externalId=" + externalId + - ", userId=" + userId + - ", amount=" + amount + - ", currency='" + currency + '\'' + - ", initialized=" + initialized + - ", merchantCategory='" + merchantCategory + '\'' + - ", merchantId=" + merchantId + - ", channel='" + channel + '\'' + - ", ipAddress='" + ipAddress + '\'' + - ", country='" + country + '\'' + - ", deviceId='" + deviceId + '\'' + - ", cardFingerprint='" + cardFingerprint + '\'' + - ", createdAt=" + createdAt + - ", updatedAt=" + updatedAt + - ", validation=" + validation + - '}'; - } } \ No newline at end of file diff --git a/src/main/java/com/neo/tx/model/Validation.java b/src/main/java/com/neo/tx/model/Validation.java index c3c1d33..3c0defa 100644 --- a/src/main/java/com/neo/tx/model/Validation.java +++ b/src/main/java/com/neo/tx/model/Validation.java @@ -126,18 +126,4 @@ public Instant getUpdatedAt() { public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } - - @Override - public String toString() { - return "Validation{" + - "id=" + id + - ", transaction=" + transaction + - ", score=" + score + - ", riskLevel=" + riskLevel + - ", decision=" + decision + - ", triggeredValidators=" + triggeredValidators + - ", createdAt=" + createdAt + - ", updatedAt=" + updatedAt + - '}'; - } } \ No newline at end of file diff --git a/src/main/java/com/neo/tx/repository/specification/EventOutboxJpaRepository.java b/src/main/java/com/neo/tx/repository/EventOutboxJpaRepository.java similarity index 78% rename from src/main/java/com/neo/tx/repository/specification/EventOutboxJpaRepository.java rename to src/main/java/com/neo/tx/repository/EventOutboxJpaRepository.java index cc48ee4..94028db 100644 --- a/src/main/java/com/neo/tx/repository/specification/EventOutboxJpaRepository.java +++ b/src/main/java/com/neo/tx/repository/EventOutboxJpaRepository.java @@ -1,7 +1,6 @@ -package com.neo.tx.repository.specification; +package com.neo.tx.repository; import com.neo.tx.model.OutboxEvent; -import com.neo.tx.model.Validation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; diff --git a/src/main/java/com/neo/tx/repository/specification/ValidationSpecification.java b/src/main/java/com/neo/tx/repository/specification/ValidationSpecification.java index 0cadbdf..e5ee237 100644 --- a/src/main/java/com/neo/tx/repository/specification/ValidationSpecification.java +++ b/src/main/java/com/neo/tx/repository/specification/ValidationSpecification.java @@ -31,12 +31,12 @@ public static Specification decision(Decision decision) { public static Specification initializedFrom(Instant from) { return (root, query, builder) -> - builder.greaterThanOrEqualTo(root.get("transaction").get("initialized"), from.toEpochMilli()); + builder.greaterThanOrEqualTo(root.get("transaction").get("initialized"), from.getEpochSecond()); } public static Specification initializedTo(Instant to) { return (root, query, builder) -> - builder.lessThanOrEqualTo(root.get("transaction").get("initialized"), to.toEpochMilli()); + builder.lessThanOrEqualTo(root.get("transaction").get("initialized"), to.getEpochSecond()); } public static Specification buildCondition(UUID userId, RiskLevel riskLevel, Decision decision, Instant from, Instant to) { diff --git a/src/main/java/com/neo/tx/service/ValidationService.java b/src/main/java/com/neo/tx/service/ValidationService.java index 5d89495..1c9ae0d 100644 --- a/src/main/java/com/neo/tx/service/ValidationService.java +++ b/src/main/java/com/neo/tx/service/ValidationService.java @@ -47,10 +47,6 @@ public ValidationResponseDto analyzeValidationResponses(List evaluate(TransactionRequestDto transaction) { - Instant monthAgo = Instant.now().minusSeconds(30 * 24 * 60 * 60); - List transactions = transactionRepository.find(transaction.userId, monthAgo); + List transactions = transactionRepository.find(transaction.userId, Instant.now().minus(30, ChronoUnit.DAYS)); long totalTransactions = transactions.size(); long countryMatch = transactions.stream().filter((e) -> Objects.equals(e.getCountry(), transaction.country)).count(); diff --git a/src/main/java/com/neo/tx/validator/VelocityValidation.java b/src/main/java/com/neo/tx/validator/VelocityValidation.java index 93610f6..564c20d 100644 --- a/src/main/java/com/neo/tx/validator/VelocityValidation.java +++ b/src/main/java/com/neo/tx/validator/VelocityValidation.java @@ -9,6 +9,7 @@ import org.springframework.stereotype.Component; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.List; @Component @@ -28,10 +29,10 @@ public List evaluate(TransactionRequestDto transaction) { int threshold = 3; Instant now = Instant.now(); - Page pagedRecords = validationRepository.find(transaction.userId, null, null, now.minusSeconds(minutes * 60), now, 0, 100); + Page pagedRecords = validationRepository.find(transaction.userId, null, null, now.minus(minutes, ChronoUnit.MINUTES), now, 0, 100); if (pagedRecords.getContent().size() > threshold) { - return List.of(new ValidationResultDto("HIGH_VELOCITY", "Transactions under user id " + transaction.userId + "are too frequent. Threshold: " + minutes, 25)); + return List.of(new ValidationResultDto("HIGH_VELOCITY", "Transactions under user id " + transaction.userId + "are too frequent. Threshold: " + threshold, 25)); } return List.of(); diff --git a/src/main/resources/application-dev.yaml b/src/main/resources/application-dev.yaml index 2008284..7f427eb 100644 --- a/src/main/resources/application-dev.yaml +++ b/src/main/resources/application-dev.yaml @@ -30,5 +30,6 @@ properties: risk.threshold.low: 30 risk.threshold.medium: 70 risk.threshold.high: 100 + kafka.producer.enabled: true kafka.consumer.enabled: true kafka.consumer.validation.topic: transaction.validation.completed \ No newline at end of file diff --git a/src/test/java/com/neo/tx/integration/TransactionTest.java b/src/test/java/com/neo/tx/integration/TransactionTest.java index 7f456d5..0e69455 100644 --- a/src/test/java/com/neo/tx/integration/TransactionTest.java +++ b/src/test/java/com/neo/tx/integration/TransactionTest.java @@ -12,7 +12,7 @@ import com.neo.tx.repository.TransactionRepository; import com.neo.tx.repository.ValidationJpaRepository; import com.neo.tx.repository.ValidationRepository; -import com.neo.tx.repository.specification.EventOutboxJpaRepository; +import com.neo.tx.repository.EventOutboxJpaRepository; import jakarta.transaction.Transactional; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; diff --git a/src/test/resources/application-test.yaml b/src/test/resources/application-test.yaml index 190368a..25260ac 100644 --- a/src/test/resources/application-test.yaml +++ b/src/test/resources/application-test.yaml @@ -36,5 +36,6 @@ properties: risk.threshold.low: 30 risk.threshold.medium: 70 risk.threshold.high: 100 + kafka.producer.enabled: false kafka.consumer.enabled: false kafka.consumer.validation.topic: transaction.validation.completed \ No newline at end of file