fix(client): convert mixed-currency day/trip cost totals instead of mislabeling raw sums (#1561)

Day headers, the plan sidebar footer and the PDF day/cover totals summed
raw place prices across currencies and labeled the result with a single
currency — a $2,730.27 hotel on a NOK trip read as "2730 NOK".

Totals now convert every amount into a base currency via the existing
frankfurter rates (sidebar: the user's display currency, falling back to
the trip's; PDF: the trip currency, resolved once before rendering so the
document is consistent), marked with "≈" when a conversion happened. When
a rate is unavailable (offline, blocked egress, unknown code) they fall
back to an honest per-currency breakdown ("2 500 kr + $2,730.27") instead
of folding foreign amounts into a mislabeled number. All-same-currency
trips make no FX request, so offline PDF export keeps working.

Also swaps the place inspector's hardcoded € chip icon for a neutral one
and formats the price via formatMoney in the place's own currency.

Note: day-header totals move from "50 EUR" to Intl formatting ("50 €").
This commit is contained in:
jubnl
2026-07-18 19:38:35 +02:00
parent 1de643e34d
commit 3bd17ce1f9
12 changed files with 452 additions and 55 deletions
+62
View File
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { downloadTripPDF } from './TripPDF'
import { server } from '../../../tests/helpers/msw/server'
import { clearExchangeRateCache } from '../../hooks/useExchangeRates'
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -50,7 +51,11 @@ beforeEach(() => {
http.get('/api/pdf-sections/:tripId', () =>
HttpResponse.json({ sections: [] })
),
// Mixed-currency exports fetch FX rates; keep the suite hermetic.
http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])),
)
// The FX cache is module-level and would leak rates between tests in this file.
clearExchangeRateCache()
})
afterEach(() => {
@@ -329,6 +334,63 @@ describe('downloadTripPDF', () => {
expect(iframe!.srcdoc).toContain('¥1,500')
})
it('FE-COMP-TRIPPDF-016d: converts foreign-currency prices into the trip currency for day and cover totals (#1561)', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', ({ request }) => {
expect(new URL(request.url).searchParams.get('base')).toBe('NOK')
return HttpResponse.json([{ quote: 'USD', rate: 0.1 }]) // 1 NOK = 0.1 USD
}))
const mixedArgs = {
...richArgs,
trip: { ...richArgs.trip, currency: 'NOK' },
assignments: {
'10': [
{ ...assignmentForDay, place: { ...placeWithDetails, currency: 'USD', price: '273' } },
{ ...assignmentForDay, id: 201, place: { ...placeWithDetails, id: 101, name: 'Museum', currency: null, price: '2500' } },
],
} as any,
}
await downloadTripPDF(mixedArgs)
const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ')
// 2500 NOK + 273 USD / 0.1 = 5230 NOK, marked approximate, in day header AND cover stat.
expect(srcdoc).toContain('≈ 5 230,00 kr')
expect((srcdoc.match(/≈ 5 230,00 kr/g) || []).length).toBeGreaterThanOrEqual(2)
})
it('FE-COMP-TRIPPDF-016e: falls back to per-currency breakdowns when the FX fetch fails (#1561)', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.error()))
const mixedArgs = {
...richArgs,
trip: { ...richArgs.trip, currency: 'NOK' },
assignments: {
'10': [
{ ...assignmentForDay, place: { ...placeWithDetails, currency: 'USD', price: '2730.27' } },
{ ...assignmentForDay, id: 201, place: { ...placeWithDetails, id: 101, name: 'Museum', currency: null, price: '2500' } },
],
} as any,
}
// Export still resolves — a dead FX endpoint must never break the PDF.
await expect(downloadTripPDF(mixedArgs)).resolves.not.toThrow()
const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ')
// Honest breakdown, base currency first; the USD amount is never NOK-labeled.
expect(srcdoc).toContain('2 500,00 kr + $2,730.27')
expect(srcdoc).not.toContain('≈')
expect(srcdoc).not.toMatch(/5 ?230/)
})
it('FE-COMP-TRIPPDF-016f: an all-same-currency trip makes no FX request', async () => {
let fxCalled = false
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => {
fxCalled = true
return HttpResponse.json([])
}))
await downloadTripPDF({ ...richArgs, trip: { ...richArgs.trip, currency: 'EUR' } })
expect(fxCalled).toBe(false)
// Totals render exactly as before for the single-currency case.
const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ')
expect(srcdoc).toContain('15,00 €')
expect(srcdoc).not.toContain('≈')
})
it('FE-COMP-TRIPPDF-017: renders trip description on cover', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
+26 -9
View File
@@ -5,7 +5,8 @@ import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship
import { accommodationsApi, mapsApi, pluginsApi } from '../../api/client'
import type { Trip, Day, Place, Category, AssignmentsMap, DayNote } from '../../types'
import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder'
import { formatMoney, splitReservationDateTime } from '../../utils/formatters'
import { formatMoney, formatMoneySum, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters'
import { fetchExchangeRates } from '../../hooks/useExchangeRates'
import { getFlightLegs, getTrainLegs } from '../../utils/flightLegs'
function renderLucideIcon(icon:LucideIcon, props = {}) {
@@ -92,9 +93,15 @@ function longDateRange(days, locale) {
return `${f.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' })} – ${l.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' })}`
}
function dayCost(assignments, dayId, locale, currency) {
const total = (assignments[String(dayId)] || []).reduce((s, a) => s + (parseFloat(a.place?.price) || 0), 0)
return total > 0 ? formatMoney(total, currency, locale) : null
// Day totals render in the trip's currency; foreign-currency place prices are
// converted via the pre-fetched rates, or listed per-currency when rates are
// unavailable (#1561).
function dayCost(assignments, dayId, locale, tripCurrency, rates) {
const entries: MoneyEntry[] = (assignments[String(dayId)] || []).map(a => ({
amount: parseFloat(a.place?.price) || 0,
currency: a.place?.currency || tripCurrency,
}))
return formatMoneySum(entries, tripCurrency, locale || 'en', rates)
}
// Pre-fetch place photos for all assigned places.
@@ -160,8 +167,18 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
const totalAssigned = new Set(
Object.values(assignments || {}).flatMap(a => a.map(x => x.place?.id)).filter(Boolean)
).size
const totalCost = Object.values(assignments || {})
.flatMap(a => a).reduce((s, a) => s + (Number(a.place?.price) || 0), 0)
// The PDF is a trip-scoped, shareable document, so totals stay in the trip's
// own currency. Rates are resolved ONCE before any HTML is built so the cover
// stat and every day header agree; all-same-currency trips skip the FX fetch
// entirely (offline export keeps working), and a failed fetch degrades to
// per-currency breakdowns instead of mislabeled sums (#1561).
const tripCur = (trip?.currency || 'EUR').toUpperCase()
const allCostEntries: MoneyEntry[] = Object.values(assignments || {})
.flatMap(a => a)
.map(a => ({ amount: Number(a.place?.price) || 0, currency: a.place?.currency || tripCur }))
const needsFx = allCostEntries.some(e => e.amount > 0 && e.currency.toUpperCase() !== tripCur)
const fxRates = needsFx ? await fetchExchangeRates(tripCur) : null
const totalCostLabel = formatMoneySum(allCostEntries, tripCur, loc || 'en', fxRates)
// Span helpers for multi-day transport (mirrors DayPlanSidebar logic)
const pdfGetDayOrder = (d: Day) => d.day_number
@@ -204,7 +221,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
const daysHtml = sorted.map((day, di) => {
const assigned = assignments[String(day.id)] || []
const notes = (dayNotes || []).filter(n => n.day_id === day.id)
const cost = dayCost(assignments, day.id, loc, trip.currency)
const cost = dayCost(assignments, day.id, loc, tripCur, fxRates)
// Reservations for this day (hotel rendered via accommodations block; car middle-phase rendered in sidebar header only)
const dayReservations = pdfGetTransportForDay(day.id)
@@ -624,8 +641,8 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
<div class="cover-stat-num">${totalAssigned}</div>
<div class="cover-stat-lbl">${escHtml(tr('pdf.planned'))}</div>
</div>
${totalCost > 0 ? `<div>
<div class="cover-stat-num">${formatMoney(totalCost, trip.currency, loc)}</div>
${totalCostLabel ? `<div>
<div class="cover-stat-num">${totalCostLabel}</div>
<div class="cover-stat-lbl">${escHtml(tr('pdf.costLabel'))}</div>
</div>` : ''}
</div>
@@ -1,6 +1,9 @@
// FE-PLANNER-DAYPLAN-001 to FE-PLANNER-DAYPLAN-042
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
import { server } from '../../../tests/helpers/msw/server'
import { clearExchangeRateCache } from '../../hooks/useExchangeRates'
import { useAuthStore } from '../../store/authStore'
import { useTripStore } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
@@ -130,6 +133,9 @@ beforeEach(() => {
vi.clearAllMocks()
sessionStorage.clear()
localStorage.clear()
// Cost totals fetch FX rates for their base currency; keep the suite hermetic.
clearExchangeRateCache()
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])))
// Reset mutable day-notes state
mockDayNotesState.noteUi = {}
mockDayNotesState.dayNotes = {}
@@ -602,6 +608,50 @@ describe('DayPlanSidebar', () => {
expect(screen.getByText('Total Cost')).toBeInTheDocument()
})
it('FE-PLANNER-DAYPLAN-037b: converts foreign-currency prices into the display currency (#1561)', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', ({ request }) => {
expect(new URL(request.url).searchParams.get('base')).toBe('USD')
return HttpResponse.json([{ quote: 'NOK', rate: 10 }]) // 10 NOK per 1 USD
}))
seedStore(useSettingsStore, { settings: { time_format: '24h', default_currency: 'USD' } } as any)
const placeUsd = buildPlace({ id: 1, name: 'Hotel', price: 25, currency: 'USD' } as any)
const placeNok = buildPlace({ id: 2, name: 'Museum', price: 250, currency: null } as any) // implicit trip currency
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
render(<DayPlanSidebar {...makeDefaultProps({
days: [day],
places: [placeUsd, placeNok],
assignments: { '10': [
buildAssignment({ id: 1, day_id: 10, order_index: 0, place: placeUsd }),
buildAssignment({ id: 2, day_id: 10, order_index: 1, place: placeNok }),
] },
trip: buildTrip({ id: 1, currency: 'NOK' }),
})} />)
// $25 + 250 NOK / 10 = $50, marked as approximate; footer and day header agree.
await waitFor(() => expect(screen.getByText('≈ $50.00')).toBeInTheDocument())
expect(screen.getByText('≈ $50')).toBeInTheDocument()
})
it('FE-PLANNER-DAYPLAN-037c: falls back to a per-currency breakdown when rates are unavailable (#1561)', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.error()))
const placeUsd = buildPlace({ id: 1, name: 'Hotel', price: 2730.27, currency: 'USD' } as any)
const placeNok = buildPlace({ id: 2, name: 'Museum', price: 2500, currency: 'NOK' } as any)
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
render(<DayPlanSidebar {...makeDefaultProps({
days: [day],
places: [placeUsd, placeNok],
assignments: { '10': [
buildAssignment({ id: 1, day_id: 10, order_index: 0, place: placeUsd }),
buildAssignment({ id: 2, day_id: 10, order_index: 1, place: placeNok }),
] },
trip: buildTrip({ id: 1, currency: 'NOK' }),
})} />)
// The USD amount must never be folded into a NOK-labeled number (the #1561 bug):
// footer keeps each currency separate, base (NOK) first.
await waitFor(() => expect(screen.getByText(/kr.*\+.*\$2,730\.27|2\s?500,00\s?kr.*\+/)).toBeInTheDocument())
expect(screen.queryByText(/≈/)).toBeNull()
expect(screen.queryByText(/5\s?230/)).toBeNull()
})
// ── Route tools (Optimize / Google Maps) ────────────────────────────────
it('FE-PLANNER-DAYPLAN-038: optimize button calls onReorder with 3 geo-places', async () => {
@@ -28,8 +28,9 @@ import {
getTransportForDay as _getTransportForDay, getMergedItems as _getMergedItems,
type MergedItem,
} from '../../utils/dayMerge'
import { formatDate, formatTime, dayTotalCost, splitReservationDateTime } from '../../utils/formatters'
import { formatDate, formatTime, dayTotalCost, formatMoneySum, splitReservationDateTime } from '../../utils/formatters'
import { useDayNotes } from '../../hooks/useDayNotes'
import { useExchangeRates } from '../../hooks/useExchangeRates'
import { RES_ICONS, getNoteIcon } from './DayPlanSidebar.constants'
import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector'
import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton'
@@ -240,6 +241,12 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
}, [selectedAssignmentId, selectedPlaceId])
const currency = trip?.currency || 'EUR'
// Cost totals render in the user's display currency (falling back to the
// trip's), converting foreign-currency place prices via live FX rates —
// same base resolution as BookingCostsSection / the Costs panel (#1561).
const displayCurrency = useSettingsStore(s => s.settings.default_currency)
const costBase = (displayCurrency || currency).toUpperCase()
const { rates: fxRates } = useExchangeRates(costBase)
// Drag-Daten aus dataTransfer, Ref oder window lesen (dataTransfer geht bei Re-Render verloren)
const getDragData = (e) => {
@@ -969,10 +976,13 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
setDraggingId(null)
}
const totalCost = useMemo(() => days.reduce((s, d) => {
const da = assignments[String(d.id)] || []
return s + da.reduce((s2, a) => s2 + (Number(a.place?.price) || 0), 0)
}, 0), [days, assignments])
const totalCostLabel = useMemo(() => {
const entries = days.flatMap(d => (assignments[String(d.id)] || []).map(a => ({
amount: Number(a.place?.price) || 0,
currency: a.place?.currency || currency,
})))
return formatMoneySum(entries, costBase, locale, fxRates)
}, [days, assignments, currency, costBase, locale, fxRates])
// Bester verfügbarer Standort für Wetter: zugewiesene Orte zuerst, dann beliebiger Reiseort
const anyGeoAssignment = Object.values(assignments).flatMap(da => da).find(a => a.place?.lat && a.place?.lng)
@@ -1101,6 +1111,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
initedTransportIds,
lastAutoScrolledIdRef,
currency,
costBase,
fxRates,
getDragData,
prevDayCount,
toggleDay,
@@ -1125,7 +1137,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
handleOptimize,
handleDropOnDay,
handleDropOnRow,
totalCost,
totalCostLabel,
anyGeoAssignment,
anyGeoPlace,
expandedRouteDayIds,
@@ -1268,6 +1280,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
initedTransportIds,
lastAutoScrolledIdRef,
currency,
costBase,
fxRates,
getDragData,
prevDayCount,
toggleDay,
@@ -1292,7 +1306,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
handleOptimize,
handleDropOnDay,
handleDropOnRow,
totalCost,
totalCostLabel,
anyGeoAssignment,
anyGeoPlace,
expandedRouteDayIds,
@@ -1335,7 +1349,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const isSelected = selectedDayId === day.id
const isExpanded = expandedDays.has(day.id)
const da = getDayAssignments(day.id)
const cost = dayTotalCost(day.id, assignments, currency)
const cost = dayTotalCost(day.id, assignments, costBase, currency, locale, fxRates)
const formattedDate = formatDate(day.date, locale)
const loc = da.find(a => a.place?.lat && a.place?.lng)
// Route tools normally need 2+ stops, but a single located place is still
@@ -2496,7 +2510,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
/>
{/* Budget-Fußzeile */}
<DayPlanSidebarFooter totalCost={totalCost} currency={currency} t={t} />
<DayPlanSidebarFooter totalCostLabel={totalCostLabel} t={t} />
<ContextMenu menu={ctxMenu.menu} onClose={ctxMenu.close} />
</div>
)
@@ -1,17 +1,14 @@
import { currencyDecimals } from '../../utils/formatters'
interface DayPlanSidebarFooterProps {
totalCost: number
currency: string
totalCostLabel: string | null
t: (key: string, params?: Record<string, any>) => string
}
export function DayPlanSidebarFooter({ totalCost, currency, t }: DayPlanSidebarFooterProps) {
if (!(totalCost > 0)) return null
export function DayPlanSidebarFooter({ totalCostLabel, t }: DayPlanSidebarFooterProps) {
if (!totalCostLabel) return null
return (
<div className="border-t border-edge-faint" style={{ flexShrink: 0, padding: '10px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}>{t('dayplan.totalCost')}</span>
<span className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{totalCost.toFixed(currencyDecimals(currency))} {currency}</span>
<span className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{totalCostLabel}</span>
</div>
)
}
@@ -443,7 +443,24 @@ describe('PlaceInspector', () => {
it('FE-PLANNER-INSPECTOR-032: price chip shown when place.price > 0', () => {
const p = buildPlace({ id: 300, price: 15, currency: 'EUR' } as any);
render(<PlaceInspector {...defaultProps} place={p} />);
expect(screen.getByText(/15 EUR/)).toBeTruthy();
// formatMoney renders in the currency's home convention (de-DE for EUR).
expect(screen.getByText(/15,00/)).toBeTruthy();
});
it('FE-PLANNER-INSPECTOR-032b: price chip formats in the place currency with a neutral icon (#1561)', () => {
const p = buildPlace({ id: 300, price: 15, currency: 'USD' } as any);
render(<PlaceInspector {...defaultProps} place={p} />);
expect(screen.getByText('$15.00')).toBeTruthy();
// The chip icon must be currency-neutral, not the euro glyph.
expect(document.querySelector('.lucide-euro')).toBeNull();
expect(document.querySelector('.lucide-banknote')).not.toBeNull();
});
it('FE-PLANNER-INSPECTOR-032c: a currency-less price falls back to the trip currency (#1561)', () => {
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'NOK' }) } as any);
const p = buildPlace({ id: 300, price: 250, currency: null } as any);
render(<PlaceInspector {...defaultProps} place={p} />);
expect(screen.getByText(/250,00\s?kr|kr\s?250,00/)).toBeTruthy();
});
// ── Phone number ───────────────────────────────────────────────────────────
@@ -4,7 +4,7 @@ import { openFile } from '../../utils/fileDownload'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
import { X, Clock, MapPin, ExternalLink, Phone, Euro, Edit2, Trash2, Plus, Minus, ChevronDown, ChevronUp, FileText, Upload, File, FileImage, Star, Navigation, Map as MapIcon, Users, Mountain, TrendingUp, Bookmark, BookmarkCheck, Copy } from 'lucide-react'
import { X, Clock, MapPin, ExternalLink, Phone, Banknote, Edit2, Trash2, Plus, Minus, ChevronDown, ChevronUp, FileText, Upload, File, FileImage, Star, Navigation, Map as MapIcon, Users, Mountain, TrendingUp, Bookmark, BookmarkCheck, Copy } from 'lucide-react'
import PlaceAvatar from '../shared/PlaceAvatar'
import GuestBadge from '../shared/GuestBadge'
import StatusBadge from '../Collections/StatusBadge'
@@ -20,7 +20,8 @@ import { usePluginStore } from '../../store/pluginStore'
import PluginFrame from '../Plugins/PluginFrame'
import type { Place, Category, Day, Assignment, Reservation, TripFile, AssignmentsMap } from '../../types'
import type { CollectionStatus } from '@trek/shared'
import { splitReservationDateTime, formatTime } from '../../utils/formatters'
import { splitReservationDateTime, formatTime, formatMoney } from '../../utils/formatters'
import { useTripStore } from '../../store/tripStore'
import { formatDistance, formatElevation } from '../../utils/units'
import { getGoogleMapsUrlForPlace } from './placeGoogleMaps'
import { getOpenStreetMapUrlForPlace } from './placeOpenStreetMap'
@@ -160,6 +161,8 @@ export default function PlaceInspector({
return () => { cancelled = true }
}, [placeIdForDetails])
const { t, locale, language } = useTranslation()
// Currency-less prices mean "the trip's currency"; null in collection mode (EUR fallback below).
const tripCurrency = useTripStore(s => s.trip?.currency)
const toast = useToast()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
const distanceUnit = useSettingsStore(s => s.settings.distance_unit) || 'metric'
@@ -330,7 +333,7 @@ export default function PlaceInspector({
)
})()}
{place.price > 0 && (
<Chip icon={<Euro size={12} />} text={`${place.price} ${place.currency || '€'}`} color="#059669" bg="#ecfdf5" />
<Chip icon={<Banknote size={12} />} text={formatMoney(Number(place.price) || 0, place.currency || tripCurrency || 'EUR', locale)} color="#059669" bg="#ecfdf5" />
)}
</div>