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.

feat(costs): start a new expense in the trip currency (#2807)

Maurice2934319722bf
diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json
index 3cf18892d..2dba8df97 100644
--- a/client/scripts/feature-pairs.json
+++ b/client/scripts/feature-pairs.json
@@ -279,7 +279,7 @@
"feature": "Costs/budget ledger: costsModel",
"hooks": ["src/components/Budget/costsModel.ts"],
"desktop": ["src/components/Budget/CostsPanel.tsx"],
- "mobile": ["src/mobile/screens/trip/sheets/MCostSheet.tsx", "src/mobile/screens/trip/tabs/MCostsTab.tsx"]
+ "mobile": ["src/mobile/screens/trip/tabs/MCostsTab.tsx"]
},
{
"feature": "Costs/budget ledger: useCostsLedger, useExpenseLinks",
diff --git a/client/src/components/Budget/CostsPanel.helpers.test.ts b/client/src/components/Budget/CostsPanel.helpers.test.ts
index 97ed55c70..b00226e89 100644
--- a/client/src/components/Budget/CostsPanel.helpers.test.ts
+++ b/client/src/components/Budget/CostsPanel.helpers.test.ts
@@ -347,13 +347,13 @@ describe('finalBudgetSources', () => {
})
describe('newExpenseSeed', () => {
- it('starts a plain new expense on the base currency, today, with nothing to attach', () => {
+ it('starts a plain new expense on the fallback currency, today, with nothing to attach', () => {
expect(newExpenseSeed(undefined, 'eur', [1, 2], '2026-09-24')).toEqual({
currency: 'EUR', day: '2026-09-24', total: '', ticketItems: [], receiptFiles: [],
})
})
- it('reads a booking price in the base currency, padded to its decimals', () => {
+ it('reads a booking price in the fallback currency, padded to its decimals', () => {
expect(newExpenseSeed({ amount: 4.9 }, 'EUR', [], '2026-09-24').total).toBe('4.90')
})
diff --git a/client/src/components/Budget/CostsPanel.helpers.ts b/client/src/components/Budget/CostsPanel.helpers.ts
index c24d01bcb..90c240a43 100644
--- a/client/src/components/Budget/CostsPanel.helpers.ts
+++ b/client/src/components/Budget/CostsPanel.helpers.ts
@@ -278,13 +278,14 @@ export function calculateTicketShares(items: TicketItem[]): { shares: Record<num
* scanned receipt, which also brings its currency, day, lines and photo. Both
* editors (the desktop modal and the phone sheet) seed from this one place.
*
- * A prefill without a currency is in `base`, which is also what the currency
- * field starts on. Receipt lines seed the Ticket split, shared by everyone like
- * a line added by hand, while the split itself stays Equally until the person
- * switches.
+ * A prefill without a currency is in `fallbackCurrency`, which is also what the
+ * currency field starts on: the editors pass the trip's own currency, the one
+ * most expenses on the road are paid in (#2807). Receipt lines seed the Ticket
+ * split, shared by everyone like a line added by hand, while the split itself
+ * stays Equally until the person switches.
*/
-export function newExpenseSeed(prefill: ExpensePrefill | undefined, base: string, peopleIds: number[], today: string) {
- const currency = (prefill?.currency || base).toUpperCase()
+export function newExpenseSeed(prefill: ExpensePrefill | undefined, fallbackCurrency: string, peopleIds: number[], today: string) {
+ const currency = (prefill?.currency || fallbackCurrency).toUpperCase()
return {
currency,
day: prefill?.date || today,
diff --git a/client/src/components/Budget/CostsPanel.tsx b/client/src/components/Budget/CostsPanel.tsx
index 5eb46e554..c6c968d43 100644
--- a/client/src/components/Budget/CostsPanel.tsx
+++ b/client/src/components/Budget/CostsPanel.tsx
@@ -1132,7 +1132,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
handleRemoveReceipt, handleToggleItemParticipant, handleUpdateItemName, handleUpdateItemPrice, isTicketMode,
multiPayer, name, nameOf, note, onPayerAmountChange, onTotalChange, participants, payerAmounts, payerId, payerIds,
payersOk, pendingReceiptFiles, placeholderShares, previewReceipts: modalPreviewReceipts, receipts, save, saving,
- setCat, setCurrency, setCustomAmounts, setDay, setName, setNote, setPayerId,
+ currencyChoices, setCat, setCurrency, setCustomAmounts, setDay, setName, setNote, setPayerId,
setPreviewReceipts: setModalPreviewReceipts, setSplitMode, splitMode, splitShortfall, splitSum, sym, ticketInfo,
ticketItems, toggleParticipant, togglePayer, total, totalNum, tripCur, uploadingReceipt, valid,
} = useExpenseForm({ tripId, base, people, me, editing, prefill, onSaved })
@@ -1515,7 +1515,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
</EditorField>
<EditorField label={t('costs.currency')}>
<CustomSelect value={currency} onChange={v => setCurrency(String(v))} searchable
- options={currencyOptions(currency)}
+ options={currencyChoices}
style={{ width: '100%' }} />
</EditorField>
<EditorField label={t('costs.day')}>
diff --git a/client/src/components/Budget/costsModel.test.ts b/client/src/components/Budget/costsModel.test.ts
index d087b73ce..8fa2d6eb2 100644
--- a/client/src/components/Budget/costsModel.test.ts
+++ b/client/src/components/Budget/costsModel.test.ts
@@ -16,7 +16,7 @@ import {
type CostsSettlement,
} from './costsModel';
-// FE-BUDGET-COSTSMODEL-001 to FE-BUDGET-COSTSMODEL-010
+// FE-BUDGET-COSTSMODEL-001 to FE-BUDGET-COSTSMODEL-011
// The pieces both ledgers share since the desktop panel runs on this model too;
// the rest of the model is pinned in tests/unit/mobile/trip/costsModel.test.ts.
@@ -135,4 +135,13 @@ describe('costsModel: the currency picker options', () => {
expect(opts[opts.length - 1]).toEqual({ value: 'BGN', label: 'BGN' });
expect(currencyOptions(null).some((o) => o.value === 'BGN')).toBe(false);
});
+
+ it('FE-BUDGET-COSTSMODEL-011: pinned currencies lead in the order given, each listed once (#2807)', () => {
+ const values = currencyOptions('EUR', ['jpy', 'EUR', 'JPY']).map((o) => o.value);
+ expect(values.slice(0, 2)).toEqual(['JPY', 'EUR']);
+ expect(values.filter((v) => v === 'JPY')).toHaveLength(1);
+ expect(values).toHaveLength(currencyOptions('EUR').length);
+ // A pin the picker cannot offer is left out rather than invented.
+ expect(currencyOptions(null, ['ZZZ']).some((o) => o.value === 'ZZZ')).toBe(false);
+ });
});
diff --git a/client/src/components/Budget/costsModel.ts b/client/src/components/Budget/costsModel.ts
index cf0126b96..e732214a1 100644
--- a/client/src/components/Budget/costsModel.ts
+++ b/client/src/components/Budget/costsModel.ts
@@ -437,8 +437,16 @@ export function buildCostsCsv(items: BudgetItem[], opts: CsvBuildOptions): { fil
/**
* The currency picker of every Costs form (expense and payment, desktop and
* phone): the supported currencies plus the one already chosen, each labelled
- * with its code and, when it has one, its symbol.
+ * with its code and, when it has one, its symbol. `pinned` ones lead the list
+ * in the order given, so the few a trip really uses are not buried in the
+ * alphabet (#2807).
*/
-export function currencyOptions(current?: string | null): { value: string; label: string }[] {
- return currenciesWith(current).map((c) => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }));
+export function currencyOptions(
+ current?: string | null,
+ pinned: readonly string[] = []
+): { value: string; label: string }[] {
+ const all = currenciesWith(current);
+ const lead = [...new Set(pinned.map((c) => c.toUpperCase()))].filter((c) => all.includes(c));
+ const ordered = [...lead, ...all.filter((c) => !lead.includes(c))];
+ return ordered.map((c) => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }));
}
diff --git a/client/src/components/Budget/useExpenseForm.test.ts b/client/src/components/Budget/useExpenseForm.test.ts
index 2ab992f93..6a962e668 100644
--- a/client/src/components/Budget/useExpenseForm.test.ts
+++ b/client/src/components/Budget/useExpenseForm.test.ts
@@ -21,7 +21,7 @@ vi.mock('./receiptUploads', () => ({
),
}));
-// FE-BUDGET-EXPFORM-001 to FE-BUDGET-EXPFORM-023
+// FE-BUDGET-EXPFORM-001 to FE-BUDGET-EXPFORM-025
const PEOPLE: TripMember[] = [
{ id: 1, username: 'alice', avatar_url: null },
@@ -104,7 +104,7 @@ afterEach(() => {
});
describe('useExpenseForm: where it starts', () => {
- it('FE-BUDGET-EXPFORM-001: a new expense is food, in the display currency, today, split equally by everyone, paid by me', () => {
+ it('FE-BUDGET-EXPFORM-001: a new expense is food, in the trip currency, today, split equally by everyone, paid by me', () => {
const { result } = setup();
const f = result.current;
expect(f.name).toBe('');
@@ -150,6 +150,19 @@ describe('useExpenseForm: where it starts', () => {
expect(f.pendingReceiptFiles).toEqual([photo]);
});
+ it('FE-BUDGET-EXPFORM-025: a new expense starts in the trip currency, which leads the picker with the display one (#2807)', () => {
+ localStorage.setItem('trek_fx_JPY', JSON.stringify({ rates: { JPY: 1, EUR: 0.006 }, ts: Date.now() }));
+ useTripStore.setState({ trip: buildTrip({ id: 7, currency: 'JPY' }) } as unknown as Partial<TripStoreState>);
+ const fresh = setup().result.current;
+ expect(fresh.currency).toBe('JPY');
+ expect(fresh.currencyChoices.slice(0, 2).map((o) => o.value)).toEqual(['JPY', 'EUR']);
+ expect(fresh.currencyChoices.filter((o) => o.value === 'EUR')).toHaveLength(1);
+ // A scanned receipt knows its own currency, and an edit keeps the saved one.
+ expect(setup({ prefill: { currency: 'usd' } }).result.current.currency).toBe('USD');
+ const editing = buildBudgetItem({ total_price: 20, currency: 'EUR', payers: [], members: [] });
+ expect(setup({ editing }).result.current.currency).toBe('EUR');
+ });
+
it('FE-BUDGET-EXPFORM-003: an edited expense reopens with its payer, its custom split, its note and receipts', () => {
const receipt = { id: 3, filename: 'r.jpg', original_name: 'r.jpg', url: '/uploads/r.jpg' };
const editing = buildBudgetItem({
diff --git a/client/src/components/Budget/useExpenseForm.ts b/client/src/components/Budget/useExpenseForm.ts
index 8d160ac03..c7b5212c8 100644
--- a/client/src/components/Budget/useExpenseForm.ts
+++ b/client/src/components/Budget/useExpenseForm.ts
@@ -26,6 +26,7 @@ import {
type TicketItem,
} from './CostsPanel.helpers';
import { catMeta } from './costsCategories';
+import { currencyOptions } from './costsModel';
import { useExpenseFx } from './expenseFx';
import { saveWithReceipts } from './receiptUploads';
@@ -76,15 +77,20 @@ export function useExpenseForm({
const [name, setName] = useState(editing?.name || prefill?.name || '');
const [cat, setCat] = useState<string>(editing ? catMeta(editing.category).key : prefill?.category || 'food');
+ // A new expense starts in the trip's own currency, the one most bills on the
+ // road come in (#2807); a prefill that knows its currency keeps it.
const [seed] = useState(() =>
newExpenseSeed(
prefill,
- base,
+ tripCur,
people.map((p) => p.id),
localToday()
)
);
const [currency, setCurrencyState] = useState(editing ? editingCurrency : seed.currency);
+ // The trip and display currencies lead the picker: an expense not in the one
+ // is most likely in the other (#2807).
+ const currencyChoices = currencyOptions(currency, [tripCur, base]);
const [day, setDay] = useState(editing ? editing.expense_date || localToday() : seed.day);
const [note, setNote] = useState(() => readUserNote(editing));
// Edit and prefill seeds are padded to the currency's decimals (#2175): the DB
@@ -430,6 +436,7 @@ export function useExpenseForm({
setCat,
currency,
setCurrency,
+ currencyChoices,
day,
setDay,
note,
diff --git a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
index bdcb858b1..578b22240 100644
--- a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
+++ b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
@@ -11,7 +11,6 @@ import { amountToInputString, formatMoney, localizeAmountInput, zeroAmountInput
import { openFile } from '../../../../utils/fileDownload'
import { splitShareLabel } from '../../../../components/Budget/expenseFx'
import { SPLIT_COLORS } from '../../../../components/Budget/BudgetPanel.constants'
-import { currencyOptions } from '../../../../components/Budget/costsModel'
import { COST_CATEGORY_LIST, catMeta } from '../../../../components/Budget/costsCategories'
import { NOTE_MAX } from '../../../../components/Budget/CostsPanel.helpers'
import type { ExpensePrefill } from '../../../../components/Budget/CostsPanel'
@@ -60,7 +59,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
// The same editor as the desktop modal, a saved expense without a currency
// opening in the trip's own (#2525).
const {
- sym, nameOf, tripCur, name, setName, cat, setCat, currency, setCurrency, day, setDay, note, setNote, total, onTotalChange,
+ sym, nameOf, tripCur, name, setName, cat, setCat, currency, setCurrency, currencyChoices, day, setDay, note, setNote, total, onTotalChange,
totalNum, fx, participants, toggleParticipant, payerId, setPayerId, multiPayer, enableMultiPayer, disableMultiPayer,
payerIds, payerAmounts, togglePayer, onPayerAmountChange, payersOk, splitMode, setSplitMode, isTicketMode, ticketItems,
ticketInfo, handleAddEmptyItem, handleUpdateItemName, handleUpdateItemPrice, handleRemoveItem, handleToggleItemParticipant,
@@ -169,7 +168,7 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
onChange={v => setCurrency(String(v))}
searchable
size="sm"
- options={currencyOptions(currency)}
+ options={currencyChoices}
style={{ width: '100%' }}
/>
</div>
diff --git a/wiki/Budget-Tracking.md b/wiki/Budget-Tracking.md
index bc3f74ae9..c3e08dd31 100644
--- a/wiki/Budget-Tracking.md
+++ b/wiki/Budget-Tracking.md
@@ -67,7 +67,7 @@ The filters work together: pick a day and a banner above the list names the day
![The Add expense dialog: the name typed into the head band beside the category pill, then amount, currency and day, Who paid?, Split, and Note beside Receipts & Invoices](assets/ExpenseDialog.png)
-1. Click **Add expense**. The dialog opens dated today, in your display currency (the trip's own unless you picked another in Settings), paid by you and split equally between everyone.
+1. Click **Add expense**. The dialog opens dated today, in the trip's own currency, paid by you and split equally between everyone. In the **Currency** list the trip currency and your display currency come first, since most bills are in one of the two.
2. Type what it was for into the head band, where it reads *e.g. Dinner, souvenirs, gas…*. The name is required. The pill beside it is the category, **Food & drink** until you pick another; the head band takes on its colour.
3. Enter the **Total amount**, and change **Currency** and **Day** if they differ. The **±** beside the amount turns the expense into a refund: a negative total gives money back instead of taking it, and the split runs the other way.
4. Set **Who paid?** and **Split** (both below).