Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(planner): the plan's costs follow the expenses in Costs

Maurice64087512df62
diff --git a/client/src/components/PDF/TripPDF.test.ts b/client/src/components/PDF/TripPDF.test.ts
index 82dd2f1de..5c8a28e4d 100644
--- a/client/src/components/PDF/TripPDF.test.ts
+++ b/client/src/components/PDF/TripPDF.test.ts
@@ -473,6 +473,31 @@ describe('downloadTripPDF', () => {
expect(srcdoc).not.toMatch(/5 ?230/)
})
+ it('FE-COMP-TRIPPDF-016g: with Costs on, the day and cover totals are the expenses, not the place prices (#2551)', async () => {
+ const args = {
+ ...richArgs,
+ trip: { ...richArgs.trip, currency: 'USD' },
+ costsEnabled: true,
+ budgetItems: [
+ { id: 1, trip_id: 10, category: 'activities', name: 'Tickets', total_price: 42, currency: null, place_id: 100 },
+ { id: 2, trip_id: 10, category: 'other', name: 'Insurance', total_price: 8, currency: null },
+ ],
+ }
+ await downloadTripPDF(args)
+ const srcdoc = getIframe()!.srcdoc
+ // The day carries the ticket linked to its place, the cover the whole trip.
+ expect(srcdoc).toContain('$42.00')
+ expect(srcdoc).toContain('$50.00')
+
+ document.getElementById('pdf-preview-overlay')?.remove()
+ // Every expense deleted: nothing is left to add up, whatever price the place carries.
+ await downloadTripPDF({ ...args, budgetItems: [] })
+ const after = getIframe()!.srcdoc
+ expect(after).not.toContain('$42.00')
+ expect(after).not.toContain('$50.00')
+ expect(after).toContain('$15.00') // the place's own price chip stays on its card
+ })
+
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', () => {
diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx
index 8f84bd549..94f1d58a1 100644
--- a/client/src/components/PDF/TripPDF.tsx
+++ b/client/src/components/PDF/TripPDF.tsx
@@ -3,13 +3,16 @@ import { createElement } from 'react'
import { getCategoryIcon } from '../shared/categoryIcons'
import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Sailboat, Bike, CarTaxiFront, Route, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark, Hotel, LogIn, LogOut, KeyRound, BedDouble, Utensils, Users, ParkingSquare, LucideIcon } from 'lucide-react'
import { accommodationsApi, mapsApi, pluginsApi } from '../../api/client'
-import type { Trip, Day, Place, Category, AssignmentsMap, DayNote, DistanceUnit } from '../../types'
+import type { Trip, Day, Place, Category, AssignmentsMap, DayNote, DistanceUnit, BudgetItem } from '../../types'
import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder'
import { hidesOnMiddleDay, getTransportForDay, getMergedItems, getSpanPhase, getDisplayTimeForDay } from '../../utils/dayMerge'
import { safeHexColor } from '../../utils/safeColor'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { formatMoney, formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters'
import { useSettingsStore } from '../../store/settingsStore'
+import { useTripStore } from '../../store/tripStore'
+import { useAddonStore } from '../../store/addonStore'
+import { planCosts } from '../Planner/planCosts'
import { routeTrip, type TripRouteSummary } from '../Map/tripRouteGeometry'
import { buildTripMapSvg } from './tripMapSvg'
import { renderTripMapImage } from './tripMapImage'
@@ -141,16 +144,6 @@ 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' })}`
}
-// 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: Number.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.
// Assignment places are a server-side projection that drops osm_id, so we recover
@@ -206,6 +199,10 @@ interface downloadTripPDFProps {
* the road trip view, and so does the print.
*/
showServiceStops?: boolean
+ /** The trip's expenses, which the cost figures add up with Costs on (#2551). Read from the trip store when left out. */
+ budgetItems?: BudgetItem[]
+ /** Whether the Costs addon is on. Read from the addon store when left out. */
+ costsEnabled?: boolean
}
/**
@@ -226,7 +223,7 @@ function planAssignments(assignments: AssignmentsMap, showServiceStops: boolean)
// `assignments` is normalised here once, to the plan's own list; every read below
// (and fetchPlacePhotos) relies on it being an object.
-export async function downloadTripPDF({ trip, days, places, assignments: stored = {}, categories, dayNotes, reservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true }: downloadTripPDFProps) {
+export async function downloadTripPDF({ trip, days, places, assignments: stored = {}, categories, dayNotes, reservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled }: downloadTripPDFProps) {
const assignments = planAssignments(stored, showServiceStops)
const breaksPerDay = pageBreakPerDay()
const loc = _locale || undefined
@@ -328,12 +325,25 @@ export async function downloadTripPDF({ trip, days, places, assignments: stored
// 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 }))
+ // The same figures the plan shows (#2551): the expenses with Costs on, each once,
+ // else each planned place's own price once. An expense linked to a place finds its
+ // day through every stop, the booked night's included.
+ const withCosts = costsEnabled ?? useAddonStore.getState().isEnabled('budget')
+ const costs = planCosts({
+ days: sorted,
+ assignments: withCosts ? stored : assignments,
+ reservations,
+ budgetItems: budgetItems ?? useTripStore.getState().budgetItems,
+ costsEnabled: withCosts,
+ tripCurrency: tripCur,
+ })
+ const allCostEntries: MoneyEntry[] = costs.total
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)
+ // Day totals render in the trip's currency; foreign amounts are converted via the
+ // pre-fetched rates, or listed per-currency when rates are unavailable (#1561).
+ const dayCost = (dayId: number) => formatMoneySum(costs.byDay.get(dayId) || [], tripCur, loc || 'en', fxRates)
/*
* The span label is the only PDF-specific piece left here. Everything else
@@ -366,7 +376,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: stored
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
const notes = (dayNotes || []).filter(n => n.day_id === day.id).slice()
.sort((a: any, b: any) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
- const cost = dayCost(assignments, day.id, loc, tripCur, fxRates)
+ const cost = dayCost(day.id)
// Assembled exactly the way DayPlanSidebar assembles it, so the page and the
// print cannot disagree about what order a day is in.
diff --git a/client/src/components/Planner/DayPlanSidebar.test.tsx b/client/src/components/Planner/DayPlanSidebar.test.tsx
index 0bc8e95c6..91e895ee2 100644
--- a/client/src/components/Planner/DayPlanSidebar.test.tsx
+++ b/client/src/components/Planner/DayPlanSidebar.test.tsx
@@ -1,5 +1,5 @@
// FE-PLANNER-DAYPLAN-001 to FE-PLANNER-DAYPLAN-232
-import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render'
+import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
import { server } from '../../../tests/helpers/msw/server'
@@ -8,10 +8,11 @@ import { useAuthStore } from '../../store/authStore'
import { useTripStore, type TripStoreState } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
import { usePluginStore } from '../../store/pluginStore'
+import { useAddonStore } from '../../store/addonStore'
import { installTouchDragBridge } from '../../utils/touchDragBridge'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
import {
- buildUser, buildTrip, buildDay, buildPlace, buildCategory, buildAssignment, buildDayNote, buildReservation,
+ buildUser, buildTrip, buildDay, buildPlace, buildCategory, buildAssignment, buildDayNote, buildReservation, buildBudgetItem,
} from '../../../tests/helpers/factories'
import type { Accommodation, Reservation } from '../../types'
import { calculateRouteWithLegs, generateCoMapsUrl, generateGoogleMapsUrl } from '../Map/RouteCalculator'
@@ -875,6 +876,30 @@ describe('DayPlanSidebar', () => {
expect(screen.queryByText(/5\s?230/)).toBeNull()
})
+ it('FE-PLANNER-DAYPLAN-037d: with Costs on, the day and the total follow the expenses, and drop one that is deleted (#2551)', async () => {
+ seedStore(useAddonStore, { addons: [{ id: 'budget', name: 'Costs', type: 'trip', icon: 'wallet', enabled: true }], loaded: true })
+ // The price on the place is not an expense: it stays out of both figures.
+ const place = buildPlace({ id: 1, name: 'Hanging Bridges', price: 999 })
+ const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
+ const ticket = buildBudgetItem({ id: 7, name: 'Tickets', total_price: 60, currency: null, place_id: 1 })
+ const insurance = buildBudgetItem({ id: 8, name: 'Insurance', total_price: 40, currency: null })
+ seedStore(useTripStore, { budgetItems: [ticket, insurance] } as Partial<TripStoreState>)
+ render(<DayPlanSidebar {...makeDefaultProps({
+ days: [day],
+ places: [place],
+ assignments: { '10': [buildAssignment({ id: 1, day_id: 10, order_index: 0, place })] },
+ trip: buildTrip({ id: 1, currency: 'EUR' }),
+ })} />)
+ // The ticket is on the day of its place; the insurance belongs to no day but to the trip.
+ expect(screen.getByText(/^60\s€$/)).toBeInTheDocument()
+ expect(screen.getByText(/^100,00\s€$/)).toBeInTheDocument()
+ expect(screen.queryByText(/999/)).toBeNull()
+
+ act(() => { useTripStore.setState({ budgetItems: [insurance] }) })
+ await waitFor(() => expect(screen.getByText(/^40,00\s€$/)).toBeInTheDocument())
+ expect(screen.queryByText(/^60\s€$/)).toBeNull()
+ })
+
// ── Route tools (Optimize / Google Maps) ────────────────────────────────
it('FE-PLANNER-DAYPLAN-038: optimize button calls onReorder with 3 geo-places', async () => {
@@ -4842,7 +4867,6 @@ describe('DayPlanSidebar remaining branches', () => {
expect(contextMenu().queryByText(/save to/i)).not.toBeInTheDocument()
unmount()
- const { useAddonStore } = await import('../../store/addonStore')
seedStore(useAddonStore, {
addons: [{ id: 'collections', name: 'Collections', type: 'trip', icon: '', enabled: true }],
loaded: true,
diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx
index ebf2e0f62..7f359cf39 100644
--- a/client/src/components/Planner/DayPlanSidebar.tsx
+++ b/client/src/components/Planner/DayPlanSidebar.tsx
@@ -48,7 +48,8 @@ import {
type MergedItem,
} from '../../utils/dayMerge'
import { withinDriveRange } from '@trek/shared/roadtrip'
-import { formatDate, formatTime, dayTotalCost, formatMoneySum, splitReservationDateTime } from '../../utils/formatters'
+import { formatDate, formatTime, formatMoneySum, splitReservationDateTime } from '../../utils/formatters'
+import { planCosts } from './planCosts'
import { useDayNotes } from '../../hooks/useDayNotes'
import { useExchangeRates } from '../../hooks/useExchangeRates'
import { RES_ICONS, getNoteIcon } from './DayPlanSidebar.constants'
@@ -1163,13 +1164,15 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
window.__dragData = null
}
- 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])
+ // The day pills and Total Cost read the expenses in Costs when it is on (#2551).
+ const budgetItems = useTripStore(s => s.budgetItems)
+ const costsEnabled = useAddonStore(s => s.isEnabled('budget'))
+ const { totalCostLabel, dayCostLabels } = useMemo(() => {
+ const costs = planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency })
+ const labels = new Map<number, string | null>()
+ for (const [dayId, entries] of costs.byDay) labels.set(dayId, formatMoneySum(entries, costBase, locale, fxRates, { decimals: 0 }))
+ return { totalCostLabel: formatMoneySum(costs.total, costBase, locale, fxRates), dayCostLabels: labels }
+ }, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])
return {
tripId,
@@ -1290,9 +1293,6 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
dayRefs,
initedTransportIds,
lastAutoScrolledIdRef,
- currency,
- costBase,
- fxRates,
getDragData,
prevDayCount,
toggleDay,
@@ -1316,6 +1316,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
handleOptimize,
handleDropOnDay,
totalCostLabel,
+ dayCostLabels,
expandedRouteDayIds,
setExpandedRouteDayIds,
}
@@ -1498,9 +1499,6 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
dayRefs,
initedTransportIds,
lastAutoScrolledIdRef,
- currency,
- costBase,
- fxRates,
getDragData,
prevDayCount,
toggleDay,
@@ -1524,6 +1522,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
handleOptimize,
handleDropOnDay,
totalCostLabel,
+ dayCostLabels,
expandedRouteDayIds,
setExpandedRouteDayIds,
} = S
@@ -1680,7 +1679,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
}
const isExpanded = expandedDays.has(day.id)
const da = getDayAssignments(day.id)
- const cost = dayTotalCost(day.id, assignments, costBase, currency, locale, fxRates)
+ const cost = dayCostLabels.get(day.id) ?? null
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
diff --git a/client/src/components/Planner/planCosts.test.ts b/client/src/components/Planner/planCosts.test.ts
new file mode 100644
index 000000000..2a09eb023
--- /dev/null
+++ b/client/src/components/Planner/planCosts.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest'
+import { buildAssignment, buildBudgetItem, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories'
+import { planCosts } from './planCosts'
+
+const day1 = buildDay({ id: 1, day_number: 1, date: '2027-01-08' })
+const day2 = buildDay({ id: 2, day_number: 2, date: '2027-01-09' })
+const day3 = buildDay({ id: 3, day_number: 3, date: '2027-01-10' })
+const days = [day1, day2, day3]
+
+const bridges = buildPlace({ id: 50, name: 'Hanging Bridges', price: 100, currency: 'USD' })
+const volcano = buildPlace({ id: 51, name: 'Volcano', price: 40 })
+// The same place on two days, the way a stop visited twice is planned.
+const assignments = {
+ '1': [buildAssignment({ id: 500, day_id: 1, place: bridges })],
+ '2': [buildAssignment({ id: 501, day_id: 2, place: bridges }), buildAssignment({ id: 502, day_id: 2, place: volcano })],
+ '3': [],
+}
+
+const base = { days, assignments, reservations: [], tripCurrency: 'USD' }
+
+describe('planCosts (#2551)', () => {
+ it('reads the expenses, not the prices on the places, while Costs is on', () => {
+ const costs = planCosts({ ...base, budgetItems: [], costsEnabled: true })
+ expect(costs.total).toEqual([])
+ expect(costs.byDay.size).toBe(0)
+ })
+
+ it('drops an expense from the day and the total as soon as it is gone', () => {
+ const ticket = buildBudgetItem({ id: 7, total_price: 60, currency: null, place_id: 50 })
+ const dinner = buildBudgetItem({ id: 8, total_price: 25, currency: null, expense_date: '2027-01-10' })
+ const withBoth = planCosts({ ...base, budgetItems: [ticket, dinner], costsEnabled: true })
+ expect(withBoth.total).toEqual([{ amount: 85, currency: 'USD' }])
+ expect(withBoth.byDay.get(1)).toEqual([{ amount: 60, currency: 'USD' }])
+ expect(withBoth.byDay.get(3)).toEqual([{ amount: 25, currency: 'USD' }])
+
+ const afterDelete = planCosts({ ...base, budgetItems: [dinner], costsEnabled: true })
+ expect(afterDelete.total).toEqual([{ amount: 25, currency: 'USD' }])
+ expect(afterDelete.byDay.has(1)).toBe(false)
+ })
+
+ it('puts an expense on the day its booking starts, a hotel on its first night', () => {
+ const hotel = buildReservation({ id: 90, type: 'hotel', accommodation_start_day_id: 2, accommodation_end_day_id: 3 })
+ const tour = buildReservation({ id: 91, type: 'tour', day_id: null, reservation_time: '2027-01-10T09:00' })
+ const items = [
+ buildBudgetItem({ id: 1, total_price: 450, currency: null, reservation_id: 90, expense_date: '2026-10-01' }),
+ buildBudgetItem({ id: 2, total_price: 80, currency: null, reservation_id: 91 }),
+ ]
+ const costs = planCosts({ ...base, reservations: [hotel, tour], budgetItems: items, costsEnabled: true })
+ expect(costs.byDay.get(2)).toEqual([{ amount: 450, currency: 'USD' }])
+ expect(costs.byDay.get(3)).toEqual([{ amount: 80, currency: 'USD' }])
+ })
+
+ it('counts an expense on no day, but in the total, when nothing ties it to one', () => {
+ const insurance = buildBudgetItem({ total_price: 120, currency: null, expense_date: '2026-11-02' })
+ const costs = planCosts({ ...base, budgetItems: [insurance], costsEnabled: true })
+ expect(costs.byDay.size).toBe(0)
+ expect(costs.total).toEqual([{ amount: 120, currency: 'USD' }])
+ })
+
+ it('counts a foreign expense at the rate frozen when it was entered, as Costs does', () => {
+ // 1 USD bought 500 CRC when this was booked: 50 000 CRC counts as 100 USD.
+ const booked = buildBudgetItem({ total_price: 50000, currency: 'CRC', exchange_rate: 500, place_id: 51 })
+ const unfrozen = buildBudgetItem({ total_price: 30, currency: 'EUR', exchange_rate: 1, place_id: 51 })
+ const costs = planCosts({ ...base, budgetItems: [booked, unfrozen], costsEnabled: true })
+ expect(costs.byDay.get(2)).toEqual([{ amount: 100, currency: 'USD' }, { amount: 30, currency: 'EUR' }])
+ })
+
+ it('nets a refund against the expenses of its day', () => {
+ const items = [
+ buildBudgetItem({ total_price: 200, currency: null, place_id: 50 }),
+ buildBudgetItem({ total_price: -50, currency: null, place_id: 50 }),
+ ]
+ const costs = planCosts({ ...base, budgetItems: items, costsEnabled: true })
+ expect(costs.byDay.get(1)).toEqual([{ amount: 150, currency: 'USD' }])
+ expect(costs.total).toEqual([{ amount: 150, currency: 'USD' }])
+ })
+
+ it('without Costs, counts a place price once, on the first day the place is planned', () => {
+ const costs = planCosts({ ...base, budgetItems: [buildBudgetItem({ total_price: 999 })], costsEnabled: false })
+ expect(costs.byDay.get(1)).toEqual([{ amount: 100, currency: 'USD' }])
+ expect(costs.byDay.get(2)).toEqual([{ amount: 40, currency: 'USD' }])
+ expect(costs.total).toEqual([{ amount: 140, currency: 'USD' }])
+ })
+})
diff --git a/client/src/components/Planner/planCosts.ts b/client/src/components/Planner/planCosts.ts
new file mode 100644
index 000000000..155ebea82
--- /dev/null
+++ b/client/src/components/Planner/planCosts.ts
@@ -0,0 +1,109 @@
+import type { AssignmentsMap, BudgetItem, Day, Reservation } from '../../types'
+import type { MoneyEntry } from '../../utils/formatters'
+import { bookedInTrip } from '../../hooks/useExchangeRates'
+import { daySpan, startKey } from './bookings/bookingsModel'
+
+/** What the plan's cost figures add up: per day, and for the whole trip. */
+export interface PlanCosts {
+ byDay: Map<number, MoneyEntry[]>
+ total: MoneyEntry[]
+}
+
+/**
+ * The money behind the day pills and the Total Cost at the foot of the plan, and
+ * behind the same figures in the PDF (#2551).
+ *
+ * With Costs on, the expenses are the one record of what the trip costs, so the
+ * plan reads them and nothing else: deleting an expense takes it off the plan, and
+ * the plan's total is the Costs total. The plan used to add up the price column of
+ * every stop instead, a figure no form shows since expenses replaced it and that
+ * nothing in Costs ever changed, once per day the stop sat on.
+ *
+ * An expense counts on the day its booking starts, else the first day its place is
+ * planned on, else the day of its date. One that belongs to no day still counts in
+ * the total. A foreign amount booked at a frozen rate counts at that rate, as Costs
+ * counts it.
+ *
+ * With Costs off there are no expenses, and a place's own price (set through the
+ * API) still counts, once, on the first day the place is planned on.
+ */
+export function planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency }: {
+ days: Day[]
+ assignments: AssignmentsMap
+ reservations: Reservation[]
+ budgetItems: BudgetItem[]
+ costsEnabled: boolean
+ tripCurrency: string
+}): PlanCosts {
+ const trip = (tripCurrency || 'EUR').toUpperCase()
+ const firstDayOfPlace = new Map<number, number>()
+ for (const day of days) {
+ for (const a of assignments[String(day.id)] || []) {
+ if (a.place?.id != null && !firstDayOfPlace.has(a.place.id)) firstDayOfPlace.set(a.place.id, day.id)
+ }
+ }
+
+ const byDay = new Map<number, MoneyEntry[]>()
+ const total: MoneyEntry[] = []
+ const add = (dayId: number | null, entry: MoneyEntry) => {
+ total.push(entry)
+ if (dayId == null) return
+ const list = byDay.get(dayId)
+ if (list) list.push(entry)
+ else byDay.set(dayId, [entry])
+ }
+
+ if (!costsEnabled) {
+ const seen = new Set<number>()
+ for (const day of days) {
+ for (const a of assignments[String(day.id)] || []) {
+ const place = a.place
+ if (!place || seen.has(place.id)) continue
+ seen.add(place.id)
+ const amount = Number.parseFloat(String(place.price ?? '')) || 0
+ if (amount !== 0) add(day.id, { amount, currency: (place.currency || trip).toUpperCase() })
+ }
+ }
+ return { byDay: netted(byDay), total: netByCurrency(total) }
+ }
+
+ const dayByDate = (value: string | null | undefined) => {
+ const date = value ? value.slice(0, 10) : ''
+ return date ? days.find(d => d.date === date)?.id ?? null : null
+ }
+ const dayOfExpense = (item: BudgetItem): number | null => {
+ const booking = item.reservation_id != null ? reservations.find(r => r.id === item.reservation_id) : undefined
+ if (booking) {
+ const onDay = daySpan(booking, days).start?.id ?? dayByDate(startKey(booking, days))
+ if (onDay != null) return onDay
+ }
+ if (item.place_id != null && firstDayOfPlace.has(item.place_id)) return firstDayOfPlace.get(item.place_id)!
+ return dayByDate(item.expense_date)
+ }
+
+ for (const item of budgetItems) {
+ const amount = item.total_price || 0
+ if (amount === 0) continue
+ const booked = bookedInTrip(amount, item.currency, item.exchange_rate, trip)
+ const entry = booked != null
+ ? { amount: booked, currency: trip }
+ : { amount, currency: (item.currency || trip).toUpperCase() }
+ add(dayOfExpense(item), entry)
+ }
+ return { byDay: netted(byDay), total: netByCurrency(total) }
+}
+
+/**
+ * One entry per currency, signed amounts summed first, so a refund (a negative
+ * expense) takes its amount back off the figure the way Costs nets it, instead of
+ * being skipped by the formatter that only prints what is above zero.
+ */
+function netByCurrency(entries: MoneyEntry[]): MoneyEntry[] {
+ const sums = new Map<string, number>()
+ for (const e of entries) sums.set(e.currency, (sums.get(e.currency) || 0) + e.amount)
+ return [...sums].map(([currency, amount]) => ({ currency, amount }))
+}
+
+function netted(byDay: Map<number, MoneyEntry[]>): Map<number, MoneyEntry[]> {
+ return new Map([...byDay].map(([dayId, entries]) => [dayId, netByCurrency(entries)]))
+}
diff --git a/client/src/utils/formatters.ts b/client/src/utils/formatters.ts
index 7fc9e1611..a9e8d1d6c 100644
--- a/client/src/utils/formatters.ts
+++ b/client/src/utils/formatters.ts
@@ -1,4 +1,4 @@
-import type { AssignmentsMap, Day } from '../types'
+import type { Day } from '../types'
// Collapses verbose Nominatim display_name strings (e.g. "Place, 1, Road, Neighbourhood,
// City, County, State, Country, Postcode, Country") into "Place, Postcode, Country".
@@ -320,19 +320,3 @@ export function formatMoneySum(
]
return parts.map(cur => formatMoney(groups.get(cur)!, cur, locale, opts)).join(' + ')
}
-
-export function dayTotalCost(
- dayId: number,
- assignments: AssignmentsMap,
- base: string,
- tripCurrency: string,
- locale: string,
- rates?: Record<string, number> | null,
-): string | null {
- const da = assignments[String(dayId)] || []
- const entries = da.map(a => ({
- amount: Number.parseFloat(String(a.place?.price ?? '')) || 0,
- currency: a.place?.currency || tripCurrency,
- }))
- return formatMoneySum(entries, base, locale, rates, { decimals: 0 })
-}
diff --git a/client/tests/unit/utils/formatters.test.ts b/client/tests/unit/utils/formatters.test.ts
index 0530f3b71..6d0006a43 100644
--- a/client/tests/unit/utils/formatters.test.ts
+++ b/client/tests/unit/utils/formatters.test.ts
@@ -1,10 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { formatDate, formatTime, formatClockTime, dayTotalCost, currencyDecimals, parseMeridiemTime } from '../../../src/utils/formatters';
-import type { AssignmentsMap } from '../../../src/types';
-
-// dayTotalCost intentionally exercises edge-case price inputs (string / non-numeric),
-// which are looser than the canonical AssignmentsMap shape — hence the casts below.
-const asMap = (m: unknown): AssignmentsMap => m as AssignmentsMap;
+import { formatDate, formatTime, formatClockTime, currencyDecimals, parseMeridiemTime } from '../../../src/utils/formatters';
describe('currencyDecimals', () => {
it('returns 0 for zero-decimal currencies', () => {
@@ -123,76 +118,3 @@ describe('formatClockTime', () => {
expect(formatClockTime('later', true)).toBe('later');
});
});
-
-describe('dayTotalCost', () => {
- // Intl money strings use non-breaking / narrow no-break spaces; normalize for assertions.
- const norm = (s: string | null) => s?.replace(/[\u00A0\u202F]/g, ' ') ?? null;
-
- it('returns null when there are no assignments', () => {
- expect(dayTotalCost(1, {}, 'EUR', 'EUR', 'en')).toBeNull();
- });
-
- it('returns null when no places have prices', () => {
- const assignments = {
- '1': [
- { id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'P', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: null, image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- ],
- };
- expect(dayTotalCost(1, asMap(assignments), 'EUR', 'EUR', 'en')).toBeNull();
- });
-
- it('sums prices across assignments', () => {
- const assignments = {
- '1': [
- { id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'A', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '20', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- { id: 2, day_id: 1, order_index: 1, notes: null, place: { id: 2, trip_id: 1, name: 'B', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '30', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- ],
- };
- expect(norm(dayTotalCost(1, asMap(assignments), 'EUR', 'EUR', 'en'))).toBe('50 €');
- });
-
- it('ignores non-numeric price strings', () => {
- const assignments = {
- '1': [
- { id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'A', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: 'free', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- ],
- };
- expect(dayTotalCost(1, asMap(assignments), 'EUR', 'EUR', 'en')).toBeNull();
- });
-
- it('uses the dayId key to look up assignments', () => {
- const assignments = {
- '2': [
- { id: 3, day_id: 2, order_index: 0, notes: null, place: { id: 3, trip_id: 1, name: 'C', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '10', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- ],
- };
- expect(dayTotalCost(1, asMap(assignments), 'USD', 'USD', 'en')).toBeNull();
- expect(dayTotalCost(2, asMap(assignments), 'USD', 'USD', 'en')).toBe('$10');
- });
-
- it('resolves a currency-less place to the trip currency, converting into the base (#1561)', () => {
- const assignments = {
- '1': [
- { id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'A', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '100', currency: null, image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- ],
- };
- // base USD, trip NOK: the implicit-NOK price must convert (rates[NOK]=10 per USD)…
- expect(dayTotalCost(1, asMap(assignments), 'USD', 'NOK', 'en', { NOK: 10 })).toBe('≈ $10');
- // …and without rates it must show as NOK, never as a raw number labeled USD.
- expect(norm(dayTotalCost(1, asMap(assignments), 'USD', 'NOK', 'en'))).toMatch(/100\s?kr|kr\s?100/);
- });
-
- it('mislabels nothing when a foreign-currency price has no rate (#1561)', () => {
- const assignments = {
- '1': [
- { id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'Hotel', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: 2730.27, currency: 'USD', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- { id: 2, day_id: 1, order_index: 1, notes: null, place: { id: 2, trip_id: 1, name: 'Museum', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: 2500, currency: 'NOK', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
- ],
- };
- const out = norm(dayTotalCost(1, asMap(assignments), 'NOK', 'NOK', 'en'));
- expect(out).toContain(' + ');
- expect(out).toMatch(/2 500\s?kr|kr\s?2 500/);
- expect(out).toContain('$2,730');
- expect(out).not.toContain('≈');
- });
-});
diff --git a/wiki/Day-Plans-and-Notes.md b/wiki/Day-Plans-and-Notes.md
index 49c8562d5..1d83f2548 100644
--- a/wiki/Day-Plans-and-Notes.md
+++ b/wiki/Day-Plans-and-Notes.md
@@ -19,7 +19,7 @@ From left to right, the head band of a day shows:
- **Pills** for what the day holds:
- the stay, with a hotel icon: green on the check-in day, red on the check-out day, grey for the nights in between. Rest the pointer on it for *Check-in: Hotel Adler* or *Check-out: Hotel Adler*, and click it to open the place. See [Accommodations](Accommodations).
- a rental car that runs across the day, with a car icon. Click it to open the booking.
- - the day's cost: the prices of the day's places, added up.
+ - the day's cost: with the [Costs](Budget-Tracking) addon on, the expenses of the day, added up. An expense counts on the day its booking starts, else on the first day its place is planned, else on its date. With Costs off, the prices of the day's places.
- a label a plugin gives the day, for example the leg of the trip it belongs to.
- **+** (*Add to day*): the menu of everything a day can be given, see below. Shown to members who can edit days.
- **The chevron** expands or collapses the day.
@@ -142,7 +142,7 @@ The head band of the days column holds, from left to right:
With the [Road trip](Road-Trip) addon on, the **Days** / **Road trip** switch sits above this band.
-At the foot of the column, **Total Cost** adds up the prices of every planned place, once at least one has a price.
+At the foot of the column, **Total Cost** adds up every expense of the trip with Costs on, the same figure as *Total trip spend* in Costs, so deleting an expense lowers it. With Costs off it adds up the prices of the planned places, each place once.
### The route bar