# Vehicles Feature Capsule ## Quick Summary (50 tokens) Primary entity for vehicle management with VIN decoding via NHTSA vPIC API. Handles CRUD operations, automatic vehicle data population, user ownership validation, caching strategy (VIN lookups: 30 days, user lists: 5 minutes). Foundation for fuel-logs and maintenance features. ## API Endpoints - `POST /api/vehicles` - Create new vehicle with VIN decoding - `GET /api/vehicles` - List all user's vehicles (cached 5 min) - `GET /api/vehicles/:id` - Get specific vehicle - `PUT /api/vehicles/:id` - Update vehicle details - `DELETE /api/vehicles/:id` - Soft delete vehicle ## Authentication Required All endpoints require valid JWT token with user context. ## Request/Response Examples ### Create Vehicle ```json POST /api/vehicles { "vin": "1HGBH41JXMN109186", "nickname": "My Honda", "color": "Blue", "licensePlate": "ABC123", "odometerReading": 50000 } Response (201): { "id": "uuid-here", "userId": "user-id", "vin": "1HGBH41JXMN109186", "make": "Honda", // Auto-decoded "model": "Civic", // Auto-decoded "year": 2021, // Auto-decoded "nickname": "My Honda", "color": "Blue", "licensePlate": "ABC123", "odometerReading": 50000, "isActive": true, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` ## Feature Architecture ### Complete Self-Contained Structure ``` vehicles/ ├── README.md # This file ├── index.ts # Public API exports ├── api/ # HTTP layer │ ├── vehicles.controller.ts │ ├── vehicles.routes.ts │ └── vehicles.validation.ts ├── domain/ # Business logic │ ├── vehicles.service.ts │ └── vehicles.types.ts ├── data/ # Database layer │ └── vehicles.repository.ts ├── migrations/ # Feature schema │ └── 001_create_vehicles_tables.sql ├── external/ # External APIs │ └── vpic/ │ ├── vpic.client.ts │ └── vpic.types.ts ├── tests/ # All tests │ ├── unit/ │ │ ├── vehicles.service.test.ts │ │ └── vpic.client.test.ts │ └── integration/ │ └── vehicles.integration.test.ts └── docs/ # Additional docs ``` ## Key Features ### 🔍 Automatic VIN Decoding - **External API**: NHTSA vPIC (Vehicle Product Information Catalog) - **Caching**: 30-day Redis cache for VIN lookups - **Fallback**: Graceful handling of decode failures - **Validation**: 17-character VIN format validation ### 🏗️ Database Schema - **Primary Table**: `vehicles` with soft delete - **Cache Table**: `vin_cache` for external API results - **Indexes**: Optimized for user queries and VIN lookups - **Constraints**: Unique VIN per user, proper foreign keys ### 🚀 Performance Optimizations - **Redis Caching**: User vehicle lists cached for 5 minutes - **VIN Cache**: 30-day persistent cache in PostgreSQL - **Indexes**: Strategic database indexes for fast queries - **Soft Deletes**: Maintains referential integrity ## Business Rules ### VIN Validation - Must be exactly 17 characters - Cannot contain letters I, O, or Q - Must pass basic checksum validation - Auto-populates make, model, year from vPIC API ### User Ownership - Each user can have multiple vehicles - Same VIN cannot be registered twice by same user - All operations validate user ownership - Soft delete preserves data for audit trail ## Dependencies ### Internal Core Services - `core/auth` - JWT authentication middleware - `core/config` - Database pool, Redis cache - `core/logging` - Structured logging with Winston - `shared-minimal/utils` - Pure validation utilities ### External Services - **NHTSA vPIC API** - VIN decoding service - **PostgreSQL** - Primary data storage - **Redis** - Caching layer ### Database Tables - `vehicles` - Primary vehicle data - `vin_cache` - External API response cache ## Caching Strategy ### VIN Decode Cache (30 days) - **Key**: `vpic:vin:{vin}` - **TTL**: 2,592,000 seconds (30 days) - **Rationale**: Vehicle specifications never change ### User Vehicle List (5 minutes) - **Key**: `vehicles:user:{userId}` - **TTL**: 300 seconds (5 minutes) - **Invalidation**: On create, update, delete ## Testing ### Unit Tests - `vehicles.service.test.ts` - Business logic with mocked dependencies - `vpic.client.test.ts` - External API client with mocked HTTP ### Integration Tests - `vehicles.integration.test.ts` - Complete API workflow with test database ### Run Tests ```bash # All vehicle tests npm test -- features/vehicles # Unit tests only npm test -- features/vehicles/tests/unit # Integration tests only npm test -- features/vehicles/tests/integration # With coverage npm test -- features/vehicles --coverage ``` ## Error Handling ### Client Errors (4xx) - `400` - Invalid VIN format, validation errors - `401` - Missing or invalid JWT token - `403` - User not authorized for vehicle - `404` - Vehicle not found - `409` - Duplicate VIN for user ### Server Errors (5xx) - `500` - Database connection, VIN API failures - Graceful degradation when vPIC API unavailable ## Future Considerations ### Dependent Features - **fuel-logs** - Will reference `vehicle_id` - **maintenance** - Will reference `vehicle_id` - Both features depend on vehicles as primary entity ### Potential Enhancements - Vehicle image uploads (MinIO integration) - VIN decode webhook for real-time updates - Vehicle value estimation integration - Maintenance scheduling based on vehicle age/mileage ## Development Commands ```bash # Run migrations make migrate # Start development environment make dev # View feature logs make logs-backend | grep vehicles # Open container shell make shell-backend # Inside container - run feature tests npm test -- features/vehicles ```