fix: before admin stations removal
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* @ai-summary React context for unit system preferences
|
||||
* @ai-context Provides unit preferences and conversion functions throughout the app
|
||||
* @ai-summary React context for unit system preferences with backend sync
|
||||
* @ai-context Provides unit preferences, conversion functions, and currency symbol throughout the app
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
|
||||
import { UnitSystem, UnitPreferences } from './units.types';
|
||||
import { safeStorage } from '../utils/safe-storage';
|
||||
import {
|
||||
@@ -18,22 +18,27 @@ import {
|
||||
getVolumeUnit,
|
||||
getFuelEfficiencyUnit
|
||||
} from './units.utils';
|
||||
import { usePreferences, useUpdatePreferences } from '../../features/settings/hooks/usePreferences';
|
||||
import { useAuth0 } from '@auth0/auth0-react';
|
||||
|
||||
interface UnitsContextType {
|
||||
unitSystem: UnitSystem;
|
||||
setUnitSystem: (system: UnitSystem) => void;
|
||||
preferences: UnitPreferences;
|
||||
|
||||
currencySymbol: string;
|
||||
currencyCode: string;
|
||||
isLoading: boolean;
|
||||
|
||||
// Conversion functions
|
||||
convertDistance: (miles: number) => number;
|
||||
convertVolume: (gallons: number) => number;
|
||||
convertFuelEfficiency: (mpg: number) => number;
|
||||
|
||||
|
||||
// Formatting functions
|
||||
formatDistance: (miles: number, precision?: number) => string;
|
||||
formatVolume: (gallons: number, precision?: number) => string;
|
||||
formatFuelEfficiency: (mpg: number, precision?: number) => string;
|
||||
formatPrice: (pricePerGallon: number, currency?: string, precision?: number) => string;
|
||||
formatPrice: (pricePerGallon: number, precision?: number) => string;
|
||||
}
|
||||
|
||||
const UnitsContext = createContext<UnitsContextType | undefined>(undefined);
|
||||
@@ -43,34 +48,78 @@ interface UnitsProviderProps {
|
||||
initialSystem?: UnitSystem;
|
||||
}
|
||||
|
||||
export const UnitsProvider: React.FC<UnitsProviderProps> = ({
|
||||
children,
|
||||
initialSystem = 'imperial'
|
||||
}) => {
|
||||
const [unitSystem, setUnitSystem] = useState<UnitSystem>(initialSystem);
|
||||
|
||||
// Load unit preference from storage on mount
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored = safeStorage.getItem('motovaultpro-unit-system');
|
||||
if (stored === 'imperial' || stored === 'metric') {
|
||||
setUnitSystem(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[Units] Failed to load unit system preference:', error);
|
||||
}
|
||||
}, []);
|
||||
// Currency symbol mapping
|
||||
const getCurrencySymbol = (system: UnitSystem): string => {
|
||||
return system === 'metric' ? '\u20AC' : '$'; // EUR or USD
|
||||
};
|
||||
|
||||
// Save unit preference to storage when changed
|
||||
const handleSetUnitSystem = (system: UnitSystem) => {
|
||||
setUnitSystem(system);
|
||||
const getCurrencyCode = (system: UnitSystem): string => {
|
||||
return system === 'metric' ? 'EUR' : 'USD';
|
||||
};
|
||||
|
||||
export const UnitsProvider: React.FC<UnitsProviderProps> = ({
|
||||
children,
|
||||
initialSystem = 'imperial'
|
||||
}) => {
|
||||
const [unitSystem, setUnitSystemState] = useState<UnitSystem>(initialSystem);
|
||||
const [hasInitialized, setHasInitialized] = useState(false);
|
||||
|
||||
const { isAuthenticated } = useAuth0();
|
||||
const { data: backendPreferences, isLoading: preferencesLoading } = usePreferences();
|
||||
const updatePreferencesMutation = useUpdatePreferences();
|
||||
|
||||
// Load unit preference from localStorage on mount (fallback)
|
||||
useEffect(() => {
|
||||
if (!hasInitialized) {
|
||||
try {
|
||||
const stored = safeStorage.getItem('motovaultpro-unit-system');
|
||||
if (stored === 'imperial' || stored === 'metric') {
|
||||
setUnitSystemState(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[Units] Failed to load unit system preference from storage:', error);
|
||||
}
|
||||
}
|
||||
}, [hasInitialized]);
|
||||
|
||||
// Sync with backend preferences when they load (takes priority over localStorage)
|
||||
useEffect(() => {
|
||||
if (backendPreferences?.unitSystem && !hasInitialized) {
|
||||
setUnitSystemState(backendPreferences.unitSystem);
|
||||
// Also update localStorage to keep them in sync
|
||||
try {
|
||||
safeStorage.setItem('motovaultpro-unit-system', backendPreferences.unitSystem);
|
||||
} catch (error) {
|
||||
console.warn('[Units] Failed to sync unit system to storage:', error);
|
||||
}
|
||||
setHasInitialized(true);
|
||||
}
|
||||
}, [backendPreferences, hasInitialized]);
|
||||
|
||||
// Mark as initialized when not authenticated (localStorage is the source of truth)
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated && !hasInitialized) {
|
||||
setHasInitialized(true);
|
||||
}
|
||||
}, [isAuthenticated, hasInitialized]);
|
||||
|
||||
// Handle unit system change with backend sync
|
||||
const handleSetUnitSystem = useCallback((system: UnitSystem) => {
|
||||
setUnitSystemState(system);
|
||||
|
||||
// Always save to localStorage (offline fallback)
|
||||
try {
|
||||
safeStorage.setItem('motovaultpro-unit-system', system);
|
||||
} catch (error) {
|
||||
console.warn('[Units] Failed to save unit system preference:', error);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Sync to backend if authenticated
|
||||
if (isAuthenticated) {
|
||||
updatePreferencesMutation.mutate({ unitSystem: system });
|
||||
}
|
||||
}, [isAuthenticated, updatePreferencesMutation]);
|
||||
|
||||
// Generate preferences object based on current system
|
||||
const preferences: UnitPreferences = {
|
||||
system: unitSystem,
|
||||
@@ -78,29 +127,36 @@ export const UnitsProvider: React.FC<UnitsProviderProps> = ({
|
||||
volume: getVolumeUnit(unitSystem),
|
||||
fuelEfficiency: getFuelEfficiencyUnit(unitSystem),
|
||||
};
|
||||
|
||||
|
||||
// Currency based on unit system
|
||||
const currencySymbol = getCurrencySymbol(unitSystem);
|
||||
const currencyCode = getCurrencyCode(unitSystem);
|
||||
|
||||
// Conversion functions using current unit system
|
||||
const convertDistance = (miles: number) => convertDistanceBySystem(miles, unitSystem);
|
||||
const convertVolume = (gallons: number) => convertVolumeBySystem(gallons, unitSystem);
|
||||
const convertFuelEfficiency = (mpg: number) => convertFuelEfficiencyBySystem(mpg, unitSystem);
|
||||
|
||||
const convertDistance = useCallback((miles: number) => convertDistanceBySystem(miles, unitSystem), [unitSystem]);
|
||||
const convertVolume = useCallback((gallons: number) => convertVolumeBySystem(gallons, unitSystem), [unitSystem]);
|
||||
const convertFuelEfficiency = useCallback((mpg: number) => convertFuelEfficiencyBySystem(mpg, unitSystem), [unitSystem]);
|
||||
|
||||
// Formatting functions using current unit system
|
||||
const formatDistance = (miles: number, precision?: number) =>
|
||||
formatDistanceBySystem(miles, unitSystem, precision);
|
||||
|
||||
const formatVolume = (gallons: number, precision?: number) =>
|
||||
formatVolumeBySystem(gallons, unitSystem, precision);
|
||||
|
||||
const formatFuelEfficiency = (mpg: number, precision?: number) =>
|
||||
formatFuelEfficiencyBySystem(mpg, unitSystem, precision);
|
||||
|
||||
const formatPrice = (pricePerGallon: number, currency?: string, precision?: number) =>
|
||||
formatPriceBySystem(pricePerGallon, unitSystem, currency, precision);
|
||||
const formatDistance = useCallback((miles: number, precision?: number) =>
|
||||
formatDistanceBySystem(miles, unitSystem, precision), [unitSystem]);
|
||||
|
||||
const formatVolume = useCallback((gallons: number, precision?: number) =>
|
||||
formatVolumeBySystem(gallons, unitSystem, precision), [unitSystem]);
|
||||
|
||||
const formatFuelEfficiency = useCallback((mpg: number, precision?: number) =>
|
||||
formatFuelEfficiencyBySystem(mpg, unitSystem, precision), [unitSystem]);
|
||||
|
||||
const formatPrice = useCallback((pricePerGallon: number, precision?: number) =>
|
||||
formatPriceBySystem(pricePerGallon, unitSystem, currencyCode, precision), [unitSystem, currencyCode]);
|
||||
|
||||
const value: UnitsContextType = {
|
||||
unitSystem,
|
||||
setUnitSystem: handleSetUnitSystem,
|
||||
preferences,
|
||||
currencySymbol,
|
||||
currencyCode,
|
||||
isLoading: preferencesLoading && isAuthenticated,
|
||||
convertDistance,
|
||||
convertVolume,
|
||||
convertFuelEfficiency,
|
||||
@@ -123,4 +179,4 @@ export const useUnits = (): UnitsContextType => {
|
||||
throw new Error('useUnits must be used within a UnitsProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
export type UnitSystem = 'imperial' | 'metric';
|
||||
export type DistanceUnit = 'miles' | 'km';
|
||||
export type VolumeUnit = 'gallons' | 'liters';
|
||||
export type FuelEfficiencyUnit = 'mpg' | 'kml';
|
||||
export type FuelEfficiencyUnit = 'mpg' | 'l100km';
|
||||
|
||||
export interface UnitPreferences {
|
||||
system: UnitSystem;
|
||||
|
||||
@@ -10,9 +10,8 @@ const MILES_TO_KM = 1.60934;
|
||||
const KM_TO_MILES = 0.621371;
|
||||
const GALLONS_TO_LITERS = 3.78541;
|
||||
const LITERS_TO_GALLONS = 0.264172;
|
||||
// For km/L conversion
|
||||
const MPG_TO_KML = 1.60934 / 3.78541; // ≈ 0.425144
|
||||
const KML_TO_MPG = 3.78541 / 1.60934; // ≈ 2.352145
|
||||
// For L/100km conversion (inverse relationship: lower L/100km = better efficiency)
|
||||
const MPG_TO_L100KM_FACTOR = 235.214;
|
||||
|
||||
// Distance Conversions
|
||||
export function convertDistance(value: number, fromUnit: DistanceUnit, toUnit: DistanceUnit): number {
|
||||
@@ -58,24 +57,24 @@ export function convertVolumeBySystem(gallons: number, toSystem: UnitSystem): nu
|
||||
return gallons;
|
||||
}
|
||||
|
||||
// Fuel Efficiency Conversions
|
||||
// Fuel Efficiency Conversions (L/100km is inverse: lower = better)
|
||||
export function convertFuelEfficiency(value: number, fromUnit: FuelEfficiencyUnit, toUnit: FuelEfficiencyUnit): number {
|
||||
if (fromUnit === toUnit) return value;
|
||||
|
||||
if (fromUnit === 'mpg' && toUnit === 'kml') {
|
||||
return value * MPG_TO_KML;
|
||||
|
||||
if (fromUnit === 'mpg' && toUnit === 'l100km') {
|
||||
return value === 0 ? 0 : MPG_TO_L100KM_FACTOR / value;
|
||||
}
|
||||
|
||||
if (fromUnit === 'kml' && toUnit === 'mpg') {
|
||||
return value * KML_TO_MPG;
|
||||
if (fromUnit === 'l100km' && toUnit === 'mpg') {
|
||||
return value === 0 ? 0 : MPG_TO_L100KM_FACTOR / value;
|
||||
}
|
||||
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function convertFuelEfficiencyBySystem(mpg: number, toSystem: UnitSystem): number {
|
||||
if (toSystem === 'metric') {
|
||||
return convertFuelEfficiency(mpg, 'mpg', 'kml');
|
||||
return convertFuelEfficiency(mpg, 'mpg', 'l100km');
|
||||
}
|
||||
return mpg;
|
||||
}
|
||||
@@ -111,15 +110,15 @@ export function formatVolume(value: number, unit: VolumeUnit, precision = 2): st
|
||||
|
||||
export function formatFuelEfficiency(value: number, unit: FuelEfficiencyUnit, precision = 1): string {
|
||||
if (typeof value !== 'number' || isNaN(value)) {
|
||||
return unit === 'mpg' ? '0 MPG' : '0 km/L';
|
||||
return unit === 'mpg' ? '0 MPG' : '0 L/100km';
|
||||
}
|
||||
|
||||
|
||||
const rounded = parseFloat(value.toFixed(precision));
|
||||
|
||||
|
||||
if (unit === 'mpg') {
|
||||
return `${rounded} MPG`;
|
||||
} else {
|
||||
return `${rounded} km/L`;
|
||||
return `${rounded} L/100km`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,8 +167,8 @@ export function formatVolumeBySystem(gallons: number, system: UnitSystem, precis
|
||||
|
||||
export function formatFuelEfficiencyBySystem(mpg: number, system: UnitSystem, precision = 1): string {
|
||||
if (system === 'metric') {
|
||||
const kml = convertFuelEfficiencyBySystem(mpg, system);
|
||||
return formatFuelEfficiency(kml, 'kml', precision);
|
||||
const l100km = convertFuelEfficiencyBySystem(mpg, system);
|
||||
return formatFuelEfficiency(l100km, 'l100km', precision);
|
||||
}
|
||||
return formatFuelEfficiency(mpg, 'mpg', precision);
|
||||
}
|
||||
@@ -192,5 +191,5 @@ export function getVolumeUnit(system: UnitSystem): VolumeUnit {
|
||||
}
|
||||
|
||||
export function getFuelEfficiencyUnit(system: UnitSystem): FuelEfficiencyUnit {
|
||||
return system === 'metric' ? 'kml' : 'mpg';
|
||||
return system === 'metric' ? 'l100km' : 'mpg';
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ export const useImportApply = () => {
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['catalogSearch'] });
|
||||
toast.success(
|
||||
`Import completed: ${result.created} created, ${result.updated} updated, ${result.deleted} deleted`
|
||||
`Import completed: ${result.created} created, ${result.updated} updated`
|
||||
);
|
||||
},
|
||||
onError: (error: ApiError) => {
|
||||
|
||||
@@ -462,9 +462,6 @@ export const AdminCatalogMobileScreen: React.FC = () => {
|
||||
<div className="bg-blue-100 text-blue-800 px-3 py-2 rounded-lg">
|
||||
<strong>{importPreview.toUpdate.length}</strong> to update
|
||||
</div>
|
||||
<div className="bg-red-100 text-red-800 px-3 py-2 rounded-lg">
|
||||
<strong>{importPreview.toDelete.length}</strong> to delete
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Errors */}
|
||||
|
||||
@@ -181,7 +181,6 @@ export interface CatalogSearchResponse {
|
||||
|
||||
// Catalog import types
|
||||
export interface ImportRow {
|
||||
action: 'add' | 'update' | 'delete';
|
||||
year: number;
|
||||
make: string;
|
||||
model: string;
|
||||
@@ -199,7 +198,6 @@ export interface ImportPreviewResult {
|
||||
previewId: string;
|
||||
toCreate: ImportRow[];
|
||||
toUpdate: ImportRow[];
|
||||
toDelete: ImportRow[];
|
||||
errors: ImportError[];
|
||||
valid: boolean;
|
||||
}
|
||||
@@ -207,7 +205,6 @@ export interface ImportPreviewResult {
|
||||
export interface ImportApplyResult {
|
||||
created: number;
|
||||
updated: number;
|
||||
deleted: number;
|
||||
errors: ImportError[];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import React from 'react';
|
||||
import { Card, CardContent, Typography, Box, Chip } from '@mui/material';
|
||||
import { UnitSystem } from '../types/fuel-logs.types';
|
||||
import { useUnits } from '../../../core/units/UnitsContext';
|
||||
|
||||
interface Props {
|
||||
fuelUnits?: number;
|
||||
costPerUnit?: number;
|
||||
calculatedCost: number;
|
||||
unitSystem?: UnitSystem;
|
||||
}
|
||||
|
||||
export const CostCalculator: React.FC<Props> = ({ fuelUnits, costPerUnit, calculatedCost, unitSystem = 'imperial' }) => {
|
||||
export const CostCalculator: React.FC<Props> = ({ fuelUnits, costPerUnit, calculatedCost }) => {
|
||||
const { unitSystem, currencySymbol } = useUnits();
|
||||
const unitLabel = unitSystem === 'imperial' ? 'gallons' : 'liters';
|
||||
|
||||
// Ensure we have valid numbers
|
||||
@@ -30,8 +30,8 @@ export const CostCalculator: React.FC<Props> = ({ fuelUnits, costPerUnit, calcul
|
||||
<Chip label="Real-time" size="small" color="primary" variant="outlined" />
|
||||
</Box>
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Typography variant="body2">{safeUnits.toFixed(3)} {unitLabel} × ${safeCostPerUnit.toFixed(3)}</Typography>
|
||||
<Typography variant="h6" color="primary.main" fontWeight={700}>${safeCost.toFixed(2)}</Typography>
|
||||
<Typography variant="body2">{safeUnits.toFixed(3)} {unitLabel} x {currencySymbol}{safeCostPerUnit.toFixed(3)}</Typography>
|
||||
<Typography variant="h6" color="primary.main" fontWeight={700}>{currencySymbol}{safeCost.toFixed(2)}</Typography>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -12,8 +12,8 @@ interface Props {
|
||||
}
|
||||
|
||||
export const DistanceInput: React.FC<Props> = ({ type, value, onChange, unitSystem = 'imperial', error, disabled }) => {
|
||||
const units = unitSystem === 'imperial' ? 'miles' : 'kilometers';
|
||||
const label = type === 'odometer' ? `Odometer (${units})` : `Trip Distance (${units})`;
|
||||
const units = unitSystem === 'imperial' ? 'miles' : 'km';
|
||||
const label = type === 'odometer' ? 'Odometer' : 'Trip Distance';
|
||||
return (
|
||||
<Box>
|
||||
<TextField
|
||||
|
||||
@@ -157,7 +157,7 @@ const FuelLogFormComponent: React.FC<{ onSuccess?: () => void; initial?: Partial
|
||||
)} />
|
||||
</Grid>
|
||||
|
||||
{/* Row 2: Date/Time | MPG/km/L */}
|
||||
{/* Row 2: Date/Time | MPG/L/100km */}
|
||||
<Grid item xs={12} sm={6}>
|
||||
<Controller name="dateTime" control={control} render={({ field }) => (
|
||||
<DateTimePicker
|
||||
@@ -182,7 +182,7 @@ const FuelLogFormComponent: React.FC<{ onSuccess?: () => void; initial?: Partial
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6}>
|
||||
<TextField
|
||||
label={`${userSettings?.unitSystem === 'metric' ? 'km/L' : 'MPG'}`}
|
||||
label={`${userSettings?.unitSystem === 'metric' ? 'L/100km' : 'MPG'}`}
|
||||
value={calculatedEfficiency > 0 ? calculatedEfficiency.toFixed(3) : ''}
|
||||
fullWidth
|
||||
InputProps={{
|
||||
@@ -283,7 +283,7 @@ const FuelLogFormComponent: React.FC<{ onSuccess?: () => void; initial?: Partial
|
||||
)} />
|
||||
</Grid>
|
||||
<Grid item xs={12}>
|
||||
<CostCalculator fuelUnits={fuelUnits} costPerUnit={costPerUnit} calculatedCost={calculatedCost} unitSystem={userSettings?.unitSystem} />
|
||||
<CostCalculator fuelUnits={fuelUnits} costPerUnit={costPerUnit} calculatedCost={calculatedCost} />
|
||||
</Grid>
|
||||
<Grid item xs={12}>
|
||||
<Controller name="locationData" control={control} render={({ field }) => (
|
||||
|
||||
@@ -31,7 +31,7 @@ interface FuelLogsListProps {
|
||||
export const FuelLogsList: React.FC<FuelLogsListProps> = ({ logs, onEdit, onDelete }) => {
|
||||
const theme = useTheme();
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
|
||||
const { unitSystem, convertDistance, convertVolume } = useUnits();
|
||||
const { unitSystem, convertDistance, convertVolume, currencySymbol } = useUnits();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [logToDelete, setLogToDelete] = useState<FuelLogResponse | null>(null);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
@@ -145,7 +145,7 @@ export const FuelLogsList: React.FC<FuelLogsListProps> = ({ logs, onEdit, onDele
|
||||
if (unitSystem === 'metric') {
|
||||
const km = convertDistance(miles);
|
||||
const liters = convertVolume(gallons);
|
||||
if (liters > 0) localEffLabel = `${(km / liters).toFixed(1)} km/L`;
|
||||
if (km > 0) localEffLabel = `${((liters / km) * 100).toFixed(1)} L/100km`;
|
||||
} else {
|
||||
localEffLabel = `${(miles / gallons).toFixed(1)} MPG`;
|
||||
}
|
||||
@@ -173,8 +173,8 @@ export const FuelLogsList: React.FC<FuelLogsListProps> = ({ logs, onEdit, onDele
|
||||
gap: isMobile ? 0.5 : 1
|
||||
}}>
|
||||
<ListItemText
|
||||
primary={`${dateText} – $${totalCost}`}
|
||||
secondary={`${fuelUnits} @ $${costPerUnit} • ${distanceText}`}
|
||||
primary={`${dateText} \u2013 ${currencySymbol}${totalCost}`}
|
||||
secondary={`${fuelUnits} @ ${currencySymbol}${costPerUnit} \u2022 ${distanceText}`}
|
||||
sx={{ flex: 1, minWidth: 0 }}
|
||||
/>
|
||||
{(log.efficiency && typeof log.efficiency === 'number' && !isNaN(log.efficiency) && log.efficiencyLabel) || localEffLabel ? (
|
||||
@@ -262,7 +262,7 @@ export const FuelLogsList: React.FC<FuelLogsListProps> = ({ logs, onEdit, onDele
|
||||
</Typography>
|
||||
{logToDelete && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
|
||||
{new Date(logToDelete.dateTime).toLocaleString()} - ${logToDelete.totalCost.toFixed(2)}
|
||||
{new Date(logToDelete.dateTime).toLocaleString()} - {currencySymbol}{logToDelete.totalCost.toFixed(2)}
|
||||
</Typography>
|
||||
)}
|
||||
</DialogContent>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { FuelLogResponse } from '../types/fuel-logs.types';
|
||||
import { useUnits } from '../../../core/units/UnitsContext';
|
||||
|
||||
export const FuelStatsCard: React.FC<{ logs?: FuelLogResponse[] }> = ({ logs }) => {
|
||||
const { unitSystem } = useUnits();
|
||||
const { unitSystem, currencySymbol } = useUnits();
|
||||
const stats = useMemo(() => {
|
||||
if (!logs || logs.length === 0) return { count: 0, totalUnits: 0, totalCost: 0 };
|
||||
|
||||
@@ -37,7 +37,7 @@ export const FuelStatsCard: React.FC<{ logs?: FuelLogResponse[] }> = ({ logs })
|
||||
</Grid>
|
||||
<Grid item xs={4}>
|
||||
<Typography variant="overline" color="text.secondary">Total Cost</Typography>
|
||||
<Typography variant="h6">${(typeof stats.totalCost === 'number' && !isNaN(stats.totalCost) ? stats.totalCost : 0).toFixed(2)}</Typography>
|
||||
<Typography variant="h6">{currencySymbol}{(typeof stats.totalCost === 'number' && !isNaN(stats.totalCost) ? stats.totalCost : 0).toFixed(2)}</Typography>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</CardContent>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { UnitSystem } from '../types/fuel-logs.types';
|
||||
|
||||
export const UnitSystemDisplay: React.FC<{ unitSystem?: UnitSystem; showLabel?: string }> = ({ unitSystem, showLabel }) => {
|
||||
if (!unitSystem) return null;
|
||||
const label = unitSystem === 'imperial' ? 'Imperial (miles, gallons, MPG)' : 'Metric (km, liters, km/L)';
|
||||
const label = unitSystem === 'imperial' ? 'Imperial (miles, gallons, MPG)' : 'Metric (km, liters, L/100km)';
|
||||
return (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{showLabel ? `${showLabel} ` : ''}{label}
|
||||
|
||||
13
frontend/src/features/settings/api/preferences.api.ts
Normal file
13
frontend/src/features/settings/api/preferences.api.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* @ai-summary API client for user preferences endpoints
|
||||
* @ai-context Handles unit system, currency, and timezone preferences sync
|
||||
*/
|
||||
|
||||
import { apiClient } from '../../../core/api/client';
|
||||
import { UserPreferences, UpdatePreferencesRequest } from '../types/preferences.types';
|
||||
|
||||
export const preferencesApi = {
|
||||
getPreferences: () => apiClient.get<UserPreferences>('/user/preferences'),
|
||||
updatePreferences: (data: UpdatePreferencesRequest) =>
|
||||
apiClient.put<UserPreferences>('/user/preferences', data),
|
||||
};
|
||||
61
frontend/src/features/settings/hooks/usePreferences.ts
Normal file
61
frontend/src/features/settings/hooks/usePreferences.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* @ai-summary React hooks for user preferences management
|
||||
* @ai-context Handles unit system, currency, and timezone preference sync with backend
|
||||
*/
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useAuth0 } from '@auth0/auth0-react';
|
||||
import { preferencesApi } from '../api/preferences.api';
|
||||
import { UpdatePreferencesRequest } from '../types/preferences.types';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
interface ApiError {
|
||||
response?: {
|
||||
data?: {
|
||||
error?: string;
|
||||
message?: string;
|
||||
};
|
||||
};
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export const usePreferences = () => {
|
||||
const { isAuthenticated, isLoading } = useAuth0();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['user-preferences'],
|
||||
queryFn: async () => {
|
||||
const response = await preferencesApi.getPreferences();
|
||||
return response.data;
|
||||
},
|
||||
enabled: isAuthenticated && !isLoading,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
gcTime: 10 * 60 * 1000, // 10 minutes cache time
|
||||
retry: (failureCount, error: any) => {
|
||||
// Retry 401s a few times (auth token might be refreshing)
|
||||
if (error?.response?.status === 401 && failureCount < 3) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdatePreferences = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: UpdatePreferencesRequest) => preferencesApi.updatePreferences(data),
|
||||
onSuccess: (response) => {
|
||||
queryClient.setQueryData(['user-preferences'], response.data);
|
||||
// Don't show toast for unit system changes - context handles UI feedback
|
||||
},
|
||||
onError: (error: ApiError) => {
|
||||
const message = error.response?.data?.message || error.response?.data?.error || 'Failed to update preferences';
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useSettingsPersistence, SettingsState } from './useSettingsPersistence';
|
||||
import { useUnits } from '../../../core/units/UnitsContext';
|
||||
|
||||
const defaultSettings: SettingsState = {
|
||||
darkMode: false,
|
||||
@@ -13,10 +14,12 @@ const defaultSettings: SettingsState = {
|
||||
|
||||
export const useSettings = () => {
|
||||
const { loadSettings, saveSettings } = useSettingsPersistence();
|
||||
const { unitSystem: contextUnitSystem, setUnitSystem: setContextUnitSystem } = useUnits();
|
||||
const [settings, setSettings] = useState<SettingsState>(defaultSettings);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Load settings from localStorage on mount
|
||||
useEffect(() => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
@@ -33,6 +36,13 @@ export const useSettings = () => {
|
||||
}
|
||||
}, [loadSettings]);
|
||||
|
||||
// Sync unitSystem from context (which may load from backend)
|
||||
useEffect(() => {
|
||||
if (contextUnitSystem && contextUnitSystem !== settings.unitSystem) {
|
||||
setSettings(prev => ({ ...prev, unitSystem: contextUnitSystem }));
|
||||
}
|
||||
}, [contextUnitSystem, settings.unitSystem]);
|
||||
|
||||
const updateSetting = <K extends keyof SettingsState>(
|
||||
key: K,
|
||||
value: SettingsState[K]
|
||||
@@ -42,6 +52,11 @@ export const useSettings = () => {
|
||||
const newSettings = { ...settings, [key]: value };
|
||||
setSettings(newSettings);
|
||||
saveSettings(newSettings);
|
||||
|
||||
// Sync unitSystem changes to context (which syncs to backend)
|
||||
if (key === 'unitSystem' && typeof value === 'string') {
|
||||
setContextUnitSystem(value as 'imperial' | 'metric');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save settings');
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ export const MobileSettingsScreen: React.FC = () => {
|
||||
<div>
|
||||
<p className="font-medium text-slate-800">Unit System</p>
|
||||
<p className="text-sm text-slate-500">
|
||||
Currently using {settings.unitSystem === 'imperial' ? 'Miles & Gallons' : 'Kilometers & Liters'}
|
||||
Currently using {settings.unitSystem === 'imperial' ? 'Miles, Gallons, MPG, USD' : 'Km, Liters, L/100km, EUR'}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
|
||||
22
frontend/src/features/settings/types/preferences.types.ts
Normal file
22
frontend/src/features/settings/types/preferences.types.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @ai-summary Type definitions for user preferences
|
||||
* @ai-context Types for unit system, currency, and timezone preferences
|
||||
*/
|
||||
|
||||
import { UnitSystem } from '../../../core/units/units.types';
|
||||
|
||||
export interface UserPreferences {
|
||||
id: string;
|
||||
userId: string;
|
||||
unitSystem: UnitSystem;
|
||||
currencyCode: string;
|
||||
timeZone: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UpdatePreferencesRequest {
|
||||
unitSystem?: UnitSystem;
|
||||
currencyCode?: string;
|
||||
timeZone?: string;
|
||||
}
|
||||
@@ -324,7 +324,7 @@ export const SettingsPage: React.FC = () => {
|
||||
<ListItem>
|
||||
<ListItemText
|
||||
primary="Units for distance and capacity"
|
||||
secondary="Choose between Imperial (miles, gallons) or Metric (kilometers, liters)"
|
||||
secondary="Imperial: miles, gallons, MPG, USD | Metric: km, liters, L/100km, EUR"
|
||||
sx={{ pl: 7 }}
|
||||
/>
|
||||
<ListItemSecondaryAction>
|
||||
|
||||
@@ -525,9 +525,6 @@ export const AdminCatalogPage: React.FC = () => {
|
||||
<Typography>
|
||||
<strong>To Update:</strong> {importPreview.toUpdate.length}
|
||||
</Typography>
|
||||
<Typography>
|
||||
<strong>To Delete:</strong> {importPreview.toDelete.length}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Errors */}
|
||||
|
||||
Reference in New Issue
Block a user