Homepage Redesign

This commit is contained in:
Eric Gullickson
2025-11-03 14:06:54 -06:00
parent 54d97a98b5
commit eeb20543fa
71 changed files with 3925 additions and 1340 deletions

View File

@@ -0,0 +1,379 @@
# Platform Feature Capsule
## Quick Summary (50 tokens)
Extensible platform service for vehicle hierarchical data lookups and VIN decoding. Replaces Python FastAPI platform service. PostgreSQL-first with vPIC fallback, Redis caching (6hr vehicle data, 7-day VIN), circuit breaker pattern for resilience.
## API Endpoints
### Vehicle Hierarchical Data
- `GET /api/platform/years` - Get available model years (distinct, descending)
- `GET /api/platform/makes?year={year}` - Get makes for specific year
- `GET /api/platform/models?year={year}&make_id={id}` - Get models for year and make
- `GET /api/platform/trims?year={year}&model_id={id}` - Get trims for year and model
- `GET /api/platform/engines?year={year}&model_id={id}&trim_id={id}` - Get engines for trim
### VIN Decoding
- `GET /api/platform/vehicle?vin={vin}` - Decode VIN to vehicle details
## Authentication
- All platform endpoints require valid JWT (Auth0)
## Request/Response Examples
### Get Years
```json
GET /api/platform/years
Response (200):
[2024, 2023, 2022, 2021, ...]
```
### Get Makes for Year
```json
GET /api/platform/makes?year=2024
Response (200):
{
"makes": [
{"id": 1, "name": "Honda"},
{"id": 2, "name": "Toyota"},
{"id": 3, "name": "Ford"}
]
}
```
### Get Models for Make/Year
```json
GET /api/platform/models?year=2024&make_id=1
Response (200):
{
"models": [
{"id": 101, "name": "Civic"},
{"id": 102, "name": "Accord"},
{"id": 103, "name": "CR-V"}
]
}
```
### Decode VIN
```json
GET /api/platform/vehicle?vin=1HGCM82633A123456
Response (200):
{
"vin": "1HGCM82633A123456",
"success": true,
"result": {
"make": "Honda",
"model": "Accord",
"year": 2003,
"trim_name": "LX",
"engine_description": "2.4L I4",
"transmission_description": "5-Speed Automatic",
"horsepower": 160,
"torque": 161,
"top_speed": null,
"fuel": "Gasoline",
"confidence_score": 0.95,
"vehicle_type": "Passenger Car"
}
}
```
### VIN Decode Error
```json
GET /api/platform/vehicle?vin=INVALID
Response (400):
{
"vin": "INVALID",
"success": false,
"result": null,
"error": "VIN must be exactly 17 characters"
}
```
## Feature Architecture
### Complete Self-Contained Structure
```
platform/
├── README.md # This file
├── index.ts # Public API exports
├── api/ # HTTP layer
│ ├── platform.controller.ts
│ └── platform.routes.ts
├── domain/ # Business logic
│ ├── vehicle-data.service.ts
│ ├── vin-decode.service.ts
│ └── platform-cache.service.ts
├── data/ # Database and external APIs
│ ├── vehicle-data.repository.ts
│ └── vpic-client.ts
├── models/ # DTOs
│ ├── requests.ts
│ └── responses.ts
├── tests/ # All tests
│ ├── unit/
│ └── integration/
└── docs/ # Additional docs
```
## Key Features
### VIN Decoding Strategy
1. **Cache First**: Check Redis (7-day TTL for success, 1-hour for failures)
2. **PostgreSQL**: Use `vehicles.f_decode_vin()` function for high-confidence decode
3. **vPIC Fallback**: NHTSA vPIC API via circuit breaker (5s timeout, 50% error threshold)
4. **Graceful Degradation**: Return meaningful errors when all sources fail
### Circuit Breaker Pattern
- **Library**: opossum
- **Timeout**: 6 seconds
- **Error Threshold**: 50%
- **Reset Timeout**: 30 seconds
- **Monitoring**: Logs state transitions (open/half-open/close)
### Hierarchical Vehicle Data
- **PostgreSQL Queries**: Normalized schema (vehicles.make, vehicles.model, etc.)
- **Caching**: 6-hour TTL for all dropdown data
- **Performance**: < 100ms response times via caching
- **Validation**: Year (1950-2100), positive integer IDs
### Database Schema
- **Uses Existing Schema**: `vehicles` schema in PostgreSQL
- **Tables**: make, model, model_year, trim, engine, trim_engine
- **Function**: `vehicles.f_decode_vin(vin text)` for VIN decoding
- **No Migrations**: Uses existing platform database structure
### Caching Strategy
#### Vehicle Data (6 hours)
- **Keys**: `mvp:platform:vehicle-data:{type}:{params}`
- **Examples**:
- `mvp:platform:years`
- `mvp:platform:vehicle-data:makes:2024`
- `mvp:platform:vehicle-data:models:2024:1`
- **TTL**: 21600 seconds (6 hours)
- **Invalidation**: Natural expiration via TTL
#### VIN Decode (7 days success, 1 hour failure)
- **Keys**: `mvp:platform:vin-decode:{VIN}`
- **Examples**: `mvp:platform:vin-decode:1HGCM82633A123456`
- **TTL**: 604800 seconds (7 days) for success, 3600 seconds (1 hour) for failures
- **Invalidation**: Natural expiration via TTL
## Business Rules
### VIN Validation
- Must be exactly 17 characters
- Cannot contain letters I, O, or Q
- Must be alphanumeric
- Auto-uppercase normalization
### Query Parameter Validation
- **Year**: Integer between 1950 and 2100
- **IDs**: Positive integers (make_id, model_id, trim_id)
- **VIN**: 17 alphanumeric characters (no I, O, Q)
## Dependencies
### Internal Core Services
- `core/config/database` - PostgreSQL pool
- `core/config/redis` - Redis cache service
- `core/auth` - JWT authentication middleware
- `core/logging` - Winston structured logging
### External APIs
- **NHTSA vPIC**: https://vpic.nhtsa.dot.gov/api
- VIN decoding fallback
- 5-second timeout
- Circuit breaker protected
- Free public API
### Database Schema
- **vehicles.make** - Vehicle manufacturers
- **vehicles.model** - Vehicle models
- **vehicles.model_year** - Year-specific models
- **vehicles.trim** - Model trims
- **vehicles.engine** - Engine configurations
- **vehicles.trim_engine** - Trim-engine relationships
- **vehicles.f_decode_vin(text)** - VIN decode function
### NPM Packages
- `opossum` - Circuit breaker implementation
- `axios` - HTTP client for vPIC API
- `zod` - Request validation schemas
## Performance Optimizations
### Caching Strategy
- **6-hour TTL**: Vehicle data rarely changes
- **7-day TTL**: VIN decode results are immutable
- **1-hour TTL**: Failed VIN decode (prevent repeated failures)
- **Cache Prefix**: `mvp:platform:` for isolation
### Circuit Breaker
- Prevents cascading failures to vPIC API
- 30-second cooldown after opening
- Automatic recovery via half-open state
- Detailed logging for monitoring
### Database Optimization
- Uses existing indexes on vehicles schema
- Prepared statements via node-postgres
- Connection pooling (max 10 connections)
## Error Handling
### Client Errors (4xx)
- `400` - Invalid VIN format, validation errors
- `401` - Missing or invalid JWT token
- `404` - VIN not found in database or API
- `503` - vPIC API unavailable (circuit breaker open)
### Server Errors (5xx)
- `500` - Database errors, unexpected failures
- Graceful degradation when external APIs unavailable
- Detailed logging without exposing internal details
### Error Response Format
```json
{
"vin": "1HGCM82633A123456",
"success": false,
"result": null,
"error": "VIN not found in database and external API unavailable"
}
```
## Extensibility Design
### Future Lookup Types
The platform feature is designed to accommodate additional lookup types beyond vehicle data:
**Current**: Vehicle hierarchical data, VIN decoding
**Future Examples**:
- Part number lookups
- Service bulletins
- Recall information
- Maintenance schedules
- Tire specifications
- Paint codes
### Extension Pattern
1. Create new service in `domain/` (e.g., `part-lookup.service.ts`)
2. Add repository in `data/` if database queries needed
3. Add external client in `data/` if API integration needed
4. Add routes in `api/platform.routes.ts`
5. Add validation schemas in `models/requests.ts`
6. Add response types in `models/responses.ts`
7. Update controller with new methods
## Testing
### Unit Tests
- `vehicle-data.service.test.ts` - Business logic with mocked dependencies
- `vin-decode.service.test.ts` - VIN decode logic with mocked API
- `vpic-client.test.ts` - vPIC client with mocked HTTP
- `platform-cache.service.test.ts` - Cache operations
### Integration Tests
- `platform.integration.test.ts` - Complete API workflow with test database
### Run Tests
```bash
# All platform tests
npm test -- features/platform
# Unit tests only
npm test -- features/platform/tests/unit
# Integration tests only
npm test -- features/platform/tests/integration
# With coverage
npm test -- features/platform --coverage
```
## Migration from Python Service
### What Changed
- **Language**: Python FastAPI -> TypeScript Fastify
- **Feature Name**: "vehicles" -> "platform" (extensibility)
- **API Routes**: `/vehicles/*` -> `/api/platform/*`
- **VIN Decode**: Kept and migrated (PostgreSQL + vPIC fallback)
- **Caching**: Redis implementation adapted to TypeScript
- **Circuit Breaker**: Python timeout -> opossum circuit breaker
### What Stayed the Same
- Database schema (vehicles.*)
- Cache TTLs (6hr vehicle data, 7-day VIN)
- VIN validation logic
- Hierarchical query structure
- Response formats
### Deprecation Plan
1. Deploy TypeScript platform feature
2. Update frontend to use `/api/platform/*` endpoints
3. Monitor traffic to Python service
4. Deprecate Python service when traffic drops to zero
5. Remove Python container from docker-compose
## Development Commands
```bash
# Start environment
make start
# View feature logs
make logs-backend | grep platform
# Open container shell
make shell-backend
# Inside container - run feature tests
npm test -- features/platform
# Type check
npm run type-check
# Lint
npm run lint
```
## Future Considerations
### Potential Enhancements
- Batch VIN decode endpoint (decode multiple VINs)
- Admin endpoint to invalidate cache patterns
- VIN decode history tracking
- Alternative VIN decode APIs (CarMD, Edmunds)
- Real-time vehicle data updates
- Part number cross-reference lookups
- Service bulletin integration
- Recall information integration
### Performance Monitoring
- Track cache hit rates
- Monitor circuit breaker state
- Log slow queries (> 200ms)
- Alert on high error rates
- Dashboard for vPIC API health
## Related Features
### Vehicles Feature
- **Path**: `backend/src/features/vehicles/`
- **Relationship**: Consumes platform VIN decode endpoint
- **Integration**: Uses `/api/platform/vehicle?vin={vin}` for VIN decode
### Frontend Integration
- **Dropdown Components**: Use hierarchical vehicle data endpoints
- **VIN Scanner**: Use VIN decode endpoint for auto-population
- **Vehicle Forms**: Leverage platform data for validation
---
**Platform Feature**: Extensible foundation for vehicle data and future platform capabilities. Production-ready with PostgreSQL, Redis caching, circuit breaker resilience, and comprehensive error handling.