Skip to main content

SGIVU Features

SGIVU provides a comprehensive suite of features designed for modern vehicle inventory management. This page covers all major capabilities across authentication, business domains, machine learning, and platform services.

Authentication & Authorization

OAuth 2.1 / OpenID Connect

Modern Authentication

Full OAuth 2.1 and OpenID Connect implementation with industry best practices

JWT Tokens

Signed JWT access tokens with RS256 algorithm using JKS keystore

PKCE Flow

Authorization Code with PKCE for secure single-page applications

Refresh Tokens

Automatic token refresh for seamless user experience
Key Features:
  • Token Issuance: Access tokens (JWT) and refresh tokens
  • OIDC Discovery: Standard .well-known/openid-configuration endpoint
  • JWKS Endpoint: Public keys at /oauth2/jwks for token verification
  • Custom Claims: Includes rolesAndPermissions, username, isAdmin
  • Session Management: Spring Session JDBC for persistent OAuth2 sessions
  • Multiple Clients: Support for web apps, mobile apps, and testing tools
Supported Endpoints:
# OIDC Discovery
GET /.well-known/openid-configuration

# Authorization
GET /oauth2/authorize

# Token endpoint
POST /oauth2/token

# JWKS
GET /oauth2/jwks

# Login page
GET /login

Backend for Frontend (BFF) Pattern

The API Gateway implements the BFF pattern, managing OAuth2 tokens server-side for enhanced security.
BFF Benefits:
1

Token Security

Access and refresh tokens stored server-side in Redis, never exposed to the browser
2

Session Cookie

Simple session cookie with HttpOnly, SameSite=Lax attributes
3

Automatic Token Relay

Gateway automatically includes Bearer tokens when proxying to backend services
4

Horizontal Scaling

Redis-backed sessions enable stateless gateway instances
Session API:
# Get current session info
GET /auth/session

Response:
{
  "subject": "user-uuid",
  "username": "john.doe",
  "roles": ["USER", "ADMIN"],
  "isAdmin": true
}

Granular Permission System

Permission Model: SGIVU uses fine-grained permissions mapped to JWT claims:
user:create, user:read, user:update, user:delete
person:create, person:read, person:update, person:delete
role:create, role:read, role:update, role:delete
permission:read
vehicle:create, vehicle:read, vehicle:update, vehicle:delete
client:create, client:read, client:update, client:delete
contract:create, contract:read, contract:update, contract:delete
ml:predict, ml:retrain
Role-Based Access Control:
  • Roles aggregate multiple permissions
  • Users can have multiple roles
  • Permissions checked via @PreAuthorize annotations
  • JWT includes rolesAndPermissions array for efficient validation
Example Authorization:
@PreAuthorize("hasAuthority('vehicle:create')")
public VehicleResponse createVehicle(VehicleRequest request) {
    // Only users with vehicle:create permission can execute
}

Service-to-Service Authentication

Internal Service Key: For service-to-service communication without user context:
GET /internal/users/username/{username}
X-Internal-Service-Key: {shared-secret}
The internal service key must be kept secret and stored in environment variables or a secret manager. Never commit to Git.

User Management

User Administration

CRUD Operations

Complete user lifecycle management with validation

Password Security

Custom password strength validation with complexity requirements

User Search

Multi-criteria search with pagination and sorting

Status Management

Enable/disable users without deletion
User Features:
  • User Creation: Username, email, password with strength validation
  • Profile Management: Link users to person entities for detailed profiles
  • Role Assignment: Assign multiple roles per user
  • Status Control: Active/inactive status for access control
  • Audit Trail: Creation and modification timestamps
  • Username Validation: Prevent special characters with custom validator
Password Requirements:
  • Minimum length (configurable)
  • Uppercase and lowercase letters
  • Numbers and special characters
  • No common passwords
  • Validated at creation and update

Person Management

Person Entity:
  • Full name, document ID, contact information
  • Address management with geographical data
  • Date of birth and demographic info
  • Photo URL support
  • Linked to user accounts
API Endpoints:
# Create person
POST /v1/persons

# Get person by ID
GET /v1/persons/{id}

# Update person
PUT /v1/persons/{id}

# Search persons
GET /v1/persons/search?name={name}&documentId={id}

# Delete person
DELETE /v1/persons/{id}

Role & Permission Management

Role Features:
  • Create custom roles with descriptions
  • Assign multiple permissions to roles
  • View role hierarchy
  • Audit role assignments
Permission Features:
  • Predefined permission catalog
  • Read-only permissions list (cannot be created/deleted)
  • Permission grouping by domain
  • Direct permission-to-role mapping
Default Roles:
  • ADMIN: Full system access with all permissions
  • USER: Standard user with limited permissions
  • Custom roles can be created as needed

Vehicle Management

Vehicle Catalog

Vehicle Types

Support for cars, motorcycles, and custom vehicle types

Comprehensive Data

Make, model, year, VIN, mileage, pricing, and more

Status Tracking

Available, sold, reserved, maintenance statuses

Image Management

Multiple images per vehicle with S3 integration
Vehicle Attributes:
{
  "id": "uuid",
  "vin": "1HGBH41JXMN109186",
  "make": "Toyota",
  "model": "Camry",
  "year": 2023,
  "color": "Silver",
  "mileage": 15000,
  "price": 28500.00,
  "status": "available",
  "vehicleType": "CAR",
  "transmission": "AUTOMATIC",
  "fuelType": "GASOLINE",
  "description": "Excellent condition, single owner",
  "images": [
    {
      "id": "uuid",
      "url": "https://s3.amazonaws.com/...",
      "isPrimary": true
    }
  ]
}

Advanced Search & Filtering

Search Criteria:
  • Make, model, year range
  • Price range (min/max)
  • Mileage range
  • Status (available, unavailable, sold)
  • Vehicle type
  • Fuel type and transmission
  • Color
  • Full-text search in description
Search API:
GET /v1/vehicles/search?
  make=Toyota&
  minYear=2020&
  maxYear=2023&
  minPrice=20000&
  maxPrice=35000&
  status=available&
  page=0&
  size=20&
  sort=price,asc
Pagination & Sorting:
  • Configurable page size
  • Sort by any field (price, year, mileage, createdAt)
  • Total count and page metadata
  • Cursor-based pagination support

Image Management with S3

Presigned URL Upload Flow:
1

Request Upload URL

Frontend requests presigned URL from backend
POST /v1/vehicles/{vehicleId}/images/upload-url
Content-Type: application/json

{
  "filename": "front-view.jpg",
  "contentType": "image/jpeg"
}
2

Receive Presigned URL

Backend generates presigned URL valid for 5 minutes
{
  "uploadUrl": "https://s3.amazonaws.com/...",
  "key": "vehicles/uuid/images/front-view.jpg",
  "expiresIn": 300
}
3

Upload Directly to S3

Client uploads image directly to S3 using presigned URL
PUT {uploadUrl}
Content-Type: image/jpeg

{binary image data}
4

Confirm Upload

After successful upload, confirm to register metadata
POST /v1/vehicles/{vehicleId}/images/confirm-upload

{
  "key": "vehicles/uuid/images/front-view.jpg",
  "filename": "front-view.jpg",
  "contentType": "image/jpeg",
  "size": 245678
}
Image Features:
  • Supported Formats: JPEG, PNG, WebP
  • Primary Image: First image or manually designated
  • Automatic Ordering: When primary deleted, next image promoted
  • CORS Configuration: S3 bucket configured for allowed origins
  • Metadata Storage: Image info stored in PostgreSQL
  • Presigned Downloads: Secure time-limited download URLs
Image Management APIs:
# List vehicle images
GET /v1/vehicles/{id}/images

# Get presigned download URL
GET /v1/vehicles/{id}/images/{imageId}/download-url

# Set primary image
PUT /v1/vehicles/{id}/images/{imageId}/primary

# Delete image
DELETE /v1/vehicles/{id}/images/{imageId}
Direct S3 upload reduces backend load and improves upload performance. Backend validates and tracks metadata after upload.

Client Management

Person & Company Clients

Individual Clients

Manage person clients with personal details and contact info

Corporate Clients

Handle company clients with business registration and representatives
Person Clients:
{
  "id": "uuid",
  "type": "PERSON",
  "firstName": "John",
  "lastName": "Doe",
  "documentId": "123456789",
  "email": "[email protected]",
  "phone": "+1-555-0123",
  "dateOfBirth": "1985-06-15",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "state": "IL",
    "zipCode": "62701",
    "country": "USA"
  }
}
Company Clients:
{
  "id": "uuid",
  "type": "COMPANY",
  "companyName": "Acme Corporation",
  "taxId": "98-7654321",
  "registrationNumber": "REG-123456",
  "email": "[email protected]",
  "phone": "+1-555-0199",
  "website": "https://acme.com",
  "address": {
    "street": "456 Business Ave",
    "city": "Chicago",
    "state": "IL",
    "zipCode": "60601",
    "country": "USA"
  },
  "contactPerson": {
    "name": "Jane Smith",
    "title": "Purchasing Manager",
    "email": "[email protected]",
    "phone": "+1-555-0188"
  }
}

Client Search & Analytics

Search Features:
  • Search by name, document ID, tax ID
  • Filter by client type (person/company)
  • Location-based filtering
  • Email and phone lookup
  • Date range filters
  • Pagination and sorting
Client Statistics:
# Get client counts
GET /v1/clients/statistics

Response:
{
  "totalClients": 1523,
  "personClients": 1234,
  "companyClients": 289,
  "activeClients": 1456,
  "newThisMonth": 42
}

Address Management

Address Features:
  • Complete address fields (street, city, state, postal code, country)
  • Geocoding support (latitude/longitude)
  • Multiple addresses per client
  • Primary address designation
  • Address validation
  • International address formats

Purchase & Sales Management

Contract Lifecycle

1

Contract Creation

Create purchase or sale contract linking client, vehicle, and user
2

Status Management

Track contract through statuses: DRAFT → ACTIVE → COMPLETED/CANCELLED
3

Document Generation

Generate PDF contracts with all details and signatures
4

Reporting

Export contracts to PDF, Excel, or CSV for analysis
Contract Types:
  • PURCHASE: Acquiring vehicles for inventory
  • SALE: Selling vehicles to clients
Contract Attributes:
{
  "id": "uuid",
  "contractNumber": "PS-2026-00123",
  "contractType": "SALE",
  "contractStatus": "ACTIVE",
  "contractDate": "2026-03-06",
  "totalAmount": 28500.00,
  "downPayment": 5000.00,
  "financedAmount": 23500.00,
  "interestRate": 4.5,
  "termMonths": 60,
  "monthlyPayment": 437.89,
  "client": {
    "id": "client-uuid",
    "name": "John Doe"
  },
  "vehicle": {
    "id": "vehicle-uuid",
    "vin": "1HGBH41JXMN109186",
    "description": "2023 Toyota Camry"
  },
  "user": {
    "id": "user-uuid",
    "name": "Sales Agent"
  },
  "notes": "Trade-in applied, warranty included"
}
Search Criteria:
GET /v1/purchase-sales/search?
  contractType=SALE&
  contractStatus=ACTIVE&
  clientId={uuid}&
  vehicleId={uuid}&
  fromDate=2026-01-01&
  toDate=2026-12-31&
  minAmount=20000&
  maxAmount=50000&
  page=0&
  size=20

Report Generation

Report Formats:

PDF

Professional contract documents using OpenPDF

Excel

Detailed spreadsheets with Apache POI

CSV

Data exports for analysis and import
Report Endpoints:
# Generate PDF contract
GET /v1/purchase-sales/{id}/pdf
Content-Type: application/pdf

# Export to Excel
GET /v1/purchase-sales/export/excel?
  fromDate=2026-01-01&
  toDate=2026-03-31
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

# Export to CSV
GET /v1/purchase-sales/export/csv?
  contractType=SALE&
  contractStatus=COMPLETED
Content-Type: text/csv
Report Contents:
  • Contract details and terms
  • Client information
  • Vehicle specifications
  • Payment schedule
  • Signatures and timestamps
  • Company branding and logos

Machine Learning

Demand Forecasting

SGIVU’s ML service provides predictive analytics for inventory management and sales forecasting.
ML Capabilities:
  • Demand prediction by vehicle segment
  • Price optimization recommendations
  • Inventory turnover forecasting
  • Seasonal trend analysis
  • Historical pattern recognition
Prediction API:
POST /v1/ml/predict
Content-Type: application/json

{
  "features": {
    "make": "Toyota",
    "model": "Camry",
    "year": 2023,
    "mileage": 15000,
    "season": "SPRING",
    "economicIndicator": 1.05
  }
}

Response:
{
  "prediction": 0.78,
  "confidence": 0.92,
  "recommendation": "HIGH_DEMAND",
  "estimatedDaysToSell": 12
}

Prediction with Historical Context

POST /v1/ml/predict-with-history

Response:
{
  "prediction": 0.78,
  "confidence": 0.92,
  "historical": [
    {
      "date": "2026-02-01",
      "value": 0.72
    },
    {
      "date": "2026-02-15",
      "value": 0.75
    },
    {
      "date": "2026-03-01",
      "value": 0.78
    }
  ],
  "trend": "INCREASING"
}
Visualization Support: Historical data enables frontend charting libraries (Chart.js) to display trends and predictions.

Model Training & Retraining

Training Features:
  • Scheduled automatic retraining
  • Manual retraining with date ranges
  • Feature engineering pipelines
  • Model versioning with joblib
  • Training metrics logging
Retrain API:
POST /v1/ml/retrain
Content-Type: application/json

{
  "startDate": "2025-01-01",
  "endDate": "2026-03-01",
  "hyperparameters": {
    "n_estimators": 100,
    "max_depth": 10
  }
}

Response:
{
  "modelVersion": "v2.1.0",
  "trainingDate": "2026-03-06T10:30:00Z",
  "metrics": {
    "rmse": 0.045,
    "mae": 0.032,
    "r2_score": 0.89
  },
  "featureImportance": {
    "year": 0.35,
    "mileage": 0.28,
    "make": 0.22,
    "season": 0.15
  }
}

Model Management

Model Metadata:
GET /v1/ml/models/latest

Response:
{
  "version": "v2.1.0",
  "algorithm": "RandomForestRegressor",
  "trainedAt": "2026-03-06T10:30:00Z",
  "trainingSamples": 15234,
  "features": [
    "make", "model", "year", "mileage",
    "price", "season", "economicIndicator"
  ],
  "metrics": {
    "rmse": 0.045,
    "mae": 0.032,
    "r2_score": 0.89
  }
}
Model Persistence:
  • Artifacts stored with joblib serialization
  • Optional PostgreSQL storage for versions
  • Feature snapshots for reproducibility
  • Prediction logging for monitoring

Platform Services

Centralized Configuration

Git-Based Config

Production configuration from Git repository for version control

Native Mode

Development configuration from local filesystem
Configuration Management:
  • Per-service configuration: sgivu-{service}.yml
  • Profile-based: sgivu-{service}-{profile}.yml
  • Global defaults: application.yml
  • Dynamic refresh: Configuration updates without restart (where supported)
  • Label support: Branch/tag-based configuration
Configuration Access:
# Get configuration for a service
GET http://localhost:8888/{application}/{profile}

# Get configuration YAML
GET http://localhost:8888/{application}-{profile}.yml

# Example
GET http://localhost:8888/sgivu-gateway/dev
GET http://localhost:8888/sgivu-gateway-prod.yml

Service Discovery with Eureka

Discovery Features:
  • Automatic service registration
  • Health check monitoring
  • Load balancing support
  • Service metadata
  • Instance deregistration on shutdown
  • Multi-zone support
Eureka Dashboard: Web UI at http://localhost:8761 shows:
  • All registered service instances
  • Instance health status
  • Service metadata
  • Registration timestamps
  • Renewal statistics
Service Resolution: Services use logical names resolved via Eureka:
# Gateway route
uri: lb://sgivu-vehicle

# Resolved to: http://192.168.1.10:8083 (actual instance)

Circuit Breaking & Resilience

Resilience4j Integration:

Circuit Breaker

Prevent cascading failures with automatic circuit breaking

Fallback Routes

Graceful degradation with fallback responses
Circuit Breaker Configuration:
resilience4j:
  circuitbreaker:
    instances:
      vehicleService:
        failure-rate-threshold: 50
        slow-call-rate-threshold: 50
        slow-call-duration-threshold: 2s
        wait-duration-in-open-state: 10s
        sliding-window-size: 10
        minimum-number-of-calls: 5
Circuit Breaker States:
  1. CLOSED: Normal operation, requests flow through
  2. OPEN: Too many failures, requests rejected immediately
  3. HALF_OPEN: Testing if service recovered
Fallback Handling:
# When circuit opens, Gateway returns fallback
GET /v1/vehicles/search

# Fallback response:
{
  "error": "Service temporarily unavailable",
  "fallback": true,
  "message": "Vehicle service is experiencing issues. Please try again later.",
  "statusCode": 503
}

Distributed Tracing

Zipkin Integration:
  • Trace ID propagation across services
  • Span creation for each service call
  • Timing and latency tracking
  • Error tracing
  • Dependency visualization
Tracing Headers:
X-Trace-Id: 1234567890abcdef
X-Span-Id: abcdef1234567890
X-Parent-Span-Id: fedcba0987654321
Zipkin UI Features:
  • Trace timeline visualization
  • Service dependency graph
  • Latency distribution
  • Error rate tracking
  • Search by trace ID, service, or time range
Access Zipkin:
http://localhost:9411

Health Checks & Monitoring

Spring Boot Actuator: All Java services expose health endpoints:
GET /actuator/health

Response:
{
  "status": "UP",
  "components": {
    "db": {
      "status": "UP",
      "details": {
        "database": "PostgreSQL",
        "validationQuery": "isValid()"
      }
    },
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 499963174912,
        "free": 250000000000,
        "threshold": 10485760
      }
    },
    "eureka": {
      "status": "UP"
    }
  }
}
Custom Health Indicators:
  • Database connectivity
  • External API availability
  • S3 bucket access
  • Redis connection
  • Eureka registration status
Metrics Endpoints:
# Metrics
GET /actuator/metrics

# Specific metric
GET /actuator/metrics/jvm.memory.used
GET /actuator/metrics/http.server.requests

Frontend Features

Angular 21 SPA

Responsive Design

Bootstrap 5 responsive layout for desktop and mobile

Interactive Charts

Chart.js integration for data visualization

Reactive Forms

Angular reactive forms with validation

Lazy Loading

Module lazy loading for performance
Key Frontend Features:
  • Dashboard: Overview with key metrics and charts
  • Vehicle Management: Search, create, edit vehicles with image upload
  • Client Management: Person and company client forms
  • Contract Management: Create and view purchase/sale contracts
  • User Management: Admin interface for users and roles
  • Authentication: OAuth2/OIDC integration via Gateway
  • Session Management: Automatic token refresh
  • Error Handling: Global error interceptor
  • Loading States: Skeleton screens and spinners
UI Components:
  • Bootstrap 5 styling
  • Bootstrap Icons
  • Custom form validators
  • Reusable components (tables, modals, cards)
  • Pagination components
  • File upload with progress

Database Features

Flyway Migrations

Version-Controlled Schema:
src/main/resources/db/migration/
├── V1__initial_schema.sql
├── V2__add_vehicle_images.sql
├── V3__add_contract_status.sql
└── R__seed_data.sql (repeatable)
Migration Features:
  • Automatic execution on startup
  • Version tracking in flyway_schema_history table
  • Rollback support (via scripts)
  • Repeatable migrations for seed data
  • Checksum validation

Database Per Service

Isolation: Each microservice has its own database:
  • Data Isolation: Service owns its data schema
  • Independent Scaling: Scale databases independently
  • Technology Freedom: Different services can use different DB technologies
  • Fault Isolation: Database failure affects only one service

PostgreSQL Features

  • Indexes: Optimized queries with strategic indexes
  • Constraints: Foreign keys, unique constraints, check constraints
  • JSON Support: JSONB columns for flexible data
  • Full-Text Search: Text search capabilities
  • Audit Columns: created_at, updated_at timestamps

Docker & Deployment

Containerization

All services are containerized with multi-stage Docker builds for optimal image size.
Docker Features:
  • Multi-stage builds (build → runtime)
  • Minimal base images (Alpine, Distroless)
  • Non-root users for security
  • Health checks in Dockerfile
  • Build scripts for automation
Example Multi-Stage Build:
# Stage 1: Build
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /workspace
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
RUN ./mvnw dependency:go-offline
COPY src src
RUN ./mvnw package -DskipTests

# Stage 2: Runtime
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=build /workspace/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Docker Compose

Development Stack:
cd infra/compose/sgivu-docker-compose
./run.bash --dev
Stack Components:
  • All microservices
  • PostgreSQL (with init scripts)
  • Redis
  • Zipkin (optional)
  • Nginx (optional)
Environment Configuration:
# .env.example
SPRING_PROFILES_ACTIVE=dev
REDIS_PASSWORD=dev-password
POSTGRES_PASSWORD=dev-password
SERVICE_INTERNAL_SECRET_KEY=dev-internal-key

Build & Push Automation

Orchestrated Build:
cd infra/compose/sgivu-docker-compose
./build-and-push-images.bash
This script:
  1. Builds all service Docker images
  2. Tags with versions
  3. Pushes to Docker registry
  4. Updates Docker Compose files

Next Steps

API Reference

Explore detailed API documentation

Deployment Guide

Learn how to deploy to production

Getting Started

Set up your development environment
For questions or issues, check the troubleshooting section in each service’s README or open an issue on GitHub.

Build docs developers (and LLMs) love