Skip to content

Repository files navigation

PortalTrip API (portaltrip)

Java Spring Boot PostgreSQL Architecture Coverage Status

PortalTrip API is a REST service built with Java 26 and Spring Boot 4.1.1. It stores the Rick and Morty catalog in PostgreSQL and manages authenticated travelers, a simple credit balance, server-side quotes, activity-based portal rewards and user-owned interdimensional reservations.

Controllers call application services, which coordinate use cases and access Spring Data JPA repositories directly. Most services use an interface and a ServiceImpl; PortalActivityService coordinates the activity cycle directly. Domain records own reservation invariants and state transitions, while PortalActivityEntity validates persisted activity timing and sequence. Spring Security keeps the catalog public, issues HS256 access tokens and scopes reservations and portal activity to the authenticated user.

Open the visual system report

🔌 Frontend for this API

This API is the backend of the PortalTrip frontend. GitHub repository: https://github.com/Prgm-code/portaltrip-frontend

With both repositories downloaded there is no .env to create: the dev profile accepts the http://localhost:4321 origin and the UI targets http://localhost:8080.


🎫 Enterprise Booking System - Full-Stack Integration

Final Challenge · Java Course · Globant Talento Ready · Desafío Latam. PortalTrip is the course's full-stack capstone project: a Java/Spring Boot REST API backed by PostgreSQL and a TypeScript/Astro frontend, delivered as two repositories that connect locally with no extra configuration.

This repository is the backend microservice of the PortalTrip capstone project. The frontend lives in Prgm-code/portaltrip-frontend.

🛠️ Tech Stack

  • Backend: Java 26, Spring Boot 4.1.1, Spring Data JPA, Hibernate 7.4, Spring Security 7.1 (JWT HS256), OpenAPI/Swagger (springdoc 3.1.0).
  • Frontend: strict TypeScript 6, Astro 7.1 on Vite 8, native ESM, semantic HTML5/CSS3, Zustand 5, Tailwind CSS 4 (port 4321).
  • Infrastructure: Docker Compose, PostgreSQL 17 Alpine published on localhost:5432, multi-stage Dockerfile (Maven + Temurin 26 JRE).
  • Quality and Testing: JUnit 6, Mockito 5, JaCoCo 0.8.15 (100% instructions and branches), TDD & Clean Architecture.

Exact versions

Layer Technology Version
Backend Java (Temurin) 26
Backend Spring Boot 4.1.1
Backend Spring Security (JWT HS256, OAuth2 Resource Server) 7.1.1
Backend Spring Data JPA + Hibernate ORM 7.4.5
Backend springdoc-openapi (Swagger UI) 3.1.0
Backend Maven Wrapper 3.9.16
Backend JUnit Jupiter / Mockito / JaCoCo 6.0.3 / 5.23.0 / 0.8.15
Database PostgreSQL (Docker postgres:17-alpine) 17
Frontend Node.js / pnpm 24 / 10.34.5
Frontend Astro (on Vite 8.2) 7.1.6
Frontend TypeScript (astro/tsconfigs/strict, zero any) 6.0.3
Frontend Tailwind CSS 4.3.3
Frontend Zustand 5.0.14
Frontend Three.js 0.185.1
Frontend Biome (lint + format) 2.5.7
Infrastructure Docker Compose (compose.yml) + multi-stage Dockerfiles Compose v2

🔗 Reference Repositories


🚀 Local Setup Guide

No .env file is needed: the API dev profile ships defaults for the database, the JWT key and CORS (http://localhost:4321), and the UI points to http://localhost:8080. Requires Java 26, Docker, Node.js 24 and pnpm 10 (npm install -g pnpm).

1. Start the Relational Database

cd portaltrip
docker compose up -d postgres

PostgreSQL is now listening on localhost:5432 (rickandmorty / rick / morty) with the catalog and the reservation schema loaded automatically.

2. Run the Automated Tests

./mvnw clean test

196 tests (JUnit Jupiter 6 + Mockito) run against in-memory H2; Docker is not required for this step.

3. Start the Backend Microservice

./mvnw spring-boot:run

All-in-one alternative with Docker: docker compose up -d --build starts PostgreSQL and the API in a single command.

4. Start the Web Frontend

cd ../portaltrip-frontend
pnpm install
pnpm dev

npm also works (npm install, npm run dev). With both repositories downloaded side by side there is nothing to configure: the UI targets http://localhost:8080 and the API accepts the http://localhost:4321 origin by default.

Full cycle: create your passport from the header button (email and password), pick a destination, request a quote and confirm the reservation. The API stores it in PostgreSQL and the reservations list refreshes in the UI without reloading the page. pnpm build runs astro check, Biome and the production build with zero errors.

CORS is handled globally in SecurityConfig (CorsConfigurationSource, equivalent to @CrossOrigin) and allows http://localhost:4321 and http://localhost:5173 by default.


☁️ Deploying to Coolify (or any Docker host)

The multi-stage Dockerfile builds the WAR with Maven and runs it on Temurin 26 JRE. The healthcheck is GET /health on port 8080.

  1. Create a PostgreSQL 17 resource in Coolify (or use an external one) and run db/seed.sql followed by db/app-schema.sql against it once. The prod profile validates the schema (ddl-auto: validate) and never creates it.
  2. Create the application from this repository with Build Pack: Dockerfile, port 8080.
  3. Define the environment variables:
Variable Production value
SPRING_PROFILES_ACTIVE prod (Swagger and OpenAPI are disabled)
DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD PostgreSQL connection data
JWT_SECRET_BASE64 Required. Generate one with openssl rand -base64 32
APP_CORS_ALLOWED_ORIGINS Public frontend URL, for example https://app.mydomain.com
JWT_ISSUER, JWT_AUDIENCE, JWT_TTL, REGISTRATION_CREDIT Optional; they have defaults

Alternative (recommended, single resource): deploy compose.coolify.yml as a Docker Compose resource in Coolify. It starts the API and PostgreSQL together. The database image is built from db/Dockerfile, which copies db/seed.sql and db/app-schema.sql into the image, so the catalog and schema load the first time the pgdata volume is created even on hosts that rewrite bind mounts.

For an existing PortalTrip database, apply db/patch-portal-stipends.sql before deploying the activity-reward backend. It creates the new tables without removing users, balances or reservations. A redeploy does not rerun initialization SQL on an existing volume. See existing database upgrades.

  1. New resource → Docker Compose → this repository, branch main, Docker Compose location: compose.coolify.yml.
  2. Environment variables: JWT_SECRET_BASE64, DB_PASSWORD and APP_CORS_ALLOWED_ORIGINS=https://<your-frontend-domain>. The profile defaults to prod in this file; everything else has a default.
  3. Assign the API domain to the app service. Coolify routes it to container port 8080 through its proxy. compose.coolify.yml publishes no host ports, so it cannot fail with "port is already allocated" like the local compose.yml would.
  4. Check https://<your-api-domain>/health. With prod, Swagger is disabled.

Project structure and architecture

portaltrip/
├── pom.xml                                            # Maven, Spring Boot and JaCoCo
├── compose.yml                                        # Local stack: API + PostgreSQL 17 with host ports
├── compose.coolify.yml                                # Same stack for Coolify, no host ports
├── db/Dockerfile                                      # PostgreSQL image with seed and schema baked in
├── .env.example                                       # Local environment template
├── bruno/                                             # Executable REST contract collection
├── db/
│   ├── seed.sql                                       # Rick and Morty catalog
│   └── app-schema.sql                                 # Users, reservations and companions
└── src/
    ├── main/
    │   ├── java/cl/prgm/portaltrip/
    │   │   ├── PortaltripApplication.java             # Spring Boot entry point
    │   │   ├── ServletInitializer.java                # WAR deployment initializer
    │   │   │
    │   │   ├── domain/                                # Domain rules and models
    │   │   │   ├── model/
    │   │   │   │   ├── Character.java                # Character domain record
    │   │   │   │   ├── Episode.java                  # Episode domain record
    │   │   │   │   ├── Location.java                 # Location and insurance rule
    │   │   │   │   ├── Quote.java                    # Calculated price breakdown
    │   │   │   │   ├── Reservation.java              # Aggregate, ownership and transitions
    │   │   │   │   ├── ReservationBalanceResult.java # Reservation plus remaining credits
    │   │   │   │   ├── ReservationDraft.java         # Self-validating creation input
    │   │   │   │   ├── ReservationStatus.java        # Reservation lifecycle states
    │   │   │   │   ├── RiskLevel.java                # LOW, MEDIUM and HIGH
    │   │   │   │   ├── TripType.java                 # Trip type and price multiplier
    │   │   │   │   └── UserAccount.java              # Credentials, role and credit balance
    │   │   │   ├── service/
    │   │   │   │   └── QuoteCalculator.java          # Quote and risk rules
    │   │   │   └── exception/
    │   │   │       ├── DomainValidationException.java
    │   │   │       ├── DuplicateUserException.java
    │   │   │       ├── IdempotencyConflictException.java
    │   │   │       ├── InsufficientBalanceException.java
    │   │   │       ├── InvalidCredentialsException.java
    │   │   │       ├── InvalidReservationStateException.java
    │   │   │       └── ResourceNotFoundException.java
    │   │   │
    │   │   ├── application/service/                  # Service interfaces and use cases
    │   │   │   ├── AuthResult.java
    │   │   │   ├── AuthService.java
    │   │   │   ├── AuthServiceImpl.java
    │   │   │   ├── CharacterService.java
    │   │   │   ├── CharacterServiceImpl.java
    │   │   │   ├── EpisodeService.java
    │   │   │   ├── EpisodeServiceImpl.java
    │   │   │   ├── LocationService.java
    │   │   │   ├── LocationServiceImpl.java
    │   │   │   ├── QuoteQuery.java
    │   │   │   ├── QuoteService.java
    │   │   │   ├── QuoteServiceImpl.java
    │   │   │   ├── ReservationService.java
    │   │   │   ├── ReservationServiceImpl.java
    │   │   │   ├── UserService.java
    │   │   │   └── UserServiceImpl.java
    │   │   │
    │   │   └── infrastructure/
    │   │       ├── persistence/                      # JPA entities and repositories
    │   │       │   ├── CharacterEntity.java
    │   │       │   ├── EpisodeEntity.java
    │   │       │   ├── LocationEntity.java
    │   │       │   ├── ReservationEntity.java
    │   │       │   ├── UserEntity.java
    │   │       │   └── repository/
    │   │       │       ├── CharacterJpaRepository.java
    │   │       │       ├── EpisodeJpaRepository.java
    │   │       │       ├── LocationJpaRepository.java
    │   │       │       ├── ReservationJpaRepository.java
    │   │       │       └── UserJpaRepository.java
    │   │       ├── security/                         # JWT, CORS and HTTP security
    │   │       │   ├── JwtTokenService.java          # HS256 access-token issuer
    │   │       │   ├── PortalTripUserDetailsService.java
    │   │       │   ├── RestAccessDeniedHandler.java
    │   │       │   ├── RestAuthenticationEntryPoint.java
    │   │       │   └── SecurityConfig.java           # Public catalog vs authenticated wallet
    │   │       └── web/                              # REST controllers and DTOs
    │   │           ├── config/OpenApiConfig.java
    │   │           ├── controller/
    │   │           │   ├── AuthController.java
    │   │           │   ├── CharacterController.java
    │   │           │   ├── EpisodeController.java
    │   │           │   ├── HomeController.java
    │   │           │   ├── LocationController.java
    │   │           │   ├── QuoteController.java
    │   │           │   ├── ReservationController.java
    │   │           │   └── UserController.java
    │   │           ├── dto/                          # HTTP request and response records
    │   │           └── exception/GlobalExceptionHandler.java
    │   └── resources/
    │       ├── application.yaml                      # Safe defaults and JWT settings
    │       ├── application-dev.yaml                  # PostgreSQL, JPA and enabled OpenAPI
    │       ├── application-prod.yaml                 # Validated schema and disabled OpenAPI
    │       └── static/index.html                     # Welcome page
    └── test/java/cl/prgm/portaltrip/                 # 196 automated tests
        ├── AuthenticationFlowIntegrationTest.java    # Register, login, JWT, CORS, 401 and 403
        ├── domain/                                   # Model, exception and quote-rule tests
        ├── application/service/                      # Service tests with mocked JPA repositories
        └── infrastructure/
            ├── persistence/                          # Entity mapping and user-scoped queries
            ├── security/                             # JWT issue/decode and UserDetails
            └── web/                                  # Controller, DTO, OpenAPI and errors

Request and persistence flow

flowchart TD
    HTTP[HTTP request] --> CONTROLLER[REST Controller]
    CONTROLLER --> CONTRACT[Service interface]
    CONTRACT --> SERVICE[ServiceImpl]
    SERVICE --> DOMAIN[Domain records and business rules]
    SERVICE --> REPOSITORY[Spring Data JpaRepository]
    REPOSITORY --> ENTITY[JPA entity mapping]
    ENTITY --> DATABASE[(PostgreSQL 17)]
Loading

ServiceImpl is the point where both sides meet. It uses domain objects to make business decisions and JPA repositories to load or store data. The controllers never access JPA, and the domain does not import Spring or Jakarta Persistence.


Relational database model and table references

The catalog contains 826 characters, 126 locations and 51 episodes. Docker loads it once from db/seed.sql. The application then creates reservations against that catalog through the schema in db/app-schema.sql.

erDiagram
    LOCATIONS ||--o{ CHARACTERS : "origin"
    LOCATIONS ||--o{ CHARACTERS : "current location"
    LOCATIONS ||--o{ LOCATION_RESIDENTS : "contains"
    CHARACTERS ||--o{ LOCATION_RESIDENTS : "appears in"
    CHARACTERS ||--o{ CHARACTER_EPISODES : "appears in"
    EPISODES ||--o{ CHARACTER_EPISODES : "contains"
    USERS ||--o{ RESERVATIONS : "purchases"
    USERS ||--o{ PORTAL_STIPENDS : "earns"
    USERS ||--o| PORTAL_ACTIVITY : "operates"
    LOCATIONS ||--o{ RESERVATIONS : "destination"
    RESERVATIONS ||--o{ RESERVATION_COMPANIONS : "includes"
    CHARACTERS ||--o{ RESERVATION_COMPANIONS : "selected as"

    USERS {
        uuid id PK
        string email UK
        string password_hash
        string full_name
        string role
        decimal balance
        bigint version
        timestamp created_at
        timestamp updated_at
    }

    PORTAL_STIPENDS {
        uuid id PK
        uuid user_id FK
        decimal amount
        timestamp created_at
    }

    PORTAL_ACTIVITY {
        uuid user_id PK,FK
        uuid cycle_id
        timestamp started_at
        timestamp sampled_at
        integer sequence
        bigint active_ms
        double distance
        decimal payout
    }

    LOCATIONS {
        integer id PK
        string name
        string type
        string dimension
    }

    CHARACTERS {
        integer id PK
        string name
        string status
        string species
        string type
        string gender
        integer origin_id FK
        integer location_id FK
        string image
    }

    EPISODES {
        integer id PK
        string name
        string air_date
        string episode
    }

    LOCATION_RESIDENTS {
        integer location_id PK,FK
        integer character_id PK,FK
    }

    CHARACTER_EPISODES {
        integer character_id PK,FK
        integer episode_id PK,FK
    }

    RESERVATIONS {
        uuid id PK
        uuid user_id FK
        uuid idempotency_key UK
        string number UK
        string status
        string passenger_name
        string email
        integer destination_id FK
        date travel_date
        integer passengers
        string trip_type
        boolean insurance
        decimal total
        string risk
        timestamp created_at
        timestamp started_at
        timestamp completed_at
    }

    RESERVATION_COMPANIONS {
        uuid reservation_id PK,FK
        integer character_id PK,FK
    }
Loading

Foreign keys

  1. characters.origin_id references locations.id.
  2. characters.location_id references locations.id.
  3. location_residents joins locations and their last known residents.
  4. character_episodes joins characters and episodes.
  5. reservations.user_id references users.id.
  6. reservations.destination_id references locations.id.
  7. reservation_companions joins reservations and selected characters.
  8. portal_stipends.user_id and portal_activity.user_id reference users.id with cascading deletion.

Environment variables and Docker setup

No .env file is required for local development. To override the defaults, optionally copy the example configuration:

cp .env.example .env
Variable Description Local default
SPRING_PROFILES_ACTIVE Spring profile (dev enables Swagger, prod disables it) dev
SERVER_PORT Spring Boot HTTP port 8080
DB_HOST PostgreSQL hostname localhost
DB_PORT PostgreSQL port 5432
DB_NAME PostgreSQL database rickandmorty
DB_USER PostgreSQL user rick
DB_PASSWORD PostgreSQL password morty
JWT_SECRET_BASE64 Base64 HMAC secret, at least 32 decoded bytes. dev and Compose ship a development-only key; prod requires an explicit value dev key from .env.example
JWT_TTL Access-token lifetime PT30M
JWT_ISSUER Expected JWT issuer https://portaltrip.local
JWT_AUDIENCE Expected JWT audience portaltrip-api
REGISTRATION_CREDIT Credits granted to a new account 5000.00
APP_CORS_ALLOWED_ORIGINS Comma-separated frontend origins http://localhost:4321,http://127.0.0.1:4321,http://localhost:5173,http://127.0.0.1:5173

The development key is safe to use locally only. Generate a real one for production and export it as JWT_SECRET_BASE64:

openssl rand -base64 32

Start or stop the API and PostgreSQL with Docker Compose:

# Build Spring Boot, start the API and initialize PostgreSQL
docker compose up -d --build

# Stop the container without deleting its data
docker compose down

Compose exposes the API at http://localhost:8080 and PostgreSQL at localhost:5432. The stack defaults to the dev profile, so Swagger UI is available at http://localhost:8080/swagger-ui.html. Inside the Compose network Spring Boot connects to the database with the hostname postgres.

For servers with their own reverse proxy (Coolify) use compose.coolify.yml, which is the same stack without host port bindings.

To run the same stack without documentation endpoints:

SPRING_PROFILES_ACTIVE=prod docker compose up -d --build

The official PostgreSQL image runs these files only when it creates the data volume:

db/seed.sql        -> /docker-entrypoint-initdb.d/01-seed.sql
db/app-schema.sql  -> /docker-entrypoint-initdb.d/02-app-schema.sql

To recreate the database from scratch, run docker compose down -v && docker compose up -d. This deletes existing users and reservations as well as the catalog volume.


How to run the application

# Start only PostgreSQL; Maven will run the API below
docker compose up -d postgres

# Run PortalTrip with the Maven wrapper
./mvnw spring-boot:run

The application starts at http://localhost:8080. The dev profile includes a development-only JWT key and CORS defaults, so no environment variables are required locally. The prod profile has no fallback and requires JWT_SECRET_BASE64.

  • Swagger UI: http://localhost:8080/swagger-ui.html
  • OpenAPI JSON: http://localhost:8080/api-docs
  • Healthcheck: http://localhost:8080/health

The default local profile is dev; it enables Swagger UI and OpenAPI. Production requires explicit database variables, validates the existing schema and disables both documentation endpoints:

SPRING_PROFILES_ACTIVE=prod \
DB_HOST=localhost DB_PORT=5432 DB_NAME=rickandmorty \
DB_USER=rick DB_PASSWORD=morty \
JWT_SECRET_BASE64='replace-with-a-generated-secret' \
./mvnw spring-boot:run

Testing and JaCoCo coverage

The suite contains 196 tests. Maven generates the console and HTML reports during test, and enforces 100% instruction and branch coverage during verify.

# Run tests
./mvnw clean test

# Run tests and enforce the coverage thresholds
./mvnw clean verify

The HTML report is generated at:

target/site/jacoco/index.html

Open the JaCoCo report published by GitHub Actions

Current verified coverage:

Counter Covered Result
Instructions 4465 / 4465 100%
Branches 172 / 172 100%
Lines 915 / 915 100%
Methods 287 / 287 100%

GitHub Actions executes ./mvnw -B clean verify on pull requests and pushes to main. It retains the Surefire and JaCoCo artifacts for 14 days and publishes the successful main report with GitHub Pages.


REST API documentation

Catalog and quote endpoints are public. Registration and login are public. Profile, portal activity and reservation endpoints require Authorization: Bearer <token>.

Every /api/v1 endpoint returns the same response envelope:

{
  "status": 200,
  "message": "Quote calculated successfully",
  "data": {},
  "timestamp": "2026-08-30T22:49:00Z"
}

Catalog endpoints

Method Endpoint Description Status codes
GET /api/v1/locations List location summaries 200 OK
GET /api/v1/locations/{id} Get a location with resident IDs 200 OK, 400 Bad Request, 404 Not Found
GET /api/v1/characters List character summaries 200 OK
GET /api/v1/characters/{id} Get a character with episode IDs 200 OK, 400 Bad Request, 404 Not Found
GET /api/v1/episodes List episode summaries 200 OK
GET /api/v1/episodes/{id} Get an episode with character IDs 200 OK, 400 Bad Request, 404 Not Found

Quote endpoint

Method Endpoint Description Status codes
POST /api/v1/quotes Calculate price and risk without persisting data 200 OK, 400 Bad Request, 404 Not Found

Example request:

{
  "destinationId": 3,
  "passengers": 2,
  "tripType": "exploration",
  "insurance": false
}

Example response data:

{
  "basePrice": 1200,
  "locationSurcharge": 300,
  "passengerSurcharge": 216,
  "tripSurcharge": 360,
  "insuranceCost": 380,
  "total": 2456,
  "risk": "MEDIUM"
}

Reservation endpoints

All reservation endpoints require Authorization: Bearer <token>. Creation also requires a UUID in Idempotency-Key, so retrying the same request cannot charge the balance twice.

Method Endpoint Description Status codes
POST /api/v1/reservations Validate, charge and create a confirmed reservation 201 Created, 400 Bad Request, 404 Not Found, 409 Conflict, 422 Unprocessable Entity
GET /api/v1/reservations List reservations from newest to oldest 200 OK
GET /api/v1/reservations/{id} Get reservation detail 200 OK, 400 Bad Request, 404 Not Found
PATCH /api/v1/reservations/{id}/start Move CONFIRMED to IN_PROGRESS 200 OK, 404 Not Found, 409 Conflict
PATCH /api/v1/reservations/{id}/complete Move IN_PROGRESS to COMPLETED 200 OK, 404 Not Found, 409 Conflict
PATCH /api/v1/reservations/{id}/cancel Cancel and refund a confirmed reservation 200 OK, 404 Not Found, 409 Conflict

Example creation request:

{
  "passengerName": "Morty Smith",
  "destinationId": 1,
  "travelDate": "2099-12-20",
  "passengers": 2,
  "companionIds": [1, 2],
  "tripType": "exploration",
  "insurance": true,
  "comments": "Window seat"
}

Creation and cancellation responses wrap the reservation together with remainingBalance, allowing the frontend to refresh its balance immediately.

Authentication and user endpoints

Method Endpoint Description Authentication
POST /api/v1/auth/register Create an account, grant the initial credit and return a JWT Public
POST /api/v1/auth/login Validate credentials and return a JWT Public
GET /api/v1/users/me Return the current user and database-backed balance Bearer JWT

Passwords use Spring Security's delegating password encoder with BCrypt. HS256 access tokens expire after 30 minutes by default and validate signature, expiration, issuer and audience. The signing secret has no fallback in the repository.

Error handling

Scenario HTTP status Response message
Resource not found 404 Not Found Identifies the missing resource and ID
Invalid HTTP input 400 Bad Request Lists invalid fields and validation messages
Domain rule violation 422 Unprocessable Entity Returns Validation failed and the domain errors in data
Invalid state transition 409 Conflict Identifies the current and requested reservation states
Duplicate account or conflicting idempotency key 409 Conflict Explains the conflict without exposing credentials
Invalid or absent authentication 401 Unauthorized Returns the unified JSON response envelope
Insufficient balance 422 Unprocessable Entity Returns required and current credit values
Unexpected server error 500 Internal Server Error Returns a generic message and logs the exception server-side

Business rules

Quote calculation

Concept Rule
Base price 1200 credits
Trip type express x1, exploration x1.3, premium x1.65
Extra passengers 18% of the base price per additional passenger
Space station 25% surcharge when the location type contains station
Insurance 190 credits per passenger, mandatory for an unknown dimension
Risk HIGH with no residents, MEDIUM for an unknown dimension or fewer than five residents, LOW otherwise

Reservation validation

  • ReservationRequestDto validates the HTTP request with Jakarta Validation.
  • ReservationDraft checks its field invariants when constructed.
  • Reservation.confirm checks companion status and destination insurance before creating the aggregate.
  • ReservationServiceImpl verifies that every requested companion exists, then coordinates domain validation, quote calculation and persistence.
  • The passenger email comes from the authenticated account, never from the reservation request.
  • Creating a reservation locks the user row, checks idempotency and debits the quote total atomically.
  • Cancelling a confirmed reservation restores that total atomically. This concept API intentionally has no credit-history model.

Reservation lifecycle

stateDiagram-v2
    [*] --> CONFIRMED
    CONFIRMED --> IN_PROGRESS: start
    CONFIRMED --> CANCELLED: cancel
    IN_PROGRESS --> COMPLETED: complete
    COMPLETED --> [*]
    CANCELLED --> [*]
Loading

COMPLETED and CANCELLED are terminal states. An invalid transition returns 409 Conflict.


cURL testing guide

# 1. Healthcheck
curl -i http://localhost:8080/health

# 2. List locations
curl -i http://localhost:8080/api/v1/locations

# 3. Get location detail
curl -i http://localhost:8080/api/v1/locations/3

# 4. Calculate a quote
curl -i -X POST http://localhost:8080/api/v1/quotes \
  -H "Content-Type: application/json" \
  -d '{
    "destinationId": 3,
    "passengers": 2,
    "tripType": "exploration",
    "insurance": false
  }'

# 5. Register and copy data.accessToken from the response
curl -i -X POST http://localhost:8080/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "fullName": "Morty Smith",
    "email": "morty@example.com",
    "password": "portal-gun-123"
  }'

# 6. Log in if the account already exists
curl -i -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "morty@example.com",
    "password": "portal-gun-123"
  }'

# 7. Create a reservation
curl -i -X POST http://localhost:8080/api/v1/reservations \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Idempotency-Key: 58f13289-82e8-4e67-a196-8b8ef445c978" \
  -H "Content-Type: application/json" \
  -d '{
    "passengerName": "Morty Smith",
    "destinationId": 1,
    "travelDate": "2099-12-20",
    "passengers": 2,
    "companionIds": [1, 2],
    "tripType": "exploration",
    "insurance": true,
    "comments": "Window seat"
  }'

# 8. Read the current balance
curl -i http://localhost:8080/api/v1/users/me \
  -H "Authorization: Bearer ${ACCESS_TOKEN}"

# 9. Cancel and refund a confirmed reservation
curl -i -X PATCH http://localhost:8080/api/v1/reservations/{id}/cancel \
  -H "Authorization: Bearer ${ACCESS_TOKEN}"

Bruno contract collection

Open the bruno/ directory in Bruno, select the local environment and run the collection in sequence. Register creates a unique email so the run does not depend on an empty users table. The collection then logs in, reads /users/me, charges a reservation, lists it, refunds a second confirmed booking, completes the first trip and checks that a completed reservation cannot be cancelled.

Seq File What it checks
1 01-healthcheck.bru GET /health
2 02-list-locations.bru Public catalog
3 03-calculate-quote.bru Public quote
4 04-register.bru Account, initial 5000 credits and JWT
5 05-login.bru Email/password login replaces the token
6 06-get-profile.bru Bearer /users/me
7 07-create-reservation.bru Authenticated charge with Idempotency-Key
8 08-get-reservation.bru Owner-scoped detail
9 09-list-reservations.bru Owner-scoped list
10 10-create-refund-reservation.bru Second confirmed booking
11 11-cancel-reservation.bru Cancel restores the balance from step 7
12 12-start-reservation.bru CONFIRMED to IN_PROGRESS
13 13-complete-reservation.bru IN_PROGRESS to COMPLETED
14 14-reject-terminal-cancel.bru 409 Conflict on a completed trip

The same audit can be run from the CLI while the application is listening on port 8080:

cd bruno
bru run --env-file environments/local.bru --bail

Logging

PortalTrip uses Spring Boot's default SLF4J and Logback configuration. Normal application output goes to the console at INFO level.

GlobalExceptionHandler logs unexpected exceptions with their stack traces and returns Internal server error to the client. Expected 400, 404, 409 and 422 responses are not logged as server failures.

Package-specific levels can be configured in src/main/resources/application.yaml:

logging:
  level:
    root: INFO
    cl.prgm.portaltrip: DEBUG

Portal activity rewards

The server owns eligibility, the random payout and wallet updates. The browser sends movement measurements, never a requested amount. Activity is available only to an authenticated user. The previous free-claim URL /api/v1/users/me/portal-stipend is no longer exposed.

API contract

Both endpoints require Authorization: Bearer <token> and use the standard response envelope.

Method Endpoint Result
POST /api/v1/users/me/portal-activity/start Open or resume the user's unfinished cycle; no request body and no payout
POST /api/v1/users/me/portal-activity Validate a sample, return progress and credit the wallet if the cycle completes

Example sample, using the cycleId and nextSequence returned by the server:

{
  "cycleId": "8fc80791-a9fc-4500-a681-69a8b8334993",
  "sequence": 1,
  "activeMs": 900,
  "distance": 0.6
}

activeMs is active movement time since the preceding sample. The client counts consecutive moving events separated by at most 200 ms. distance is the path length in portal widths, which avoids rewarding larger screens. No coordinates are sent. Response data contains cycleId, nextSequence, progress from 0 to 1, payout and balance. An unfinished cycle has payout: 0.

The client sends about one sample per second, with one request in flight. The server:

  • Checks the cycle belongs to the authenticated account and enforces sample order.
  • Requires at least 750 ms between samples and compares active time to server elapsed time.
  • Accepts at most 5000 active milliseconds and 20 portal widths per sample, and credits at most 4 widths per active second.
  • Requires 2400 active milliseconds and 1.5 portal widths to finish.
  • Resets progress for a stationary sample or a gap longer than 5 seconds; cycles expire at 90 seconds.
  • Returns the previous payout when the last accepted sample is retried, without adding credits again.

Invalid JSON or field constraints return 400; missing accounts/activity return 404; invalid, expired, out-of-order or too-frequent samples return 422; the payout cooldown returns 429. Missing or invalid authentication returns 401.

Reward amounts

Every completed, paid cycle awards 200 to 1620 credits. Zero in a response means that the activity has not earned its reward yet.

Rule Value
Gaussian base Mean 650, standard deviation 100, clamped to 300–900
Movement bonus Up to 50%, increasing between 1.5 and 6 validated portal widths
Active-time bonus Up to 20%, increasing between 2400 and 8000 active milliseconds
Maximum before fatigue 900 × 1.5 × 1.2 = 1620
Final minimum after fatigue 200
Payout cooldown 6 seconds
Repeated-help fatigue Rolling 12-minute window
Earned-credit fatigue Rolling 20-minute window, reference value 6500
Consecutive-help reduction Factor 0.52 when the last payout was less than 28 seconds ago

Bonuses multiply the base before fatigue and rounding. The 6500 value scales fatigue; it is not a hard earnings cap. Staying still adds no active time. Movement and duration are bounded so sending larger numbers cannot increase bonuses indefinitely.

Backend implementation

File Responsibility
UserController.java Authenticated start/sample routes and request validation
PortalActivityService.java Lock the account, validate its cycle and coordinate one reward
PortalActivityEntity.java Persist cycle ID, timing, sequence, accepted activity and completed payout
PortalStipendCalculator.java Gaussian base, movement/time bonuses, cooldown and fatigue
PortalStipendServiceImpl.java Save the reward history and credit the account
PortalActivityRequestDto.java, PortalActivityResponseDto.java Sample and progress/wallet contract
GlobalExceptionHandler.java Structured validation and cooldown errors

The activity row, reward history and balance change share a transaction. A pessimistic account lock serializes concurrent requests, including duplicate final samples. portal_activity keeps one row per user; portal_stipends records successful payouts and has a (user_id, created_at) index for rolling-window queries.

The integration tests cover inactivity, short passes, pauses, invalid timing, wrong cycles, cooldowns, concurrent retries and wallet consistency. Calculator tests cover movement/time bonuses, fatigue and the minimum/maximum payout.

These checks validate the protocol and prevent client-selected amounts. They do not prove human presence: a modified client can fabricate plausible telemetry.

Local backend in Docker

Run from this backend checkout:

docker compose --env-file /dev/null up -d --build

This starts PostgreSQL and the API at http://localhost:8080. --env-file /dev/null skips the local .env; exported shell variables still override Compose defaults. Start the frontend separately from its own checkout with pnpm install and pnpm dev.

A fresh database volume automatically loads 126 locations, 826 characters, 51 episodes, 804 resident links and 1267 character/episode links, followed by the application tables.

Existing database upgrades

For an existing local database, apply the additive patch once:

docker compose exec -T postgres \
  sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 --single-transaction' \
  < db/patch-portal-stipends.sql

For Coolify, open the terminal of the PortalTrip postgres container, run psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1, then paste the contents of db/patch-portal-stipends.sql inside BEGIN; and COMMIT;. Leave psql with \q. The patch uses IF NOT EXISTS and preserves existing data. It is not baked into a migration runner; apply it before deploying the backend, then deploy the matching frontend. Fresh volumes already receive both reward tables from db/app-schema.sql.

Releases

Packages

Contributors

Languages