# Fuel Logs Feature Capsule

## Quick Summary (50 tokens)
Tracks fuel purchases and calculates MPG efficiency. Depends on vehicles feature for vehicle_id. Provides analytics for fuel costs, consumption trends, and efficiency metrics. Cached user logs for 5 minutes. Supports CRUD operations with user ownership validation.

## API Endpoints
- `POST /api/fuel-logs` - Create new fuel log entry
- `GET /api/fuel-logs` - List all user's fuel logs (cached 5 min)
- `GET /api/fuel-logs/:id` - Get specific fuel log
- `PUT /api/fuel-logs/:id` - Update fuel log details
- `DELETE /api/fuel-logs/:id` - Delete fuel log
- `GET /api/fuel-logs/vehicle/:vehicleId` - Get fuel logs for specific vehicle
- `GET /api/fuel-logs/vehicle/:vehicleId/stats` - Get fuel efficiency statistics

## Authentication Required
All endpoints require valid JWT token with user context.

## Request/Response Examples

### Create Fuel Log
```json
POST /api/fuel-logs
{
  "vehicleId": "uuid-vehicle-id",
  "dateTime": "2024-01-15T10:30:00Z",
  "odometerReading": 52000,
  "tripDistance": 325,
  "fuelType": "gasoline",
  "fuelGrade": "premium",
  "fuelUnits": 12.5,
  "costPerUnit": 3.299,
  "locationData": "123 Main St, City, ST",
  "notes": "Full tank, premium gas"
}

Response (201):
{
  "id": "uuid-here",
  "userId": "user-id",
  "vehicleId": "uuid-vehicle-id",
  "dateTime": "2024-01-15T10:30:00Z",
  "odometerReading": 52000,
  "tripDistance": 325,
  "fuelType": "gasoline",
  "fuelGrade": "premium",
  "fuelUnits": 12.5,
  "costPerUnit": 3.299,
  "totalCost": 41.24,
  "locationData": "123 Main St, City, ST",
  "notes": "Full tank, premium gas",
  "efficiency": 28.4, // Auto-calculated from distance/fuelUnits
  "efficiencyLabel": "MPG",
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}
```

### Get Vehicle Statistics
```json
GET /api/fuel-logs/vehicle/:vehicleId/stats

Response (200):
{
  "logCount": 15,
  "totalFuelUnits": 187.5,
  "totalCost": 618.45,
  "averageCostPerUnit": 3.299,
  "totalDistance": 5475,
  "averageEfficiency": 29.2,
  "unitLabels": {
    "distance": "miles",
    "fuelUnits": "gallons",
    "efficiencyUnits": "MPG"
  }
}
```

## Feature Architecture

### Complete Self-Contained Structure
```
fuel-logs/
├── README.md              # This file
├── index.ts               # Public API exports
├── api/                   # HTTP layer
│   ├── fuel-logs.controller.ts
│   ├── fuel-logs.routes.ts
│   ├── fuel-logs.validators.ts
│   └── fuel-grade.controller.ts    # Fuel grade lookup endpoints
├── domain/                # Business logic
│   ├── fuel-logs.service.ts        # Core fuel log operations
│   ├── fuel-logs.types.ts          # Type definitions
│   ├── fuel-grade.service.ts       # Fuel grade management
│   ├── efficiency-calculation.service.ts  # MPG/L per 100km calculations
│   ├── unit-conversion.service.ts  # Imperial/metric conversions
│   └── enhanced-validation.service.ts    # Complex validation rules
├── data/                  # Database layer
│   └── fuel-logs.repository.ts
├── external/              # External service integrations
│   └── user-settings.service.ts    # User preference lookups
├── migrations/            # Feature schema
│   ├── 001_create_fuel_logs_table.sql
│   ├── 002_enhance_fuel_logs_schema.sql
│   ├── 003_drop_mpg_column.sql
│   └── 004_relax_odometer_and_trip_precision.sql
├── tests/                 # All tests
│   ├── unit/
│   │   └── fuel-logs.service.test.ts
│   └── integration/
│       └── fuel-logs.integration.test.ts
└── fixtures/              # Test fixtures (empty - uses inline mocks)
```

## Key Features

### Efficiency Calculation (MPG/L equivalent)
- **Auto-calculation**: Computes efficiency based on trip distance or odometer difference
- **Unit System**: Respects user preference (imperial = MPG, metric = L/100km)
- **First Entry**: No efficiency for first fuel log (no baseline)
- **Accuracy**: Requires either trip distance or consistent odometer readings
- **Validation**: Ensures positive values and proper fuel unit tracking

### Database Schema
- **Primary Table**: `fuel_logs` with foreign key to vehicles
- **Indexes**: Optimized for user queries, vehicle lookups, date ranges
- **Constraints**: Valid vehicle_id, positive gallons/cost, future dates allowed

### Performance Optimizations
- **Redis Caching**: User fuel logs cached for 5 minutes
- **Indexes**: Strategic database indexes for fast queries
- **Efficient Queries**: Single query for MPG calculations

## Business Rules

### Data Validation
- **Vehicle Ownership**: User must own the vehicle
- **Positive Values**: Gallons, price, cost must be > 0
- **Odometer Logic**: Reading must be >= previous reading for same vehicle
- **Date Validation**: No fuel logs in future (beyond today)

### Efficiency Calculation Logic
- **Primary Formula**: Trip Distance / Fuel Units (gives MPG for imperial, L/100km for metric)
- **Fallback Formula**: (Current Odometer - Previous Odometer) / Fuel Units
- **Unit Conversion**: Automatically converts between imperial and metric based on user preference
- **Edge Cases**: Handles first log, odometer resets, missing trip distance data
- **Aggregation**: Vehicle statistics compute average efficiency across all logs

## 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

### Feature Dependencies
- **vehicles** - REQUIRED: vehicle_id foreign key relationship
- Must have valid vehicle before creating fuel logs

### Database Tables
- `fuel_logs` - Primary fuel tracking data
- `vehicles` - Referenced via vehicle_id foreign key

## Caching Strategy

### User Fuel Logs (5 minutes per unit system)
- **Key**: `fuel-logs:user:{userId}:{unitSystem}`
- **TTL**: 300 seconds (5 minutes)
- **Invalidation**: On create, update, delete
- **Unit System**: Cache keys include `imperial` or `metric` for user preference

### Vehicle Fuel Logs (5 minutes per unit system)
- **Key**: `fuel-logs:vehicle:{vehicleId}:{unitSystem}`
- **TTL**: 300 seconds (5 minutes)
- **Invalidation**: On create, update, delete

### Vehicle Statistics
- **Strategy**: Fresh queries on each request (no caching)
- **Calculation**: Real-time aggregation of all logs, efficiency calculations
- **Performance**: Optimized query patterns for vehicle-specific lookups

## Testing

### Unit Tests
- `fuel-logs.service.test.ts` - Business logic with mocked dependencies
- Tests MPG calculation logic
- Tests vehicle ownership validation
- Tests error handling paths

### Integration Tests
- `fuel-logs.integration.test.ts` - Complete API workflow with test database

### Run Tests
```bash
# All fuel log tests
npm test -- --testPathPattern=src/features/fuel-logs

# Unit tests only
npm test -- --testPathPattern=src/features/fuel-logs/tests/unit

# Integration tests only
npm test -- --testPathPattern=src/features/fuel-logs/tests/integration

# With coverage
npm test -- --testPathPattern=src/features/fuel-logs --coverage
```

## Error Handling

### Client Errors (4xx)
- `400` - Invalid data, negative values, validation errors
- `401` - Missing or invalid JWT token
- `403` - User not authorized for vehicle/fuel log
- `404` - Vehicle or fuel log not found
- `409` - Odometer reading conflicts

### Server Errors (5xx)
- `500` - Database connection failures
- Graceful error responses with meaningful messages

## Development Commands

```bash
# Run migrations
make migrate

# Start environment
make start

# View feature logs
make logs-backend | grep fuel-logs

# Open container shell
make shell-backend

# Inside container - run feature tests
npm test -- --testPathPattern=src/features/fuel-logs
```
