Files
motovaultpro/backend/src/features/fuel-logs/README.md
2025-08-23 10:20:03 -05:00

6.0 KiB

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

POST /api/fuel-logs
{
  "vehicleId": "uuid-vehicle-id",
  "date": "2024-01-15",
  "odometer": 52000,
  "gallons": 12.5,
  "pricePerGallon": 3.299,
  "totalCost": 41.24,
  "station": "Shell Station",
  "location": "123 Main St, City, ST",
  "notes": "Full tank, premium gas"
}

Response (201):
{
  "id": "uuid-here",
  "userId": "user-id",
  "vehicleId": "uuid-vehicle-id", 
  "date": "2024-01-15",
  "odometer": 52000,
  "gallons": 12.5,
  "pricePerGallon": 3.299,
  "totalCost": 41.24,
  "station": "Shell Station",
  "location": "123 Main St, City, ST",
  "notes": "Full tank, premium gas",
  "mpg": 28.4, // Auto-calculated from previous log
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

Get Vehicle Statistics

GET /api/fuel-logs/vehicle/:vehicleId/stats

Response (200):
{
  "totalLogs": 15,
  "totalGallons": 187.5,
  "totalCost": 618.45,
  "averageMpg": 29.2,
  "averagePricePerGallon": 3.299,
  "lastFillUp": "2024-01-15",
  "milesTracked": 5475
}

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
├── domain/                # Business logic
│   ├── fuel-logs.service.ts
│   └── fuel-logs.types.ts
├── data/                  # Database layer
│   └── fuel-logs.repository.ts
├── migrations/            # Feature schema
│   └── 001_create_fuel_logs_table.sql
├── tests/                 # All tests
│   ├── unit/
│   │   └── fuel-logs.service.test.ts
│   └── integration/
│       └── fuel-logs.integration.test.ts
└── docs/                  # Additional docs

Key Features

MPG Calculation

  • Auto-calculation: Computes MPG based on odometer difference from previous log
  • First Entry: No MPG for first fuel log (no baseline)
  • Accuracy: Requires consistent odometer readings
  • Validation: Ensures odometer readings increase over time

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)

MPG Calculation Logic

  • Formula: (Current Odometer - Previous Odometer) / Gallons
  • Baseline: Requires at least 2 fuel logs for calculation
  • Edge Cases: Handles first log, odometer resets, missing data

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)

  • Key: fuel-logs:user:{userId}
  • TTL: 300 seconds (5 minutes)
  • Invalidation: On create, update, delete

Vehicle Statistics (15 minutes)

  • Key: fuel-stats:vehicle:{vehicleId}
  • TTL: 900 seconds (15 minutes)
  • Rationale: Stats change less frequently than individual logs

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

# All fuel log tests
npm test -- features/fuel-logs

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

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

# With coverage
npm test -- 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

# Run migrations
make migrate

# Start development environment
make dev

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

# Open container shell
make shell-backend

# Inside container - run feature tests
npm test -- features/fuel-logs