fix: back-merge v3.1.4 hotfixes into dev (#1371)

Port the three main-only fixes onto dev's (post-rewrite) architecture:
- fix(backups): prevent recursion when the backup path sits inside the backed-up dir
- fix(share): convert budget items to the viewer's base currency instead of a flat EUR
- fix(files): surface the descriptive server error for unsupported upload types (#1363)

Cherry-picked from 819aa793 on main; the SharedTripPage and useTripPlanner
conflicts were resolved to keep dev's font-scaling and full import set while
taking the fixes' currency conversion and translateApiError wiring.
This commit is contained in:
jubnl
2026-07-01 18:57:16 +02:00
committed by Maurice
parent 3686792ce8
commit 60cbd20327
37 changed files with 276 additions and 18 deletions
@@ -1,7 +1,7 @@
import { useState, useCallback, useEffect } from 'react'
import { useDropzone } from 'react-dropzone'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { useTranslation, translateApiError } from '../../i18n'
import { filesApi } from '../../api/client'
import type { Place, Reservation, TripFile, Day, AssignmentsMap } from '../../types'
import { useCanDo } from '../../store/permissionsStore'
@@ -119,8 +119,8 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
if (lastId && (places.length > 0 || reservations.length > 0)) {
setAssignFileId(lastId)
}
} catch {
toast.error(t('files.uploadError'))
} catch (err) {
toast.error(translateApiError(t, err, 'files.uploadError'))
} finally {
setUploading(false)
}
@@ -14,7 +14,7 @@ import { useAddonStore } from '../../store/addonStore'
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
import { getCategoryIcon } from '../shared/categoryIcons'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { useTranslation, translateApiError } from '../../i18n'
import type { Place, Category, Day, Assignment, Reservation, TripFile, AssignmentsMap } from '../../types'
import type { CollectionStatus } from '@trek/shared'
import { splitReservationDateTime, formatTime } from '../../utils/formatters'
@@ -255,7 +255,7 @@ export default function PlaceInspector({
setFilesExpanded(true)
} catch (err: unknown) {
console.error('Upload failed', err)
toast.error(t('files.uploadError'))
toast.error(translateApiError(t, err, 'files.uploadError'))
} finally {
setIsUploading(false)
if (fileInputRef.current) fileInputRef.current.value = ''
+1
View File
@@ -8,3 +8,4 @@ export {
SUPPORTED_LANGUAGES,
} from './TranslationContext'
export { TransHtml } from './TransHtml'
export { translateApiError } from './translateApiError'
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest'
import { translateApiError } from './translateApiError'
// Mimics the real t(): returns a translation for known keys, the key itself otherwise.
const dict: Record<string, string> = {
'files.uploadErrorType': "This file type isn't supported",
'files.uploadError': 'Upload failed',
}
const t = (key: string) => dict[key] ?? key
describe('translateApiError', () => {
it('resolves a server message that is a known i18n key', () => {
const err = new Error('files.uploadErrorType')
expect(translateApiError(t, err, 'files.uploadError')).toBe("This file type isn't supported")
})
it('falls back to the generic key when the message is a plain string', () => {
const err = new Error('Some raw server message')
expect(translateApiError(t, err, 'files.uploadError')).toBe('Upload failed')
})
it('falls back when the message is an empty string', () => {
expect(translateApiError(t, new Error(''), 'files.uploadError')).toBe('Upload failed')
})
it('falls back when the thrown value is not an Error', () => {
expect(translateApiError(t, 'nope', 'files.uploadError')).toBe('Upload failed')
expect(translateApiError(t, undefined, 'files.uploadError')).toBe('Upload failed')
})
})
+17
View File
@@ -0,0 +1,17 @@
/**
* Resolve a server error whose message may be an i18n key.
*
* The server can return a translation key as its error message (e.g.
* `files.uploadErrorType`). `t()` returns the key unchanged when it isn't a
* known translation, so `translated === key` reliably means "not a key" — in
* that case we fall back to a generic, always-localized message.
*/
export function translateApiError(
t: (key: string) => string,
err: unknown,
fallbackKey: string,
): string {
const key = err instanceof Error ? err.message : ''
const translated = t(key)
return translated && translated !== key ? translated : t(fallbackKey)
}
+63
View File
@@ -509,4 +509,67 @@ describe('SharedTripPage', () => {
await waitFor(() => expect(screen.getByText('Tag 1')).toBeInTheDocument());
});
});
describe('FE-PAGE-SHARED-019: budget renders in the owner\'s baseCurrency, not the EUR trip fallback (#1361)', () => {
it('labels totals with the payload baseCurrency even when the trip currency is EUR', async () => {
server.use(
// No FX needed when the expense is already in the base; stub frankfurter so
// the live-rate fetch never hits the network in tests.
http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])),
http.get('/api/shared/:token', ({ params }) => {
if (params.token !== 'cad-token') return;
return HttpResponse.json({
trip: { id: 1, title: 'Shared Paris Trip', start_date: '2026-07-01', end_date: '2026-07-05', currency: 'EUR' },
baseCurrency: 'CAD',
days: [], assignments: {}, dayNotes: {}, places: [], reservations: [], accommodations: [], packing: [],
budget: [{ id: 1, name: 'Hotel', total_price: '200', category: 'Accommodation', currency: 'CAD' }],
categories: [],
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
collab: [],
});
}),
);
renderSharedTrip('cad-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /budget/i }));
await waitFor(() => expect(screen.getByText('Hotel')).toBeInTheDocument());
// Total + per-row labelled CAD; never the EUR fallback.
expect(screen.getAllByText(/200\.00 CAD/).length).toBeGreaterThan(0);
expect(screen.queryByText(/EUR/)).toBeNull();
});
});
describe('FE-PAGE-SHARED-020: mixed-currency expenses convert into baseCurrency via live FX (#1361)', () => {
it('converts a EUR expense into the base using fetched rates', async () => {
// Distinct base (NZD) so this test can't read the cached CAD rates seeded by
// FE-PAGE-SHARED-019 (useExchangeRates caches per base in module memory).
server.use(
// rates[X] = units of X per 1 base(NZD); 0.8 EUR per NZD → 100 EUR = 125.00 NZD
// (a clean 2-decimal result, distinct from the unconverted 100).
http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([{ quote: 'EUR', rate: 0.8 }])),
http.get('/api/shared/:token', ({ params }) => {
if (params.token !== 'mixed-token') return;
return HttpResponse.json({
trip: { id: 1, title: 'Shared Paris Trip', start_date: '2026-07-01', end_date: '2026-07-05', currency: 'EUR' },
baseCurrency: 'NZD',
days: [], assignments: {}, dayNotes: {}, places: [], reservations: [], accommodations: [], packing: [],
budget: [{ id: 1, name: 'Dinner', total_price: '100', category: 'Food', currency: 'EUR' }],
categories: [],
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
collab: [],
});
}),
);
renderSharedTrip('mixed-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /budget/i }));
await waitFor(() => expect(screen.getByText('Dinner')).toBeInTheDocument());
// 100 EUR / 0.8 = 125.00 NZD once the rate resolves.
await waitFor(() => expect(screen.getAllByText(/125\.00 NZD/).length).toBeGreaterThan(0));
});
});
});
+9 -5
View File
@@ -42,7 +42,7 @@ function FitBoundsToPlaces({ places }: { places: any[] }) {
export default function SharedTripPage() {
const { t, locale } = useTranslation()
// Page = wiring container: share fetch + view state live in the hook.
const { data, error, selectedDay, setSelectedDay, activeTab, setActiveTab, showLangPicker, setShowLangPicker } = useSharedTrip()
const { data, error, base, convert, selectedDay, setSelectedDay, activeTab, setActiveTab, showLangPicker, setShowLangPicker } = useSharedTrip()
if (error) return (
<div className="bg-[#f3f4f6]" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
@@ -328,26 +328,30 @@ export default function SharedTripPage() {
{/* Budget */}
{activeTab === 'budget' && (budget || []).length > 0 && (() => {
// Pre-rework rows store currency = NULL ("the trip's own currency"); convert
// each expense into the owner's display base via live FX, mirroring CostsPanel.
const curOf = (i: any) => i.currency || trip.currency || base
const grouped = (budget || []).reduce((g: any, i: any) => { const c = i.category || t('shared.other'); (g[c] = g[c] || []).push(i); return g }, {})
const total = (budget || []).reduce((s: number, i: any) => s + (parseFloat(i.total_price) || 0), 0)
const sumIn = (items: any[]) => items.reduce((s: number, i: any) => s + convert(parseFloat(i.total_price) || 0, curOf(i)), 0)
const total = sumIn(budget || [])
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* Total card */}
<div className="text-white" style={{ background: 'linear-gradient(135deg, #000 0%, #1a1a2e 100%)', borderRadius: 14, padding: '20px 24px' }}>
<div style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 500, letterSpacing: 1, textTransform: 'uppercase', opacity: 0.5 }}>{t('shared.totalBudget')}</div>
<div style={{ fontSize: 'calc(28px * var(--fs-scale-title, 1))', fontWeight: 700, marginTop: 4 }}>{total.toLocaleString(locale, { minimumFractionDigits: 2 })} {trip.currency || 'EUR'}</div>
<div style={{ fontSize: 'calc(28px * var(--fs-scale-title, 1))', fontWeight: 700, marginTop: 4 }}>{total.toLocaleString(locale, { minimumFractionDigits: 2 })} {base}</div>
</div>
{/* By category */}
{Object.entries(grouped).map(([cat, items]: [string, any]) => (
<div key={cat} className="bg-surface-card border border-edge-faint" style={{ borderRadius: 12, overflow: 'hidden' }}>
<div className="bg-[#f9fafb]" style={{ padding: '10px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #f3f4f6' }}>
<span className="text-[#374151]" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 700 }}>{cat}</span>
<span className="text-[#6b7280]" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{items.reduce((s: number, i: any) => s + (parseFloat(i.total_price) || 0), 0).toLocaleString(locale, { minimumFractionDigits: 2 })} {trip.currency || ''}</span>
<span className="text-[#6b7280]" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{sumIn(items).toLocaleString(locale, { minimumFractionDigits: 2 })} {base}</span>
</div>
{items.map((item: any) => (
<div key={item.id} style={{ padding: '8px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #fafafa' }}>
<span className="text-[#111827]" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{item.name}</span>
<span className="text-[#111827]" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{item.total_price ? Number(item.total_price).toLocaleString(locale, { minimumFractionDigits: 2 }) : '—'}</span>
<span className="text-[#111827]" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{item.total_price ? `${convert(parseFloat(item.total_price) || 0, curOf(item)).toLocaleString(locale, { minimumFractionDigits: 2 })} ${base}` : '—'}</span>
</div>
))}
</div>
+9 -1
View File
@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { shareApi } from '../../api/client'
import { useExchangeRates } from '../../hooks/useExchangeRates'
/**
* Shared-trip (public) data hook — owns the token lookup, the read-only share
@@ -24,5 +25,12 @@ export function useSharedTrip() {
shareApi.getSharedTrip(token).then(setData).catch(() => setError(true))
}, [token])
return { data, error, selectedDay, setSelectedDay, activeTab, setActiveTab, showLangPicker, setShowLangPicker }
// Budget display currency = what the share owner sees in Costs (embedded in the
// payload as baseCurrency), falling back to the trip's own currency, then EUR.
// Convert every expense into it via live FX, mirroring CostsPanel — a public
// viewer has no settings store, so the base comes from the payload (#1361).
const base = String(data?.baseCurrency || data?.trip?.currency || 'EUR').toUpperCase()
const { convert } = useExchangeRates(base)
return { data, error, base, convert, selectedDay, setSelectedDay, activeTab, setActiveTab, showLangPicker, setShowLangPicker }
}
@@ -6,7 +6,7 @@ import { useSettingsStore } from '../../store/settingsStore'
import { getCached, fetchPhoto } from '../../services/photoService'
import { useToast } from '../../components/shared/Toast'
import { Map, Ticket, PackageCheck, Wallet, FolderOpen, Users, Train } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useTranslation, translateApiError } from '../../i18n'
import { addonsApi, accommodationsApi, authApi, tripsApi, assignmentsApi, healthApi, airtrailApi, mapsApi, placesApi } from '../../api/client'
import { parsedItemToDraft, isTransportItem, type BookingReviewDraft } from '../../components/Planner/parsedItemToDraft'
import type { BookingImportPreviewItem } from '@trek/shared'
@@ -426,7 +426,7 @@ export function useTripPlanner() {
const fd = new FormData()
fd.append('file', file)
fd.append('place_id', String(editingPlace.id))
try { await tripActions.addFile(tripId, fd) } catch { toast.error(t('files.uploadError')) }
try { await tripActions.addFile(tripId, fd) } catch (err) { toast.error(translateApiError(t, err, 'files.uploadError')) }
}
}
toast.success(t('trip.toast.placeUpdated'))
@@ -437,7 +437,7 @@ export function useTripPlanner() {
const fd = new FormData()
fd.append('file', file)
fd.append('place_id', String(place.id))
try { await tripActions.addFile(tripId, fd) } catch { toast.error(t('files.uploadError')) }
try { await tripActions.addFile(tripId, fd) } catch (err) { toast.error(translateApiError(t, err, 'files.uploadError')) }
}
}
toast.success(t('trip.toast.placeAdded'))