From b0d79a26ae78fb9bd86b22dec2af10c17de23afd Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Mon, 12 Jan 2026 19:56:30 -0600 Subject: [PATCH 01/11] feat: add TCO fields migration (refs #15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add database columns for Total Cost of Ownership: - purchase_price, purchase_date - insurance_cost, insurance_interval - registration_cost, registration_interval - tco_enabled toggle Includes CHECK constraints for interval values and non-negative costs. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../migrations/006_add_tco_fields.sql | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 backend/src/features/vehicles/migrations/006_add_tco_fields.sql diff --git a/backend/src/features/vehicles/migrations/006_add_tco_fields.sql b/backend/src/features/vehicles/migrations/006_add_tco_fields.sql new file mode 100644 index 0000000..0f1e993 --- /dev/null +++ b/backend/src/features/vehicles/migrations/006_add_tco_fields.sql @@ -0,0 +1,33 @@ +-- Migration: Add TCO (Total Cost of Ownership) fields to vehicles table +-- Issue: #15 + +ALTER TABLE vehicles + ADD COLUMN IF NOT EXISTS purchase_price DECIMAL(12,2), + ADD COLUMN IF NOT EXISTS purchase_date DATE, + ADD COLUMN IF NOT EXISTS insurance_cost DECIMAL(10,2), + ADD COLUMN IF NOT EXISTS insurance_interval VARCHAR(20), + ADD COLUMN IF NOT EXISTS registration_cost DECIMAL(10,2), + ADD COLUMN IF NOT EXISTS registration_interval VARCHAR(20), + ADD COLUMN IF NOT EXISTS tco_enabled BOOLEAN DEFAULT false; + +-- Add CHECK constraints to enforce valid interval values +ALTER TABLE vehicles + ADD CONSTRAINT chk_insurance_interval + CHECK (insurance_interval IS NULL OR insurance_interval IN ('monthly', 'semi_annual', 'annual')); + +ALTER TABLE vehicles + ADD CONSTRAINT chk_registration_interval + CHECK (registration_interval IS NULL OR registration_interval IN ('monthly', 'semi_annual', 'annual')); + +-- Add CHECK constraints for non-negative costs +ALTER TABLE vehicles + ADD CONSTRAINT chk_purchase_price_non_negative + CHECK (purchase_price IS NULL OR purchase_price >= 0); + +ALTER TABLE vehicles + ADD CONSTRAINT chk_insurance_cost_non_negative + CHECK (insurance_cost IS NULL OR insurance_cost >= 0); + +ALTER TABLE vehicles + ADD CONSTRAINT chk_registration_cost_non_negative + CHECK (registration_cost IS NULL OR registration_cost >= 0); -- 2.49.1 From 8517b1ded2e0725e72fb7680bbacd36af226897e Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Mon, 12 Jan 2026 19:58:59 -0600 Subject: [PATCH 02/11] feat: add TCO types and repository updates (refs #15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add CostInterval type and PAYMENTS_PER_YEAR constant - Add 7 TCO fields to Vehicle, CreateVehicleRequest, UpdateVehicleRequest - Update VehicleResponse and Body types - Update mapRow() with snake_case to camelCase mapping - Update create(), update(), batchInsert() for new fields - Add Zod validation for TCO fields with interval enum 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../vehicles/api/vehicles.validation.ts | 19 +++++ .../vehicles/data/vehicles.repository.ts | 73 ++++++++++++++++--- .../vehicles/domain/vehicles.types.ts | 57 +++++++++++++++ 3 files changed, 140 insertions(+), 9 deletions(-) diff --git a/backend/src/features/vehicles/api/vehicles.validation.ts b/backend/src/features/vehicles/api/vehicles.validation.ts index e2538c4..6e8755c 100644 --- a/backend/src/features/vehicles/api/vehicles.validation.ts +++ b/backend/src/features/vehicles/api/vehicles.validation.ts @@ -6,6 +6,9 @@ import { z } from 'zod'; import { isValidVIN } from '../../../shared-minimal/utils/validators'; +// Cost interval enum for TCO recurring costs +const costIntervalSchema = z.enum(['monthly', 'semi_annual', 'annual']); + export const createVehicleSchema = z.object({ vin: z.string() .length(17, 'VIN must be exactly 17 characters') @@ -14,6 +17,14 @@ export const createVehicleSchema = z.object({ color: z.string().min(1).max(50).optional(), licensePlate: z.string().min(1).max(20).optional(), odometerReading: z.number().min(0).max(9999999).optional(), + // TCO fields + purchasePrice: z.number().min(0).max(99999999.99).optional(), + purchaseDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD').optional(), + insuranceCost: z.number().min(0).max(9999999.99).optional(), + insuranceInterval: costIntervalSchema.optional(), + registrationCost: z.number().min(0).max(9999999.99).optional(), + registrationInterval: costIntervalSchema.optional(), + tcoEnabled: z.boolean().optional(), }); export const updateVehicleSchema = z.object({ @@ -30,6 +41,14 @@ export const updateVehicleSchema = z.object({ color: z.string().min(1).max(50).optional(), licensePlate: z.string().min(1).max(20).optional(), odometerReading: z.number().min(0).max(9999999).optional(), + // TCO fields + purchasePrice: z.number().min(0).max(99999999.99).optional().nullable(), + purchaseDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD').optional().nullable(), + insuranceCost: z.number().min(0).max(9999999.99).optional().nullable(), + insuranceInterval: costIntervalSchema.optional().nullable(), + registrationCost: z.number().min(0).max(9999999.99).optional().nullable(), + registrationInterval: costIntervalSchema.optional().nullable(), + tcoEnabled: z.boolean().optional(), }); export const vehicleIdSchema = z.object({ diff --git a/backend/src/features/vehicles/data/vehicles.repository.ts b/backend/src/features/vehicles/data/vehicles.repository.ts index 3f2df8a..7e98bae 100644 --- a/backend/src/features/vehicles/data/vehicles.repository.ts +++ b/backend/src/features/vehicles/data/vehicles.repository.ts @@ -4,7 +4,7 @@ */ import { Pool } from 'pg'; -import { Vehicle, CreateVehicleRequest, VehicleImageMeta } from '../domain/vehicles.types'; +import { Vehicle, CreateVehicleRequest, VehicleImageMeta, CostInterval } from '../domain/vehicles.types'; export class VehiclesRepository { constructor(private pool: Pool) {} @@ -12,14 +12,16 @@ export class VehiclesRepository { async create(data: CreateVehicleRequest & { userId: string, make?: string, model?: string, year?: number }): Promise { const query = ` INSERT INTO vehicles ( - user_id, vin, make, model, year, + user_id, vin, make, model, year, engine, transmission, trim_level, drive_type, fuel_type, - nickname, color, license_plate, odometer_reading + nickname, color, license_plate, odometer_reading, + purchase_price, purchase_date, insurance_cost, insurance_interval, + registration_cost, registration_interval, tco_enabled ) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) RETURNING * `; - + const values = [ data.userId, (data.vin && data.vin.trim().length > 0) ? data.vin.trim() : null, @@ -34,7 +36,14 @@ export class VehiclesRepository { data.nickname, data.color, data.licensePlate, - data.odometerReading || 0 + data.odometerReading || 0, + data.purchasePrice ?? null, + data.purchaseDate ?? null, + data.insuranceCost ?? null, + data.insuranceInterval ?? null, + data.registrationCost ?? null, + data.registrationInterval ?? null, + data.tcoEnabled ?? false ]; const result = await this.pool.query(query, values); @@ -142,6 +151,35 @@ export class VehiclesRepository { fields.push(`odometer_reading = $${paramCount++}`); values.push(data.odometerReading); } + // TCO fields + if (data.purchasePrice !== undefined) { + fields.push(`purchase_price = $${paramCount++}`); + values.push(data.purchasePrice); + } + if (data.purchaseDate !== undefined) { + fields.push(`purchase_date = $${paramCount++}`); + values.push(data.purchaseDate); + } + if (data.insuranceCost !== undefined) { + fields.push(`insurance_cost = $${paramCount++}`); + values.push(data.insuranceCost); + } + if (data.insuranceInterval !== undefined) { + fields.push(`insurance_interval = $${paramCount++}`); + values.push(data.insuranceInterval); + } + if (data.registrationCost !== undefined) { + fields.push(`registration_cost = $${paramCount++}`); + values.push(data.registrationCost); + } + if (data.registrationInterval !== undefined) { + fields.push(`registration_interval = $${paramCount++}`); + values.push(data.registrationInterval); + } + if (data.tcoEnabled !== undefined) { + fields.push(`tco_enabled = $${paramCount++}`); + values.push(data.tcoEnabled); + } if (fields.length === 0) { return this.findById(id); @@ -193,10 +231,17 @@ export class VehiclesRepository { vehicle.nickname, vehicle.color, vehicle.licensePlate, - vehicle.odometerReading || 0 + vehicle.odometerReading || 0, + vehicle.purchasePrice ?? null, + vehicle.purchaseDate ?? null, + vehicle.insuranceCost ?? null, + vehicle.insuranceInterval ?? null, + vehicle.registrationCost ?? null, + vehicle.registrationInterval ?? null, + vehicle.tcoEnabled ?? false ]; - const placeholder = `($${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++})`; + const placeholder = `($${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++}, $${paramCount++})`; placeholders.push(placeholder); values.push(...vehicleParams); }); @@ -205,7 +250,9 @@ export class VehiclesRepository { INSERT INTO vehicles ( user_id, vin, make, model, year, engine, transmission, trim_level, drive_type, fuel_type, - nickname, color, license_plate, odometer_reading + nickname, color, license_plate, odometer_reading, + purchase_price, purchase_date, insurance_cost, insurance_interval, + registration_cost, registration_interval, tco_enabled ) VALUES ${placeholders.join(', ')} RETURNING * @@ -292,6 +339,14 @@ export class VehiclesRepository { imageFileName: row.image_file_name, imageContentType: row.image_content_type, imageFileSize: row.image_file_size, + // TCO fields + purchasePrice: row.purchase_price ? Number(row.purchase_price) : undefined, + purchaseDate: row.purchase_date, + insuranceCost: row.insurance_cost ? Number(row.insurance_cost) : undefined, + insuranceInterval: row.insurance_interval as CostInterval | undefined, + registrationCost: row.registration_cost ? Number(row.registration_cost) : undefined, + registrationInterval: row.registration_interval as CostInterval | undefined, + tcoEnabled: row.tco_enabled, }; } } diff --git a/backend/src/features/vehicles/domain/vehicles.types.ts b/backend/src/features/vehicles/domain/vehicles.types.ts index 3c14334..8eff5cb 100644 --- a/backend/src/features/vehicles/domain/vehicles.types.ts +++ b/backend/src/features/vehicles/domain/vehicles.types.ts @@ -3,6 +3,15 @@ * @ai-context Core business types, no external dependencies */ +// TCO cost interval types +export type CostInterval = 'monthly' | 'semi_annual' | 'annual'; + +export const PAYMENTS_PER_YEAR: Record = { + monthly: 12, + semi_annual: 2, + annual: 1, +} as const; + export interface Vehicle { id: string; userId: string; @@ -28,6 +37,14 @@ export interface Vehicle { imageFileName?: string; imageContentType?: string; imageFileSize?: number; + // TCO fields + purchasePrice?: number; + purchaseDate?: string; + insuranceCost?: number; + insuranceInterval?: CostInterval; + registrationCost?: number; + registrationInterval?: CostInterval; + tcoEnabled?: boolean; } export interface CreateVehicleRequest { @@ -44,6 +61,14 @@ export interface CreateVehicleRequest { color?: string; licensePlate?: string; odometerReading?: number; + // TCO fields + purchasePrice?: number; + purchaseDate?: string; + insuranceCost?: number; + insuranceInterval?: CostInterval; + registrationCost?: number; + registrationInterval?: CostInterval; + tcoEnabled?: boolean; } export interface UpdateVehicleRequest { @@ -60,6 +85,14 @@ export interface UpdateVehicleRequest { color?: string; licensePlate?: string; odometerReading?: number; + // TCO fields + purchasePrice?: number; + purchaseDate?: string; + insuranceCost?: number; + insuranceInterval?: CostInterval; + registrationCost?: number; + registrationInterval?: CostInterval; + tcoEnabled?: boolean; } export interface VehicleResponse { @@ -82,6 +115,14 @@ export interface VehicleResponse { createdAt: string; updatedAt: string; imageUrl?: string; + // TCO fields + purchasePrice?: number; + purchaseDate?: string; + insuranceCost?: number; + insuranceInterval?: CostInterval; + registrationCost?: number; + registrationInterval?: CostInterval; + tcoEnabled?: boolean; } export interface VehicleImageMeta { @@ -116,6 +157,14 @@ export interface CreateVehicleBody { color?: string; licensePlate?: string; odometerReading?: number; + // TCO fields + purchasePrice?: number; + purchaseDate?: string; + insuranceCost?: number; + insuranceInterval?: CostInterval; + registrationCost?: number; + registrationInterval?: CostInterval; + tcoEnabled?: boolean; } export interface UpdateVehicleBody { @@ -132,6 +181,14 @@ export interface UpdateVehicleBody { color?: string; licensePlate?: string; odometerReading?: number; + // TCO fields + purchasePrice?: number; + purchaseDate?: string; + insuranceCost?: number; + insuranceInterval?: CostInterval; + registrationCost?: number; + registrationInterval?: CostInterval; + tcoEnabled?: boolean; } export interface VehicleParams { -- 2.49.1 From 35fd1782b44ddf44192bd251ae1124c666620d77 Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Mon, 12 Jan 2026 19:59:41 -0600 Subject: [PATCH 03/11] feat: add maintenance cost aggregation for TCO (refs #15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add MaintenanceCostStats interface - Add getVehicleMaintenanceCosts() method to maintenance service - Validates numeric cost values and throws on invalid data 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../maintenance/domain/maintenance.service.ts | 16 +++++++++++++++- .../maintenance/domain/maintenance.types.ts | 6 ++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/backend/src/features/maintenance/domain/maintenance.service.ts b/backend/src/features/maintenance/domain/maintenance.service.ts index 7990ac4..da04b7e 100644 --- a/backend/src/features/maintenance/domain/maintenance.service.ts +++ b/backend/src/features/maintenance/domain/maintenance.service.ts @@ -9,7 +9,8 @@ import type { MaintenanceRecordResponse, MaintenanceScheduleResponse, MaintenanceCategory, - ScheduleType + ScheduleType, + MaintenanceCostStats } from './maintenance.types'; import { validateSubtypes } from './maintenance.types'; import { MaintenanceRepository } from '../data/maintenance.repository'; @@ -63,6 +64,19 @@ export class MaintenanceService { return records.map(r => this.toRecordResponse(r)); } + async getVehicleMaintenanceCosts(vehicleId: string, userId: string): Promise { + const records = await this.repo.findRecordsByVehicleId(vehicleId, userId); + const totalCost = records.reduce((sum, r) => { + if (r.cost === null || r.cost === undefined) return sum; + const cost = Number(r.cost); + if (isNaN(cost)) { + throw new Error(`Invalid cost value for maintenance record ${r.id}`); + } + return sum + cost; + }, 0); + return { totalCost, recordCount: records.length }; + } + async updateRecord(userId: string, id: string, patch: UpdateMaintenanceRecordRequest): Promise { const existing = await this.repo.findRecordById(id, userId); if (!existing) return null; diff --git a/backend/src/features/maintenance/domain/maintenance.types.ts b/backend/src/features/maintenance/domain/maintenance.types.ts index caeeeb5..ce85ac1 100644 --- a/backend/src/features/maintenance/domain/maintenance.types.ts +++ b/backend/src/features/maintenance/domain/maintenance.types.ts @@ -162,6 +162,12 @@ export interface MaintenanceRecordResponse extends MaintenanceRecord { subtypeCount: number; } +// TCO aggregation stats +export interface MaintenanceCostStats { + totalCost: number; + recordCount: number; +} + export interface MaintenanceScheduleResponse extends MaintenanceSchedule { subtypeCount: number; isDueSoon?: boolean; -- 2.49.1 From 381f602e9ffede9d7351e6cfd7f36d1426731da5 Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Mon, 12 Jan 2026 20:01:24 -0600 Subject: [PATCH 04/11] feat: add TCO calculation service (refs #15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add TCOResponse interface - Add getTCO() method aggregating all cost sources - Add normalizeRecurringCost() with division-by-zero guard - Integrate FuelLogsService and MaintenanceService for cost data - Respect user preferences for distance unit and currency 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../vehicles/domain/vehicles.service.ts | 111 +++++++++++++++++- .../vehicles/domain/vehicles.types.ts | 14 +++ 2 files changed, 124 insertions(+), 1 deletion(-) diff --git a/backend/src/features/vehicles/domain/vehicles.service.ts b/backend/src/features/vehicles/domain/vehicles.service.ts index cde91b5..ca8fcaa 100644 --- a/backend/src/features/vehicles/domain/vehicles.service.ts +++ b/backend/src/features/vehicles/domain/vehicles.service.ts @@ -10,7 +10,10 @@ import { CreateVehicleRequest, UpdateVehicleRequest, VehicleResponse, - VehicleImageMeta + VehicleImageMeta, + TCOResponse, + CostInterval, + PAYMENTS_PER_YEAR } from './vehicles.types'; import { logger } from '../../../core/logging/logger'; import { cacheService } from '../../../core/config/redis'; @@ -25,6 +28,10 @@ import { NHTSAClient, NHTSADecodeResponse, DecodedVehicleData, MatchedField } fr import { canAddVehicle, getVehicleLimitConfig } from '../../../core/config/feature-tiers'; import { UserProfileRepository } from '../../user-profile/data/user-profile.repository'; import { SubscriptionTier } from '../../user-profile/domain/user-profile.types'; +import { FuelLogsService } from '../../fuel-logs/domain/fuel-logs.service'; +import { FuelLogsRepository } from '../../fuel-logs/data/fuel-logs.repository'; +import { MaintenanceService } from '../../maintenance/domain/maintenance.service'; +import { UserSettingsService } from '../../fuel-logs/external/user-settings.service'; export class VehicleLimitExceededError extends Error { constructor( @@ -378,6 +385,108 @@ export class VehiclesService { ).catch(err => logger.error('Failed to log vehicle delete audit event', { error: err })); } + async getTCO(id: string, userId: string): Promise { + // Get vehicle and verify ownership + const vehicle = await this.repository.findById(id); + if (!vehicle) { + const err: any = new Error('Vehicle not found'); + err.statusCode = 404; + throw err; + } + if (vehicle.userId !== userId) { + const err: any = new Error('Unauthorized'); + err.statusCode = 403; + throw err; + } + + // Get user preferences for units + const userSettings = await UserSettingsService.getUserSettings(userId); + const distanceUnit = userSettings.unitSystem === 'metric' ? 'km' : 'mi'; + const currencyCode = userSettings.currencyCode || 'USD'; + + // Get fuel costs from fuel-logs service + const fuelLogsRepository = new FuelLogsRepository(this.pool); + const fuelLogsService = new FuelLogsService(fuelLogsRepository); + let fuelCosts = 0; + try { + const fuelStats = await fuelLogsService.getVehicleStats(id, userId); + fuelCosts = fuelStats.totalCost || 0; + } catch { + // Vehicle may have no fuel logs + fuelCosts = 0; + } + + // Get maintenance costs from maintenance service + const maintenanceService = new MaintenanceService(); + let maintenanceCosts = 0; + try { + const maintenanceStats = await maintenanceService.getVehicleMaintenanceCosts(id, userId); + maintenanceCosts = maintenanceStats.totalCost || 0; + } catch { + // Vehicle may have no maintenance records + maintenanceCosts = 0; + } + + // Get fixed costs from vehicle record + const purchasePrice = vehicle.purchasePrice || 0; + + // Normalize recurring costs based on purchase date + const insuranceCosts = this.normalizeRecurringCost( + vehicle.insuranceCost, + vehicle.insuranceInterval, + vehicle.purchaseDate + ); + const registrationCosts = this.normalizeRecurringCost( + vehicle.registrationCost, + vehicle.registrationInterval, + vehicle.purchaseDate + ); + + // Calculate lifetime total + const lifetimeTotal = purchasePrice + insuranceCosts + registrationCosts + fuelCosts + maintenanceCosts; + + // Calculate cost per distance + const odometerReading = vehicle.odometerReading || 0; + const costPerDistance = odometerReading > 0 ? lifetimeTotal / odometerReading : 0; + + return { + vehicleId: id, + purchasePrice, + insuranceCosts, + registrationCosts, + fuelCosts, + maintenanceCosts, + lifetimeTotal, + costPerDistance, + distanceUnit, + currencyCode + }; + } + + private normalizeRecurringCost( + cost: number | null | undefined, + interval: CostInterval | null | undefined, + purchaseDate: string | null | undefined + ): number { + if (!cost || !interval || !purchaseDate) return 0; + + const monthsOwned = Math.max(1, this.calculateMonthsOwned(purchaseDate)); + const paymentsPerYear = PAYMENTS_PER_YEAR[interval]; + if (!paymentsPerYear) { + throw new Error(`Invalid cost interval: ${interval}`); + } + const totalPayments = (monthsOwned / 12) * paymentsPerYear; + return cost * totalPayments; + } + + private calculateMonthsOwned(purchaseDate: string): number { + const purchase = new Date(purchaseDate); + const now = new Date(); + const yearDiff = now.getFullYear() - purchase.getFullYear(); + const monthDiff = now.getMonth() - purchase.getMonth(); + return yearDiff * 12 + monthDiff; + } + async getVehicleRaw(id: string, userId: string): Promise { const vehicle = await this.repository.findById(id); if (!vehicle || vehicle.userId !== userId) { diff --git a/backend/src/features/vehicles/domain/vehicles.types.ts b/backend/src/features/vehicles/domain/vehicles.types.ts index 8eff5cb..b0377a6 100644 --- a/backend/src/features/vehicles/domain/vehicles.types.ts +++ b/backend/src/features/vehicles/domain/vehicles.types.ts @@ -194,3 +194,17 @@ export interface UpdateVehicleBody { export interface VehicleParams { id: string; } + +// TCO (Total Cost of Ownership) response +export interface TCOResponse { + vehicleId: string; + purchasePrice: number; + insuranceCosts: number; + registrationCosts: number; + fuelCosts: number; + maintenanceCosts: number; + lifetimeTotal: number; + costPerDistance: number; + distanceUnit: string; + currencyCode: string; +} -- 2.49.1 From 47de6898cdd09ee1535446a497f18988d3970749 Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Mon, 12 Jan 2026 20:02:15 -0600 Subject: [PATCH 05/11] feat: add TCO API endpoint (refs #15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add GET /api/vehicles/:id/tco route - Add getTCO controller method with error handling - Returns 200 with TCO data, 404 for not found, 403 for unauthorized 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../vehicles/api/vehicles.controller.ts | 39 +++++++++++++++++-- .../features/vehicles/api/vehicles.routes.ts | 6 +++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/backend/src/features/vehicles/api/vehicles.controller.ts b/backend/src/features/vehicles/api/vehicles.controller.ts index 3e94dfa..4bf7870 100644 --- a/backend/src/features/vehicles/api/vehicles.controller.ts +++ b/backend/src/features/vehicles/api/vehicles.controller.ts @@ -166,20 +166,20 @@ export class VehiclesController { try { const userId = (request as any).user.sub; const { id } = request.params; - + await this.vehiclesService.deleteVehicle(id, userId); - + return reply.code(204).send(); } catch (error: any) { logger.error('Error deleting vehicle', { error, vehicleId: request.params.id, userId: (request as any).user?.sub }); - + if (error.message === 'Vehicle not found' || error.message === 'Unauthorized') { return reply.code(404).send({ error: 'Not Found', message: 'Vehicle not found' }); } - + return reply.code(500).send({ error: 'Internal server error', message: 'Failed to delete vehicle' @@ -187,6 +187,37 @@ export class VehiclesController { } } + async getTCO(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) { + try { + const userId = (request as any).user.sub; + const { id } = request.params; + + const tco = await this.vehiclesService.getTCO(id, userId); + return reply.code(200).send(tco); + } catch (error: any) { + logger.error('Error getting vehicle TCO', { error, vehicleId: request.params.id, userId: (request as any).user?.sub }); + + if (error.statusCode === 404 || error.message === 'Vehicle not found') { + return reply.code(404).send({ + error: 'Not Found', + message: 'Vehicle not found' + }); + } + + if (error.statusCode === 403 || error.message === 'Unauthorized') { + return reply.code(403).send({ + error: 'Forbidden', + message: 'Not authorized to access this vehicle' + }); + } + + return reply.code(500).send({ + error: 'Internal server error', + message: 'Failed to calculate TCO' + }); + } + } + async getDropdownMakes(request: FastifyRequest<{ Querystring: { year: number } }>, reply: FastifyReply) { try { const { year } = request.query; diff --git a/backend/src/features/vehicles/api/vehicles.routes.ts b/backend/src/features/vehicles/api/vehicles.routes.ts index c874441..e82cb6c 100644 --- a/backend/src/features/vehicles/api/vehicles.routes.ts +++ b/backend/src/features/vehicles/api/vehicles.routes.ts @@ -100,6 +100,12 @@ export const vehiclesRoutes: FastifyPluginAsync = async ( handler: vehiclesController.deleteImage.bind(vehiclesController) }); + // GET /api/vehicles/:id/tco - Get vehicle Total Cost of Ownership + fastify.get<{ Params: VehicleParams }>('/vehicles/:id/tco', { + preHandler: [fastify.authenticate], + handler: vehiclesController.getTCO.bind(vehiclesController) + }); + // Dynamic :id routes MUST come last to avoid matching specific paths like "dropdown" // GET /api/vehicles/:id - Get specific vehicle fastify.get<{ Params: VehicleParams }>('/vehicles/:id', { -- 2.49.1 From 5e40754c68ca4828fee65a1500b4e4da06166230 Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Mon, 12 Jan 2026 20:04:21 -0600 Subject: [PATCH 06/11] feat: add ownership cost fields to vehicle form (refs #15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add CostInterval type and TCOResponse interface - Add TCO fields to Vehicle, CreateVehicleRequest, UpdateVehicleRequest - Add "Ownership Costs" section to VehicleForm with: - Purchase price and date - Insurance cost and interval - Registration cost and interval - TCO display toggle - Add getTCO API method - Mobile-responsive grid layout with 44px touch targets 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .../src/features/vehicles/api/vehicles.api.ts | 10 +- .../vehicles/components/VehicleForm.tsx | 142 +++++++++++++++++- .../features/vehicles/types/vehicles.types.ts | 41 +++++ 3 files changed, 191 insertions(+), 2 deletions(-) diff --git a/frontend/src/features/vehicles/api/vehicles.api.ts b/frontend/src/features/vehicles/api/vehicles.api.ts index ed409c7..d24d6b0 100644 --- a/frontend/src/features/vehicles/api/vehicles.api.ts +++ b/frontend/src/features/vehicles/api/vehicles.api.ts @@ -3,7 +3,7 @@ */ import { apiClient } from '../../../core/api/client'; -import { Vehicle, CreateVehicleRequest, UpdateVehicleRequest, DecodedVehicleData } from '../types/vehicles.types'; +import { Vehicle, CreateVehicleRequest, UpdateVehicleRequest, DecodedVehicleData, TCOResponse } from '../types/vehicles.types'; // All requests (including dropdowns) use authenticated apiClient @@ -88,5 +88,13 @@ export const vehiclesApi = { decodeVin: async (vin: string): Promise => { const response = await apiClient.post('/vehicles/decode-vin', { vin }); return response.data; + }, + + /** + * Get Total Cost of Ownership data for a vehicle + */ + getTCO: async (vehicleId: string): Promise => { + const response = await apiClient.get(`/vehicles/${vehicleId}/tco`); + return response.data; } }; diff --git a/frontend/src/features/vehicles/components/VehicleForm.tsx b/frontend/src/features/vehicles/components/VehicleForm.tsx index 559d351..094becf 100644 --- a/frontend/src/features/vehicles/components/VehicleForm.tsx +++ b/frontend/src/features/vehicles/components/VehicleForm.tsx @@ -7,12 +7,19 @@ import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { Button } from '../../../shared-minimal/components/Button'; -import { CreateVehicleRequest, Vehicle } from '../types/vehicles.types'; +import { CreateVehicleRequest, Vehicle, CostInterval } from '../types/vehicles.types'; import { vehiclesApi } from '../api/vehicles.api'; import { VehicleImageUpload } from './VehicleImageUpload'; import { useTierAccess } from '../../../core/hooks/useTierAccess'; import { UpgradeRequiredDialog } from '../../../shared-minimal/components/UpgradeRequiredDialog'; +// Cost interval options +const costIntervalOptions: { value: CostInterval; label: string }[] = [ + { value: 'monthly', label: 'Monthly' }, + { value: 'semi_annual', label: 'Semi-Annual (6 months)' }, + { value: 'annual', label: 'Annual' }, +]; + const vehicleSchema = z .object({ vin: z.string().max(17).nullable().optional().transform(val => val ?? undefined), @@ -28,6 +35,14 @@ const vehicleSchema = z color: z.string().nullable().optional(), licensePlate: z.string().nullable().optional(), odometerReading: z.number().min(0).nullable().optional(), + // TCO fields + purchasePrice: z.number().min(0).nullable().optional(), + purchaseDate: z.string().nullable().optional(), + insuranceCost: z.number().min(0).nullable().optional(), + insuranceInterval: z.enum(['monthly', 'semi_annual', 'annual']).nullable().optional(), + registrationCost: z.number().min(0).nullable().optional(), + registrationInterval: z.enum(['monthly', 'semi_annual', 'annual']).nullable().optional(), + tcoEnabled: z.boolean().nullable().optional(), }) .refine( (data) => { @@ -824,6 +839,131 @@ export const VehicleForm: React.FC = ({ /> + {/* Ownership Costs Section (TCO) */} +
+

+ Ownership Costs +

+

+ Track your total cost of ownership including purchase price and recurring costs. +

+ +
+
+ + +
+ +
+ + +
+
+ +
+
+ + +
+ +
+ + +
+
+ +
+
+ + +
+ +
+ + +
+
+ +
+ +

+ When enabled, shows lifetime cost and cost per mile/km on the vehicle detail page. +

+
+
+
+ +
+ + ); +}; diff --git a/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx b/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx new file mode 100644 index 0000000..74874c4 --- /dev/null +++ b/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx @@ -0,0 +1,201 @@ +/** + * @ai-summary List component for displaying ownership costs + */ + +import React, { useState } from 'react'; +import { + OwnershipCost, + CreateOwnershipCostRequest, + COST_TYPE_LABELS, + INTERVAL_LABELS +} from '../types/ownership-costs.types'; +import { OwnershipCostForm } from './OwnershipCostForm'; +import { useOwnershipCosts } from '../hooks/useOwnershipCosts'; +import { Button } from '../../../shared-minimal/components/Button'; + +interface OwnershipCostsListProps { + vehicleId: string; +} + +export const OwnershipCostsList: React.FC = ({ + vehicleId, +}) => { + const { costs, isLoading, error, createCost, updateCost, deleteCost } = useOwnershipCosts(vehicleId); + const [showForm, setShowForm] = useState(false); + const [editingCost, setEditingCost] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + const [deleteConfirm, setDeleteConfirm] = useState(null); + + const handleSubmit = async (data: Omit) => { + setIsSubmitting(true); + try { + if (editingCost) { + await updateCost(editingCost.id, data); + } else { + await createCost({ ...data, vehicleId }); + } + setShowForm(false); + setEditingCost(null); + } finally { + setIsSubmitting(false); + } + }; + + const handleEdit = (cost: OwnershipCost) => { + setEditingCost(cost); + setShowForm(true); + }; + + const handleDelete = async (id: string) => { + try { + await deleteCost(id); + setDeleteConfirm(null); + } catch (err) { + console.error('Failed to delete cost:', err); + } + }; + + const handleCancel = () => { + setShowForm(false); + setEditingCost(null); + }; + + // Format currency + const formatCurrency = (value: number): string => { + return value.toLocaleString(undefined, { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }); + }; + + // Format date + const formatDate = (dateString: string): string => { + return new Date(dateString).toLocaleDateString(); + }; + + if (isLoading) { + return ( +
+ {[1, 2].map((i) => ( +
+ ))} +
+ ); + } + + if (error) { + return ( +
+ {error} +
+ ); + } + + return ( +
+
+

+ Recurring Costs +

+ {!showForm && ( + + )} +
+ + {showForm && ( +
+

+ {editingCost ? 'Edit Cost' : 'Add New Cost'} +

+ +
+ )} + + {costs.length === 0 && !showForm ? ( +
+

No recurring costs added yet.

+

Track insurance, registration, and other recurring vehicle costs.

+
+ ) : ( +
+ {costs.map((cost) => ( +
+
+
+
+ + {COST_TYPE_LABELS[cost.costType]} + + + {INTERVAL_LABELS[cost.interval]} + +
+ {cost.description && ( +

+ {cost.description} +

+ )} +

+ {formatDate(cost.startDate)} + {cost.endDate ? ` - ${formatDate(cost.endDate)}` : ' - Ongoing'} +

+
+
+
+ ${formatCurrency(cost.amount)} +
+
+ + {deleteConfirm === cost.id ? ( +
+ + +
+ ) : ( + + )} +
+
+
+
+ ))} +
+ )} +
+ ); +}; diff --git a/frontend/src/features/ownership-costs/hooks/useOwnershipCosts.ts b/frontend/src/features/ownership-costs/hooks/useOwnershipCosts.ts new file mode 100644 index 0000000..c7c568e --- /dev/null +++ b/frontend/src/features/ownership-costs/hooks/useOwnershipCosts.ts @@ -0,0 +1,75 @@ +/** + * @ai-summary React hook for ownership costs management + */ + +import { useState, useEffect, useCallback } from 'react'; +import { ownershipCostsApi } from '../api/ownership-costs.api'; +import { + OwnershipCost, + CreateOwnershipCostRequest, + UpdateOwnershipCostRequest +} from '../types/ownership-costs.types'; + +interface UseOwnershipCostsResult { + costs: OwnershipCost[]; + isLoading: boolean; + error: string | null; + refresh: () => Promise; + createCost: (data: CreateOwnershipCostRequest) => Promise; + updateCost: (id: string, data: UpdateOwnershipCostRequest) => Promise; + deleteCost: (id: string) => Promise; +} + +export function useOwnershipCosts(vehicleId: string): UseOwnershipCostsResult { + const [costs, setCosts] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const fetchCosts = useCallback(async () => { + if (!vehicleId) return; + + setIsLoading(true); + setError(null); + try { + const data = await ownershipCostsApi.getByVehicle(vehicleId); + setCosts(data); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : 'Failed to load ownership costs'; + setError(message); + console.error('Failed to fetch ownership costs:', err); + } finally { + setIsLoading(false); + } + }, [vehicleId]); + + useEffect(() => { + fetchCosts(); + }, [fetchCosts]); + + const createCost = useCallback(async (data: CreateOwnershipCostRequest): Promise => { + const newCost = await ownershipCostsApi.create(data); + setCosts(prev => [newCost, ...prev]); + return newCost; + }, []); + + const updateCost = useCallback(async (id: string, data: UpdateOwnershipCostRequest): Promise => { + const updated = await ownershipCostsApi.update(id, data); + setCosts(prev => prev.map(cost => cost.id === id ? updated : cost)); + return updated; + }, []); + + const deleteCost = useCallback(async (id: string): Promise => { + await ownershipCostsApi.delete(id); + setCosts(prev => prev.filter(cost => cost.id !== id)); + }, []); + + return { + costs, + isLoading, + error, + refresh: fetchCosts, + createCost, + updateCost, + deleteCost, + }; +} diff --git a/frontend/src/features/ownership-costs/index.ts b/frontend/src/features/ownership-costs/index.ts new file mode 100644 index 0000000..45a863e --- /dev/null +++ b/frontend/src/features/ownership-costs/index.ts @@ -0,0 +1,25 @@ +/** + * @ai-summary Public API for ownership-costs frontend feature + */ + +// Export components +export { OwnershipCostForm } from './components/OwnershipCostForm'; +export { OwnershipCostsList } from './components/OwnershipCostsList'; + +// Export hooks +export { useOwnershipCosts } from './hooks/useOwnershipCosts'; + +// Export API +export { ownershipCostsApi } from './api/ownership-costs.api'; + +// Export types +export type { + OwnershipCost, + CreateOwnershipCostRequest, + UpdateOwnershipCostRequest, + OwnershipCostStats, + OwnershipCostType, + CostInterval +} from './types/ownership-costs.types'; + +export { COST_TYPE_LABELS, INTERVAL_LABELS } from './types/ownership-costs.types'; diff --git a/frontend/src/features/ownership-costs/types/ownership-costs.types.ts b/frontend/src/features/ownership-costs/types/ownership-costs.types.ts new file mode 100644 index 0000000..6bd6338 --- /dev/null +++ b/frontend/src/features/ownership-costs/types/ownership-costs.types.ts @@ -0,0 +1,70 @@ +/** + * @ai-summary Type definitions for ownership-costs feature + */ + +// Cost types supported by ownership-costs feature +export type OwnershipCostType = 'insurance' | 'registration' | 'tax' | 'other'; + +// Cost interval types +export type CostInterval = 'monthly' | 'semi_annual' | 'annual' | 'one_time'; + +export interface OwnershipCost { + id: string; + userId: string; + vehicleId: string; + documentId?: string; + costType: OwnershipCostType; + description?: string; + amount: number; + interval: CostInterval; + startDate: string; + endDate?: string; + createdAt: string; + updatedAt: string; +} + +export interface CreateOwnershipCostRequest { + vehicleId: string; + documentId?: string; + costType: OwnershipCostType; + description?: string; + amount: number; + interval: CostInterval; + startDate: string; + endDate?: string; +} + +export interface UpdateOwnershipCostRequest { + documentId?: string | null; + costType?: OwnershipCostType; + description?: string | null; + amount?: number; + interval?: CostInterval; + startDate?: string; + endDate?: string | null; +} + +// Aggregated cost statistics +export interface OwnershipCostStats { + insuranceCosts: number; + registrationCosts: number; + taxCosts: number; + otherCosts: number; + totalCosts: number; +} + +// Display labels for cost types +export const COST_TYPE_LABELS: Record = { + insurance: 'Insurance', + registration: 'Registration', + tax: 'Tax', + other: 'Other', +}; + +// Display labels for intervals +export const INTERVAL_LABELS: Record = { + monthly: 'Monthly', + semi_annual: 'Semi-Annual (6 months)', + annual: 'Annual', + one_time: 'One-Time', +}; diff --git a/frontend/src/features/vehicles/components/TCODisplay.tsx b/frontend/src/features/vehicles/components/TCODisplay.tsx index 42fe9fa..32a5187 100644 --- a/frontend/src/features/vehicles/components/TCODisplay.tsx +++ b/frontend/src/features/vehicles/components/TCODisplay.tsx @@ -121,6 +121,12 @@ export const TCODisplay: React.FC = ({ vehicleId, tcoEnabled }) {tco.registrationCosts > 0 && (
Registration: {currencySymbol}{formatCurrency(tco.registrationCosts)}
)} + {tco.taxCosts > 0 && ( +
Tax: {currencySymbol}{formatCurrency(tco.taxCosts)}
+ )} + {tco.otherCosts > 0 && ( +
Other: {currencySymbol}{formatCurrency(tco.otherCosts)}
+ )} {tco.fuelCosts > 0 && (
Fuel: {currencySymbol}{formatCurrency(tco.fuelCosts)}
)} diff --git a/frontend/src/features/vehicles/types/vehicles.types.ts b/frontend/src/features/vehicles/types/vehicles.types.ts index ca66436..8238c1d 100644 --- a/frontend/src/features/vehicles/types/vehicles.types.ts +++ b/frontend/src/features/vehicles/types/vehicles.types.ts @@ -89,6 +89,8 @@ export interface TCOResponse { purchasePrice: number; insuranceCosts: number; registrationCosts: number; + taxCosts: number; + otherCosts: number; fuelCosts: number; maintenanceCosts: number; lifetimeTotal: number; -- 2.49.1 From cb93e3ccc58f06808c0048c079bb5af8ce6d2dea Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Tue, 13 Jan 2026 07:57:23 -0600 Subject: [PATCH 10/11] feat: integrate ownership-costs UI into vehicle detail pages (refs #15) - Add OwnershipCostsList to desktop VehicleDetailPage - Add OwnershipCostsList to mobile VehicleDetailMobile - Users can now view, add, edit, and delete recurring costs directly from the vehicle detail view --- .../features/vehicles/mobile/VehicleDetailMobile.tsx | 11 ++++++++++- .../features/vehicles/pages/VehicleDetailPage.tsx | 12 +++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/frontend/src/features/vehicles/mobile/VehicleDetailMobile.tsx b/frontend/src/features/vehicles/mobile/VehicleDetailMobile.tsx index 9847f20..2f15bef 100644 --- a/frontend/src/features/vehicles/mobile/VehicleDetailMobile.tsx +++ b/frontend/src/features/vehicles/mobile/VehicleDetailMobile.tsx @@ -11,6 +11,7 @@ import { FuelLogResponse, UpdateFuelLogRequest } from '../../fuel-logs/types/fue import { FuelLogEditDialog } from '../../fuel-logs/components/FuelLogEditDialog'; import { fuelLogsApi } from '../../fuel-logs/api/fuel-logs.api'; import { VehicleImage } from '../components/VehicleImage'; +import { OwnershipCostsList } from '../../ownership-costs'; interface VehicleDetailMobileProps { vehicle: Vehicle; @@ -224,7 +225,15 @@ export const VehicleDetailMobile: React.FC = ({ - + +
+ + + + + +
+
diff --git a/frontend/src/features/vehicles/pages/VehicleDetailPage.tsx b/frontend/src/features/vehicles/pages/VehicleDetailPage.tsx index 65027a1..e5a5894 100644 --- a/frontend/src/features/vehicles/pages/VehicleDetailPage.tsx +++ b/frontend/src/features/vehicles/pages/VehicleDetailPage.tsx @@ -22,6 +22,7 @@ import { FuelLogEditDialog } from '../../fuel-logs/components/FuelLogEditDialog' import { FuelLogForm } from '../../fuel-logs/components/FuelLogForm'; // Unit conversions now handled by backend import { fuelLogsApi } from '../../fuel-logs/api/fuel-logs.api'; +import { OwnershipCostsList } from '../../ownership-costs'; const DetailField: React.FC<{ label: string; @@ -356,14 +357,19 @@ export const VehicleDetailPage: React.FC = () => {
- + {/* Recurring Ownership Costs */} + + + + Vehicle Records -- 2.49.1 From 395670c3bddf5ce1432e5f32e677b09a78f35a4d Mon Sep 17 00:00:00 2001 From: Eric Gullickson <16152721+ericgullickson@users.noreply.github.com> Date: Tue, 13 Jan 2026 08:15:53 -0600 Subject: [PATCH 11/11] fix: add ownership-costs to migration order and improve error handling (refs #15) - Add 'features/ownership-costs' to MIGRATION_ORDER in run-all.ts - Improve OwnershipCostsList error display to not block the page - Show friendly message when feature needs migration --- backend/src/_system/migrations/run-all.ts | 1 + .../components/OwnershipCostsList.tsx | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/backend/src/_system/migrations/run-all.ts b/backend/src/_system/migrations/run-all.ts index a134ee9..2d0fd9e 100644 --- a/backend/src/_system/migrations/run-all.ts +++ b/backend/src/_system/migrations/run-all.ts @@ -28,6 +28,7 @@ const MIGRATION_ORDER = [ 'features/user-profile', // User profile management; independent 'features/terms-agreement', // Terms & Conditions acceptance audit trail 'features/audit-log', // Centralized audit logging; independent + 'features/ownership-costs', // Depends on vehicles and documents; TCO recurring costs ]; // Base directory where migrations are copied inside the image (set by Dockerfile) diff --git a/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx b/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx index 74874c4..3b69dfb 100644 --- a/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx +++ b/frontend/src/features/ownership-costs/components/OwnershipCostsList.tsx @@ -84,9 +84,18 @@ export const OwnershipCostsList: React.FC = ({ } if (error) { + // Show a subtle message if the feature isn't set up yet, don't block the page return ( -
- {error} +
+
+

+ Recurring Costs +

+
+
+

Recurring costs tracking is being set up.

+

Run migrations to enable this feature.

+
); } -- 2.49.1