feat: add ownership-costs feature capsule (refs #15)

- Create ownership_costs table for recurring vehicle costs
- Add backend feature capsule with types, repository, service, routes
- Update TCO calculation to use ownership_costs (with fallback to legacy vehicle fields)
- Add taxCosts and otherCosts to TCO response
- Create frontend ownership-costs feature with form, list, API, hooks
- Update TCODisplay to show all cost types

This implements a more flexible approach to tracking recurring ownership costs
(insurance, registration, tax, other) with explicit date ranges and optional
document association.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Eric Gullickson
2026-01-12 21:28:25 -06:00
parent 5c93150a58
commit a8c4eba8d1
19 changed files with 1644 additions and 15 deletions

View File

@@ -0,0 +1,60 @@
/**
* @ai-summary API calls for ownership-costs feature
*/
import { apiClient } from '../../../core/api/client';
import {
OwnershipCost,
CreateOwnershipCostRequest,
UpdateOwnershipCostRequest,
OwnershipCostStats
} from '../types/ownership-costs.types';
export const ownershipCostsApi = {
/**
* Get all ownership costs for a vehicle
*/
getByVehicle: async (vehicleId: string): Promise<OwnershipCost[]> => {
const response = await apiClient.get(`/ownership-costs/vehicle/${vehicleId}`);
return response.data;
},
/**
* Get a single ownership cost by ID
*/
getById: async (id: string): Promise<OwnershipCost> => {
const response = await apiClient.get(`/ownership-costs/${id}`);
return response.data;
},
/**
* Create a new ownership cost
*/
create: async (data: CreateOwnershipCostRequest): Promise<OwnershipCost> => {
const response = await apiClient.post('/ownership-costs', data);
return response.data;
},
/**
* Update an existing ownership cost
*/
update: async (id: string, data: UpdateOwnershipCostRequest): Promise<OwnershipCost> => {
const response = await apiClient.put(`/ownership-costs/${id}`, data);
return response.data;
},
/**
* Delete an ownership cost
*/
delete: async (id: string): Promise<void> => {
await apiClient.delete(`/ownership-costs/${id}`);
},
/**
* Get aggregated cost stats for a vehicle
*/
getVehicleStats: async (vehicleId: string): Promise<OwnershipCostStats> => {
const response = await apiClient.get(`/ownership-costs/vehicle/${vehicleId}/stats`);
return response.data;
},
};

View File

@@ -0,0 +1,214 @@
/**
* @ai-summary Form component for adding/editing ownership costs
*/
import React, { useState, useEffect } from 'react';
import { Button } from '../../../shared-minimal/components/Button';
import {
OwnershipCost,
OwnershipCostType,
CostInterval,
COST_TYPE_LABELS,
INTERVAL_LABELS
} from '../types/ownership-costs.types';
interface OwnershipCostFormProps {
vehicleId: string;
initialData?: OwnershipCost;
onSubmit: (data: {
costType: OwnershipCostType;
description?: string;
amount: number;
interval: CostInterval;
startDate: string;
endDate?: string;
}) => Promise<void>;
onCancel: () => void;
loading?: boolean;
}
export const OwnershipCostForm: React.FC<OwnershipCostFormProps> = ({
initialData,
onSubmit,
onCancel,
loading,
}) => {
const [costType, setCostType] = useState<OwnershipCostType>(initialData?.costType || 'insurance');
const [description, setDescription] = useState(initialData?.description || '');
const [amount, setAmount] = useState(initialData?.amount?.toString() || '');
const [interval, setInterval] = useState<CostInterval>(initialData?.interval || 'monthly');
const [startDate, setStartDate] = useState(initialData?.startDate || new Date().toISOString().split('T')[0]);
const [endDate, setEndDate] = useState(initialData?.endDate || '');
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (initialData) {
setCostType(initialData.costType);
setDescription(initialData.description || '');
setAmount(initialData.amount.toString());
setInterval(initialData.interval);
setStartDate(initialData.startDate);
setEndDate(initialData.endDate || '');
}
}, [initialData]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
// Validate amount
const parsedAmount = parseFloat(amount);
if (isNaN(parsedAmount) || parsedAmount < 0) {
setError('Please enter a valid amount');
return;
}
// Validate dates
if (!startDate) {
setError('Start date is required');
return;
}
if (endDate && new Date(endDate) < new Date(startDate)) {
setError('End date must be after start date');
return;
}
try {
await onSubmit({
costType,
description: description.trim() || undefined,
amount: parsedAmount,
interval,
startDate,
endDate: endDate || undefined,
});
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Failed to save cost';
setError(message);
}
};
const isEditMode = !!initialData;
return (
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-md text-sm">
{error}
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-avus mb-1">
Cost Type
</label>
<select
value={costType}
onChange={(e) => setCostType(e.target.value as OwnershipCostType)}
className="w-full px-3 py-2 border rounded-md min-h-[44px] bg-white text-gray-900 border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-scuro dark:text-avus dark:border-silverstone dark:focus:ring-abudhabi"
style={{ fontSize: '16px' }}
>
{(Object.entries(COST_TYPE_LABELS) as [OwnershipCostType, string][]).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-avus mb-1">
Description (optional)
</label>
<input
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="e.g., Geico Full Coverage"
className="w-full px-3 py-2 border rounded-md min-h-[44px] bg-white text-gray-900 border-gray-300 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-scuro dark:text-avus dark:border-silverstone dark:placeholder-canna"
style={{ fontSize: '16px' }}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-avus mb-1">
Amount
</label>
<input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="0.00"
inputMode="decimal"
step="0.01"
min="0"
required
className="w-full px-3 py-2 border rounded-md min-h-[44px] bg-white text-gray-900 border-gray-300 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-scuro dark:text-avus dark:border-silverstone dark:placeholder-canna"
style={{ fontSize: '16px' }}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-avus mb-1">
Payment Interval
</label>
<select
value={interval}
onChange={(e) => setInterval(e.target.value as CostInterval)}
className="w-full px-3 py-2 border rounded-md min-h-[44px] bg-white text-gray-900 border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-scuro dark:text-avus dark:border-silverstone dark:focus:ring-abudhabi"
style={{ fontSize: '16px' }}
>
{(Object.entries(INTERVAL_LABELS) as [CostInterval, string][]).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-avus mb-1">
Start Date
</label>
<input
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
required
className="w-full px-3 py-2 border rounded-md min-h-[44px] bg-white text-gray-900 border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-scuro dark:text-avus dark:border-silverstone"
style={{ fontSize: '16px' }}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-avus mb-1">
End Date (optional)
</label>
<input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
className="w-full px-3 py-2 border rounded-md min-h-[44px] bg-white text-gray-900 border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-scuro dark:text-avus dark:border-silverstone"
style={{ fontSize: '16px' }}
/>
<p className="text-xs text-gray-500 dark:text-titanio mt-1">
Leave blank for ongoing costs
</p>
</div>
</div>
<div className="flex gap-3 justify-end pt-4">
<Button variant="secondary" onClick={onCancel} type="button">
Cancel
</Button>
<Button type="submit" loading={loading}>
{isEditMode ? 'Update Cost' : 'Add Cost'}
</Button>
</div>
</form>
);
};

View File

@@ -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<OwnershipCostsListProps> = ({
vehicleId,
}) => {
const { costs, isLoading, error, createCost, updateCost, deleteCost } = useOwnershipCosts(vehicleId);
const [showForm, setShowForm] = useState(false);
const [editingCost, setEditingCost] = useState<OwnershipCost | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
const handleSubmit = async (data: Omit<CreateOwnershipCostRequest, 'vehicleId'>) => {
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 (
<div className="animate-pulse space-y-4">
{[1, 2].map((i) => (
<div key={i} className="h-24 bg-gray-200 dark:bg-silverstone rounded-lg" />
))}
</div>
);
}
if (error) {
return (
<div className="text-red-500 dark:text-red-400 text-sm p-4 bg-red-50 dark:bg-red-900/20 rounded-lg">
{error}
</div>
);
}
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="text-lg font-medium text-gray-900 dark:text-avus">
Recurring Costs
</h3>
{!showForm && (
<Button
variant="secondary"
onClick={() => setShowForm(true)}
className="text-sm"
>
Add Cost
</Button>
)}
</div>
{showForm && (
<div className="p-4 bg-gray-50 dark:bg-scuro rounded-lg border border-gray-200 dark:border-silverstone">
<h4 className="text-md font-medium text-gray-900 dark:text-avus mb-4">
{editingCost ? 'Edit Cost' : 'Add New Cost'}
</h4>
<OwnershipCostForm
vehicleId={vehicleId}
initialData={editingCost || undefined}
onSubmit={handleSubmit}
onCancel={handleCancel}
loading={isSubmitting}
/>
</div>
)}
{costs.length === 0 && !showForm ? (
<div className="text-center py-8 text-gray-500 dark:text-titanio">
<p>No recurring costs added yet.</p>
<p className="text-sm mt-1">Track insurance, registration, and other recurring vehicle costs.</p>
</div>
) : (
<div className="space-y-3">
{costs.map((cost) => (
<div
key={cost.id}
className="p-4 bg-white dark:bg-jet rounded-lg border border-gray-200 dark:border-silverstone"
>
<div className="flex justify-between items-start">
<div>
<div className="flex items-center gap-2">
<span className="font-medium text-gray-900 dark:text-avus">
{COST_TYPE_LABELS[cost.costType]}
</span>
<span className="text-xs px-2 py-0.5 bg-gray-100 dark:bg-silverstone text-gray-600 dark:text-titanio rounded">
{INTERVAL_LABELS[cost.interval]}
</span>
</div>
{cost.description && (
<p className="text-sm text-gray-500 dark:text-titanio mt-1">
{cost.description}
</p>
)}
<p className="text-xs text-gray-400 dark:text-canna mt-2">
{formatDate(cost.startDate)}
{cost.endDate ? ` - ${formatDate(cost.endDate)}` : ' - Ongoing'}
</p>
</div>
<div className="text-right">
<div className="text-lg font-semibold text-gray-900 dark:text-avus">
${formatCurrency(cost.amount)}
</div>
<div className="flex gap-2 mt-2">
<button
onClick={() => handleEdit(cost)}
className="text-sm text-primary-600 dark:text-abudhabi hover:underline"
>
Edit
</button>
{deleteConfirm === cost.id ? (
<div className="flex gap-1">
<button
onClick={() => handleDelete(cost.id)}
className="text-sm text-red-600 hover:underline"
>
Confirm
</button>
<button
onClick={() => setDeleteConfirm(null)}
className="text-sm text-gray-500 hover:underline"
>
Cancel
</button>
</div>
) : (
<button
onClick={() => setDeleteConfirm(cost.id)}
className="text-sm text-red-600 hover:underline"
>
Delete
</button>
)}
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
);
};

View File

@@ -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<void>;
createCost: (data: CreateOwnershipCostRequest) => Promise<OwnershipCost>;
updateCost: (id: string, data: UpdateOwnershipCostRequest) => Promise<OwnershipCost>;
deleteCost: (id: string) => Promise<void>;
}
export function useOwnershipCosts(vehicleId: string): UseOwnershipCostsResult {
const [costs, setCosts] = useState<OwnershipCost[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(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<OwnershipCost> => {
const newCost = await ownershipCostsApi.create(data);
setCosts(prev => [newCost, ...prev]);
return newCost;
}, []);
const updateCost = useCallback(async (id: string, data: UpdateOwnershipCostRequest): Promise<OwnershipCost> => {
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<void> => {
await ownershipCostsApi.delete(id);
setCosts(prev => prev.filter(cost => cost.id !== id));
}, []);
return {
costs,
isLoading,
error,
refresh: fetchCosts,
createCost,
updateCost,
deleteCost,
};
}

View File

@@ -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';

View File

@@ -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<OwnershipCostType, string> = {
insurance: 'Insurance',
registration: 'Registration',
tax: 'Tax',
other: 'Other',
};
// Display labels for intervals
export const INTERVAL_LABELS: Record<CostInterval, string> = {
monthly: 'Monthly',
semi_annual: 'Semi-Annual (6 months)',
annual: 'Annual',
one_time: 'One-Time',
};

View File

@@ -121,6 +121,12 @@ export const TCODisplay: React.FC<TCODisplayProps> = ({ vehicleId, tcoEnabled })
{tco.registrationCosts > 0 && (
<div>Registration: {currencySymbol}{formatCurrency(tco.registrationCosts)}</div>
)}
{tco.taxCosts > 0 && (
<div>Tax: {currencySymbol}{formatCurrency(tco.taxCosts)}</div>
)}
{tco.otherCosts > 0 && (
<div>Other: {currencySymbol}{formatCurrency(tco.otherCosts)}</div>
)}
{tco.fuelCosts > 0 && (
<div>Fuel: {currencySymbol}{formatCurrency(tco.fuelCosts)}</div>
)}

View File

@@ -89,6 +89,8 @@ export interface TCOResponse {
purchasePrice: number;
insuranceCosts: number;
registrationCosts: number;
taxCosts: number;
otherCosts: number;
fuelCosts: number;
maintenanceCosts: number;
lifetimeTotal: number;