diff --git a/client/src/components/Trips/TripFormModal.test.tsx b/client/src/components/Trips/TripFormModal.test.tsx index a744e5a3f..f5955dbf8 100644 --- a/client/src/components/Trips/TripFormModal.test.tsx +++ b/client/src/components/Trips/TripFormModal.test.tsx @@ -347,4 +347,38 @@ describe('TripFormModal', () => { expect(updateBody).toMatchObject({ cover_image: 'https://images.example.com/regular.jpg' }); }); }); + + // The trip currency is the base every expense and settlement is netted against, and + // until #1543 the only way to set it was the legacy Budget addon panel. + it('FE-COMP-TRIPFORM-032: pre-fills the currency of the trip being edited', () => { + render(); + expect(screen.getByText(/^RUB/)).toBeInTheDocument(); + }); + + it('FE-COMP-TRIPFORM-033: defaults a new trip to EUR and sends the currency on save', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue({ trip: buildTrip({ id: 99 }) }); + render(); + + await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Moscow 2026'); + const submitBtn = screen.getAllByText('Create New Trip').find(el => el.closest('button'))!; + await user.click(submitBtn.closest('button')!); + + await waitFor(() => expect(onSave).toHaveBeenCalled()); + expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ currency: 'EUR' })); + }); + + it('FE-COMP-TRIPFORM-034: picking a currency sends the new one on save', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue({}); + render(); + + await user.click(screen.getByText(/^EUR/)); + await user.click(await screen.findByText(/^USD/)); + + await user.click(screen.getByText('Update').closest('button')!); + + await waitFor(() => expect(onSave).toHaveBeenCalled()); + expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ currency: 'USD' })); + }); }); diff --git a/client/src/components/Trips/TripFormModal.tsx b/client/src/components/Trips/TripFormModal.tsx index 4a3c3b679..3862267e1 100644 --- a/client/src/components/Trips/TripFormModal.tsx +++ b/client/src/components/Trips/TripFormModal.tsx @@ -12,6 +12,7 @@ import { normalizeImageFile } from '../../utils/convertHeic' import { getApiErrorMessage, type Trip } from '../../types' import type { TripCreateRequest } from '@trek/shared' import { NumericInput } from '../shared/NumericInput' +import { currenciesWith, SYMBOLS } from '../Budget/BudgetPanel.constants' interface TripFormModalProps { isOpen: boolean @@ -50,6 +51,7 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp description: '', start_date: '', end_date: '', + currency: 'EUR', reminder_days: 0 as number, day_count: 7 as number | '', }) @@ -77,6 +79,7 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp description: trip.description || '', start_date: trip.start_date || '', end_date: trip.end_date || '', + currency: trip.currency || 'EUR', reminder_days: rd, day_count: trip.day_count || 7, }) @@ -84,7 +87,7 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp setCoverPreview(trip.cover_image || null) setCoverSearchQuery('') } else { - setFormData({ title: '', description: '', start_date: '', end_date: '', reminder_days: tripRemindersEnabled ? 3 : 0, day_count: 7 }) + setFormData({ title: '', description: '', start_date: '', end_date: '', currency: 'EUR', reminder_days: tripRemindersEnabled ? 3 : 0, day_count: 7 }) setCustomReminder(false) setCoverPreview(null) setCoverSearchQuery('') @@ -134,6 +137,7 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp description: formData.description.trim() || null, start_date: formData.start_date || null, end_date: formData.end_date || null, + currency: formData.currency, reminder_days: formData.reminder_days, ...(!formData.start_date && !formData.end_date ? { day_count: Number(formData.day_count) } : {}), }) @@ -448,6 +452,17 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp )} +
+ + canEditTrip && update('currency', v)} + disabled={!canEditTrip} + options={currenciesWith(formData.currency).map(c => ({ value: c, label: `${c} (${SYMBOLS[c] || c})` }))} + searchable + /> +
+ {/* Reminder — only visible to owner (or when creating) */} {(!isEditing || trip?.user_id === currentUser?.id || currentUser?.role === 'admin') && (
diff --git a/server/src/mcp/tools/trips.ts b/server/src/mcp/tools/trips.ts index 3ede43033..4db8905f6 100644 --- a/server/src/mcp/tools/trips.ts +++ b/server/src/mcp/tools/trips.ts @@ -18,6 +18,7 @@ import { countMessages, listPolls } from '../../services/collabService'; import { listItems as listTodoItems, } from '../../services/todoService'; +import { rebaseTripCurrency } from '../../services/budgetService'; import { safeBroadcast, MAX_MCP_TRIP_DAYS, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, @@ -97,6 +98,8 @@ export function registerTripTools(server: McpServer, userId: number, scopes: str if (isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== end_date) return { content: [{ type: 'text' as const, text: 'end_date is not a valid calendar date.' }], isError: true }; } + // Re-anchor the budget before the trip row moves off the old currency (#1543). + await rebaseTripCurrency(tripId, currency); const { updatedTrip } = updateTrip(tripId, userId, { title, description, start_date, end_date, currency, is_archived, cover_image }, 'user'); safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip }); return ok({ trip: updatedTrip }); diff --git a/server/src/nest/trips/trips.controller.ts b/server/src/nest/trips/trips.controller.ts index f4d057bb0..6eb7b1bb0 100644 --- a/server/src/nest/trips/trips.controller.ts +++ b/server/src/nest/trips/trips.controller.ts @@ -153,7 +153,7 @@ export class TripsController { ? (this.trips.getRaw(id) as { cover_image: string | null } | undefined)?.cover_image : undefined; try { - const result = this.trips.update(id, user.id, body, user.role); + const result = await this.trips.update(id, user.id, body, user.role); if (body.cover_image !== undefined && body.cover_image !== oldCover) { this.trips.deleteOldCover(oldCover); } diff --git a/server/src/nest/trips/trips.service.ts b/server/src/nest/trips/trips.service.ts index 9ecd26877..618ef0e25 100644 --- a/server/src/nest/trips/trips.service.ts +++ b/server/src/nest/trips/trips.service.ts @@ -8,7 +8,7 @@ import { listDays, listAccommodations } from '../../services/dayService'; import { listPlaces } from '../../services/placeService'; import { listItems as listPackingItems } from '../../services/packingService'; import { listItems as listTodoItems } from '../../services/todoService'; -import { listBudgetItems } from '../../services/budgetService'; +import { listBudgetItems, rebaseTripCurrency } from '../../services/budgetService'; import { listReservations } from '../../services/reservationService'; import { listFiles } from '../../services/fileService'; import { searchUnsplashPhotos, getUnsplashKey } from '../../services/unsplashService'; @@ -58,7 +58,11 @@ export class TripsService { return tripSvc.getTripOwner(tripId); } - update(tripId: string, userId: number, body: Parameters[2], role: string) { + async update(tripId: string, userId: number, body: Parameters[2], role: string) { + // Re-anchor the budget while the outgoing currency is still on the trip row, + // otherwise the frozen FX rates and the currency-less expenses that inherit the + // trip's base are left pointing at a currency that no longer exists (#1543). + await rebaseTripCurrency(tripId, body.currency); return tripSvc.updateTrip(tripId, userId, body, role); } diff --git a/server/src/services/budgetService.ts b/server/src/services/budgetService.ts index 882147a0c..8d58bd29f 100644 --- a/server/src/services/budgetService.ts +++ b/server/src/services/budgetService.ts @@ -141,6 +141,61 @@ export async function freezeForeignRate( if (r && r > 0) data.exchange_rate = r; } +/** + * Re-anchor a trip's budget when its base currency changes (#1543). + * + * Every frozen `exchange_rate` is "units of the row's currency per 1 *trip* + * currency", and `currency = NULL` means "the trip's own currency" — both are + * relative to the trip currency, so swapping it out from under them silently + * corrupts the settlement: NULL rows redenominate (9 000 RUB becomes 9 000 EUR) + * and frozen rates keep pointing at the old base, which is exactly the mismatch + * that inflated #1543 by ~27x. + * + * So, before the switch: pin the implicit rows to the outgoing currency (their + * amounts really were in it) and re-freeze every row against the incoming one. + * No stored amount is rewritten — each expense keeps the figure the user typed, + * in the currency they typed it in, and its real-world value is preserved. + * + * Must run *before* the (synchronous) trip update, while the old currency is + * still in `trips`, and is a no-op when the currency isn't actually changing. + */ +export async function rebaseTripCurrency( + tripId: string | number, + newCurrency: string | null | undefined, +): Promise { + const next = (newCurrency || '').toUpperCase(); + if (!next) return; + const trip = db.prepare('SELECT currency FROM trips WHERE id = ?') + .get(tripId) as { currency?: string } | undefined; + if (!trip) return; + const prev = (trip.currency || 'EUR').toUpperCase(); + if (prev === next) return; + + const rates = await getRates(next); + // A row already denominated in the new base needs no conversion (rate 1). When no + // live rate is available we also store 1 rather than a stale one: rate 1 means "not + // frozen", so the settlement falls back to live rates instead of trusting a figure + // anchored to a currency this trip no longer uses. + const rateFor = (cur: string): number => { + if (cur === next) return 1; + const r = rates?.[cur]; + return r && r > 0 ? r : 1; + }; + + const rebase = (table: 'budget_items' | 'budget_settlements') => { + db.prepare(`UPDATE ${table} SET currency = ? WHERE trip_id = ? AND (currency IS NULL OR currency = '')`) + .run(prev, tripId); + const rows = db.prepare(`SELECT DISTINCT currency AS cur FROM ${table} WHERE trip_id = ? AND currency IS NOT NULL`) + .all(tripId) as { cur: string }[]; + for (const { cur } of rows) { + db.prepare(`UPDATE ${table} SET exchange_rate = ? WHERE trip_id = ? AND currency = ?`) + .run(rateFor(cur.toUpperCase()), tripId, cur); + } + }; + + db.transaction(() => { rebase('budget_items'); rebase('budget_settlements'); })(); +} + export function createBudgetItem( tripId: string | number, data: { diff --git a/server/tests/unit/nest/trips.service.test.ts b/server/tests/unit/nest/trips.service.test.ts index c7b4f95d8..f8ba72089 100644 --- a/server/tests/unit/nest/trips.service.test.ts +++ b/server/tests/unit/nest/trips.service.test.ts @@ -27,24 +27,30 @@ vi.mock('../../../src/services/dayService', () => ({ listDays: () => ({ days: [1 vi.mock('../../../src/services/placeService', () => ({ listPlaces: () => [] })); vi.mock('../../../src/services/packingService', () => ({ listItems: () => [] })); vi.mock('../../../src/services/todoService', () => ({ listItems: () => [] })); -vi.mock('../../../src/services/budgetService', () => ({ listBudgetItems: () => [] })); +vi.mock('../../../src/services/budgetService', () => ({ + listBudgetItems: () => [], + rebaseTripCurrency: vi.fn(async () => {}), +})); vi.mock('../../../src/services/reservationService', () => ({ listReservations: () => [] })); vi.mock('../../../src/services/fileService', () => ({ listFiles: () => [] })); import { TripsService } from '../../../src/nest/trips/trips.service'; +import { rebaseTripCurrency } from '../../../src/services/budgetService'; function svc() { return new TripsService(); } beforeEach(() => vi.clearAllMocks()); describe('TripsService (wrapper delegation + bundle/copy/notify helpers)', () => { - it('delegates the simple wrappers to tripService', () => { + it('delegates the simple wrappers to tripService', async () => { const s = svc(); s.list(1, 0); expect(tripSvc.listTrips).toHaveBeenCalledWith(1, 0); s.create(1, { title: 'T' } as never); expect(tripSvc.createTrip).toHaveBeenCalledWith(1, { title: 'T' }); s.get('9', 1); expect(tripSvc.getTrip).toHaveBeenCalledWith('9', 1); s.getRaw('9'); expect(tripSvc.getTripRaw).toHaveBeenCalledWith('9'); s.getOwner('9'); expect(tripSvc.getTripOwner).toHaveBeenCalledWith('9'); - s.update('9', 1, {} as never, 'user'); expect(tripSvc.updateTrip).toHaveBeenCalledWith('9', 1, {}, 'user'); + // update() first re-anchors the budget to any incoming currency, so it is async now. + await s.update('9', 1, {} as never, 'user'); expect(tripSvc.updateTrip).toHaveBeenCalledWith('9', 1, {}, 'user'); + expect(rebaseTripCurrency).toHaveBeenCalledWith('9', undefined); s.remove('9', 1, 'user'); expect(tripSvc.deleteTrip).toHaveBeenCalledWith('9', 1, 'user'); s.deleteOldCover('/old.jpg'); expect(tripSvc.deleteOldCover).toHaveBeenCalledWith('/old.jpg'); s.updateCoverImage('9', '/n.jpg'); expect(tripSvc.updateCoverImage).toHaveBeenCalledWith('9', '/n.jpg'); @@ -59,6 +65,18 @@ describe('TripsService (wrapper delegation + bundle/copy/notify helpers)', () => s.exportICS('9'); expect(tripSvc.exportICS).toHaveBeenCalledWith('9'); }); + it('re-anchors the budget before the trip row leaves its old currency (#1543)', async () => { + const order: string[] = []; + (rebaseTripCurrency as ReturnType).mockImplementationOnce(async () => { order.push('rebase'); }); + (tripSvc.updateTrip as ReturnType).mockImplementationOnce(() => { order.push('update'); return {} as never; }); + + await svc().update('9', 1, { currency: 'RUB' } as never, 'user'); + + // The rebase reads the outgoing currency off the trip row, so it has to run first. + expect(rebaseTripCurrency).toHaveBeenCalledWith('9', 'RUB'); + expect(order).toEqual(['rebase', 'update']); + }); + it('canAccessTrip delegates to the db helper', () => { canAccessTrip.mockReturnValueOnce({ user_id: 7 }); expect(svc().canAccessTrip('9', 7)).toEqual({ user_id: 7 }); diff --git a/server/tests/unit/services/budgetServiceDb.test.ts b/server/tests/unit/services/budgetServiceDb.test.ts index f74b66aa9..7854315b8 100644 --- a/server/tests/unit/services/budgetServiceDb.test.ts +++ b/server/tests/unit/services/budgetServiceDb.test.ts @@ -28,11 +28,20 @@ vi.mock('../../../src/config', () => ({ updateJwtSecret: () => {}, })); +// Frozen snapshot of the rates in play in #1543 (rates[X] = units of X per 1 base). +const RATES: Record> = { + RUB: { RUB: 1, USD: 0.013042, EUR: 0.011412 }, + EUR: { EUR: 1, USD: 1.1429, RUB: 87.63 }, +}; +vi.mock('../../../src/services/exchangeRateService', () => ({ + getRates: vi.fn(async (base: string) => RATES[base.toUpperCase()] ?? null), +})); + import { createTables } from '../../../src/db/schema'; import { runMigrations } from '../../../src/db/migrations'; import { resetTestDb } from '../../helpers/test-db'; import { createUser, createTrip } from '../../helpers/factories'; -import { createBudgetItem, updateMembers, toggleMemberPaid, calculateSettlement } from '../../../src/services/budgetService'; +import { createBudgetItem, updateMembers, toggleMemberPaid, calculateSettlement, rebaseTripCurrency } from '../../../src/services/budgetService'; beforeAll(() => { createTables(testDb); @@ -111,3 +120,118 @@ describe('calculateSettlement custom splits', () => { ]); }); }); + +/** The exact trip from #1543: RUB base, three members, one expense booked in USD. */ +function seedIssue1543Trip(tripCurrency: string) { + const { user: me } = createUser(testDb, { username: 'me' }); + const { user: danil } = createUser(testDb, { username: 'danil' }); + const { user: serega } = createUser(testDb, { username: 'serega' }); + const trip = createTrip(testDb, me.id, { title: 'Trip' }); + testDb.prepare('UPDATE trips SET currency = ? WHERE id = ?').run(tripCurrency, trip.id); + const members = [{ user_id: me.id }, { user_id: danil.id }, { user_id: serega.id }]; + + // 9 000 ₽ nobody has paid yet, 9 000 ₽ paid by me, and $100 paid by me. The USD row + // carries the rate frozen at entry time: units of USD per 1 RUB. + createBudgetItem(trip.id, { name: 'Проезд обратно', total_price: 9000, currency: 'RUB', members }); + createBudgetItem(trip.id, { name: 'Проезд туда', currency: 'RUB', payers: [{ user_id: me.id, amount: 9000 }], members }); + createBudgetItem(trip.id, { + name: 'test', currency: 'USD', exchange_rate: 0.013042, + payers: [{ user_id: me.id, amount: 100 }], members, + }); + return { trip, me, danil, serega }; +} + +describe('calculateSettlement with a foreign-currency expense (#1543)', () => { + it('BUDGET-SVC-DB-004: nets in the trip currency instead of inflating the foreign share ~27x', () => { + const { trip, me, danil, serega } = seedIssue1543Trip('RUB'); + + const result = calculateSettlement(trip.id, { base: 'RUB', tripCurrency: 'RUB', rates: RATES.RUB }); + const balanceOf = (id: number) => result.balances.find(b => b.user_id === id)!.balance; + + // Total spend is 9 000 + 9 000 + $100 (≈7 668 ₽), so each of the three owes a third + // of it and I am owed back everything I fronted beyond my own share. The bug divided + // the RUB shares by the USD rate and reported +451 092 / −230 080 / −230 012 instead. + // Tolerance is a rouble: the cent-rotation in splitEqualShares moves the odd cent of + // the $100 between members, which the USD rate magnifies ~77x. + const totalSpend = 18000 + 100 / RATES.RUB.USD; + const share = totalSpend / 3; + expect(balanceOf(me.id)).toBeCloseTo(9000 + 100 / RATES.RUB.USD - share, -1); + expect(balanceOf(danil.id)).toBeCloseTo(-share, -1); + expect(balanceOf(serega.id)).toBeCloseTo(-share, -1); + // The 9 000 ₽ expense nobody paid is the only imbalance in the trip. + expect(result.balances.reduce((a, b) => a + b.balance, 0)).toBeCloseTo(-9000, 1); + }); + + it('BUDGET-SVC-DB-005: reports the same balances when the display currency differs from the trip currency', () => { + const { trip, danil } = seedIssue1543Trip('RUB'); + + // Same trip, viewed in EUR: every balance is the RUB one converted once, at the end. + const inEur = calculateSettlement(trip.id, { base: 'EUR', tripCurrency: 'RUB', rates: RATES.EUR }); + const danilEur = inEur.balances.find(b => b.user_id === danil.id)!.balance; + + const shareRub = (18000 + 100 / RATES.RUB.USD) / 3; + expect(danilEur).toBeCloseTo(-shareRub / RATES.EUR.RUB, 0); + }); +}); + +describe('rebaseTripCurrency', () => { + const itemRow = (id: number) => + testDb.prepare('SELECT currency, exchange_rate FROM budget_items WHERE id = ?') + .get(id) as { currency: string | null; exchange_rate: number }; + + it('BUDGET-SVC-DB-006: pins currency-less expenses to the outgoing currency and re-freezes the rest', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { title: 'Trip' }); + testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id); + const members = [{ user_id: user.id }]; + + // An expense that inherits the trip's base (currency NULL), one booked in USD, and + // one already in the incoming currency. + const implicit = createBudgetItem(trip.id, { name: 'Implicit', total_price: 100, members }) as { id: number }; + const usd = createBudgetItem(trip.id, { name: 'USD', total_price: 100, currency: 'USD', exchange_rate: 1.1429, members }) as { id: number }; + const rub = createBudgetItem(trip.id, { name: 'RUB', total_price: 9000, currency: 'RUB', exchange_rate: 87.63, members }) as { id: number }; + + await rebaseTripCurrency(trip.id, 'RUB'); + + // The implicit row really held euros, so it is stamped EUR rather than silently + // becoming 100 ₽, and every rate is re-anchored to the new base. + expect(itemRow(implicit.id)).toEqual({ currency: 'EUR', exchange_rate: RATES.RUB.EUR }); + expect(itemRow(usd.id)).toEqual({ currency: 'USD', exchange_rate: RATES.RUB.USD }); + // Already in the trip's new currency → no conversion left to freeze. + expect(itemRow(rub.id)).toEqual({ currency: 'RUB', exchange_rate: 1 }); + }); + + it('BUDGET-SVC-DB-007: keeps every balance at the same real-world value across the switch', async () => { + const { user: alice } = createUser(testDb, { username: 'alice' }); + const { user: bob } = createUser(testDb, { username: 'bob' }); + const trip = createTrip(testDb, alice.id, { title: 'Trip' }); + testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id); + const members = [{ user_id: alice.id }, { user_id: bob.id }]; + + createBudgetItem(trip.id, { name: 'Hotel', payers: [{ user_id: alice.id, amount: 100 }], members }); + createBudgetItem(trip.id, { name: 'Dinner', currency: 'USD', exchange_rate: 1.1429, payers: [{ user_id: bob.id, amount: 60 }], members }); + + const before = calculateSettlement(trip.id, { base: 'EUR', tripCurrency: 'EUR', rates: RATES.EUR }); + + await rebaseTripCurrency(trip.id, 'RUB'); + testDb.prepare("UPDATE trips SET currency = 'RUB' WHERE id = ?").run(trip.id); + + const after = calculateSettlement(trip.id, { base: 'RUB', tripCurrency: 'RUB', rates: RATES.RUB }); + + for (const b of before.balances) { + const rub = after.balances.find(x => x.user_id === b.user_id)!.balance; + expect(rub).toBeCloseTo(b.balance * 87.63, 0); // same money, different unit + } + }); + + it('BUDGET-SVC-DB-008: is a no-op when the currency is unchanged', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { title: 'Trip' }); + testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id); + const item = createBudgetItem(trip.id, { name: 'Implicit', total_price: 100, members: [{ user_id: user.id }] }) as { id: number }; + + await rebaseTripCurrency(trip.id, 'EUR'); + + expect(itemRow(item.id)).toEqual({ currency: null, exchange_rate: 1 }); + }); +});