mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
feat(costs): read a trip in another currency from the Costs tab (#1683)
Costs always converted to the display currency from Settings, so a trip that moves on to another country could not be read in its new local currency. A picker in the Costs bar (beside the Expenses heading on the phone) now reads one trip in any currency; the server already settles in any base. The pick is per trip and kept in this browser, nothing stored.
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import { useTranslation } from '../../i18n';
|
||||
import CustomSelect from '../shared/CustomSelect';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
/**
|
||||
* Which currency Costs shows the trip in (#1683): a compact select with the
|
||||
* usual currency and the trip's own on top. Desktop bar, narrow window and phone
|
||||
* tab alike; the pick itself lives in useCostsCurrency.
|
||||
*/
|
||||
export function CostsCurrencyPicker({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
value: string;
|
||||
options: { value: string; label: string }[];
|
||||
onChange: (currency: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Tooltip label={t('costs.showIn')}>
|
||||
<div className="w-[92px] flex-none">
|
||||
<CustomSelect
|
||||
ariaLabel={t('costs.showIn')}
|
||||
value={value}
|
||||
onChange={(v) => onChange(String(v))}
|
||||
options={options}
|
||||
size="sm"
|
||||
searchable
|
||||
menuFit="content"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -741,7 +741,7 @@ describe('CostsPanel — settlements in the ledger', () => {
|
||||
await user.click(await screen.findByRole('button', { name: 'Add payment' }))
|
||||
await user.type(await screen.findByPlaceholderText('0,00'), '25')
|
||||
// Bob paid me back in dollars — the server freezes the USD rate on write.
|
||||
await user.click(screen.getByText(/^EUR/))
|
||||
await user.click(within(screen.getByRole('dialog')).getByText(/^EUR/))
|
||||
await user.click(await screen.findByText(/^USD/))
|
||||
const addButtons = screen.getAllByRole('button', { name: 'Add payment' })
|
||||
await user.click(addButtons[addButtons.length - 1])
|
||||
@@ -1451,7 +1451,7 @@ describe('CostsPanel — expense modal', () => {
|
||||
|
||||
await user.type(screen.getByPlaceholderText('e.g. Dinner, souvenirs, gas…'), 'Diner')
|
||||
await user.type(screen.getAllByPlaceholderText('0,00')[0], '100')
|
||||
await user.click(screen.getByText(/^EUR/))
|
||||
await user.click(within(screen.getByRole('dialog')).getByText(/^EUR/))
|
||||
await user.click(await screen.findByText(/^USD/))
|
||||
|
||||
expect(screen.getByText('live rate', { exact: false })).toBeInTheDocument()
|
||||
@@ -2493,7 +2493,7 @@ describe('CostsPanel: a bill entered in the display currency (#2525)', () => {
|
||||
// Seeding the display currency here would label 100 euro as 100 dollars, and a
|
||||
// plain save would then store it that way.
|
||||
expect(screen.getByText(/^EUR/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/^USD/)).toBeNull()
|
||||
expect(within(screen.getByRole('dialog')).queryByText(/^USD/)).toBeNull()
|
||||
|
||||
// Saving without touching anything keeps the 100 euro.
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
|
||||
@@ -32,6 +32,7 @@ import { FlowPills } from './FlowPills'
|
||||
import { CostsSplitChips } from './CostsSplitChips'
|
||||
import { CostsModeCard } from './CostsModeCard'
|
||||
import { CostsCategoryBreakdown } from './CostsCategoryBreakdown'
|
||||
import { CostsCurrencyPicker } from './CostsCurrencyPicker'
|
||||
import type { BudgetParticipantFinal, ReceiptLine } from '@trek/shared'
|
||||
import type { BudgetItem, BudgetItemReceipt } from '../../types'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
@@ -76,7 +77,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
me, base, tripCurrency, ctx, settlement, settlementError, loadSettlement, knownNames, splitting,
|
||||
search, setSearch, segment: filter, setSegment: setFilter, catFilter, setCatFilter, dayFilter, setDayFilter,
|
||||
totals, filtered, filteredSettlements, catBreakdown, leftOutLabel, toggleLeftOutCat, countAllCats, exportCsv: handleExportCsv,
|
||||
deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll,
|
||||
deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll, setBase, baseOptions,
|
||||
} = useCostsLedger({
|
||||
tripId, trip, budgetItems, memberCount: tripMembers.length, actions: { loadBudgetItems, deleteBudgetItem }, canEdit, t, toast,
|
||||
settlementOnTripChange: true, skipUnfinishedShares: true, csvCurrencyAsStored: true,
|
||||
@@ -273,7 +274,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
canEdit={canEdit} canSettle={(settlement?.flows || []).length > 0}
|
||||
onSettleAll={settleAll} onAddExpense={() => { setEditing(null); setModalOpen(true) }}
|
||||
onScanReceipt={receiptScan.offered ? receiptScan.open : undefined}
|
||||
view={view} onView={setView}
|
||||
view={view} onView={setView} currency={{ value: base, options: baseOptions, onChange: setBase }}
|
||||
filters={{
|
||||
query: search, onQuery: setSearch,
|
||||
owner: filter, onOwner: setFilter,
|
||||
@@ -557,7 +558,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
{/* Expenses */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(19px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.02em' }}>{t('costs.expenses')}</div>
|
||||
<div className="text-content" style={{ fontSize: 'calc(19px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.02em', marginInlineEnd: 'auto' }}>{t('costs.expenses')}</div>
|
||||
<CostsCurrencyPicker value={base} options={baseOptions} onChange={setBase} />
|
||||
<Tooltip label={t('budget.exportCsv')}>
|
||||
<button type="button" onClick={handleExportCsv} aria-label={t('budget.exportCsv')} disabled={!budgetItems.length}
|
||||
className="bg-surface-card border border-edge text-content-muted disabled:opacity-40"
|
||||
@@ -602,7 +604,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
{BalancesList({ balances: settlement?.balances || [] })}
|
||||
</div>
|
||||
|
||||
{/* Final budget */}
|
||||
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.finalBudget')}</div>
|
||||
{FinalBudgetList()}
|
||||
@@ -1362,7 +1363,6 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nothing to split on a trip of one (#2689). */}
|
||||
{showSplit && payerSection}
|
||||
{showSplit && splitSection}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COSTSBAR-001 to FE-COSTSBAR-014
|
||||
// FE-COSTSBAR-001 to FE-COSTSBAR-015
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
@@ -83,6 +83,17 @@ describe('CostsToolbar', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Scan receipt' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COSTSBAR-015: shows the currency the tab reads in, and reports another one picked (#1683)', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
setup({ currency: { value: 'EUR', options: [{ value: 'EUR', label: 'EUR €' }, { value: 'VND', label: 'VND ₫' }], onChange } })
|
||||
const picker = screen.getByRole('button', { name: 'Show amounts in' })
|
||||
expect(picker).toHaveTextContent('EUR')
|
||||
await user.click(picker)
|
||||
await user.click(await screen.findByText(/^VND\s/))
|
||||
expect(onChange).toHaveBeenCalledWith('VND')
|
||||
})
|
||||
|
||||
describe('search and filters', () => {
|
||||
function filters(over: Partial<CostsFilterProps> = {}): CostsFilterProps {
|
||||
return {
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { TripMember } from './BudgetPanelMemberChips'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { POPOVER, POPOVER_CAPTION, POPOVER_DIVIDER, useDismissOnOutside } from '../Packing/packingPopoverStyles'
|
||||
import { PopoverItem } from '../Packing/PackingPopover'
|
||||
import { CostsCurrencyPicker } from './CostsCurrencyPicker'
|
||||
|
||||
export type OwnerFilter = 'all' | 'mine' | 'owed'
|
||||
/** The day-by-day list, or the categorized table the old budget had. */
|
||||
@@ -51,6 +52,8 @@ interface CostsToolbarProps {
|
||||
/** The switch between the list and the table; left out, the bar has none. */
|
||||
view?: CostsView
|
||||
onView?: (view: CostsView) => void
|
||||
/** Which currency the tab shows the trip in (#1683); left out, the bar has no picker. */
|
||||
currency?: Parameters<typeof CostsCurrencyPicker>[0]
|
||||
}
|
||||
|
||||
const BODY_SIZE = 'calc(13px * var(--fs-scale-body, 1))'
|
||||
@@ -62,7 +65,7 @@ const BAR_BTN = 'relative grid h-9 w-9 flex-none place-items-center rounded-[10p
|
||||
* Bookings, Lists and Files open with: the tab's name and what the numbers
|
||||
* cover, then how to narrow the ledger and the actions on the right.
|
||||
*/
|
||||
export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit, canSettle, splitting = true, onSettleAll, onAddExpense, onScanReceipt, filters, view, onView }: CostsToolbarProps) {
|
||||
export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit, canSettle, splitting = true, onSettleAll, onAddExpense, onScanReceipt, filters, view, onView, currency }: CostsToolbarProps) {
|
||||
const { t } = useTranslation()
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const chip = 'inline-flex items-center whitespace-nowrap rounded-full bg-surface-card px-3 py-1.5 font-medium text-content-muted shadow-sm'
|
||||
@@ -130,6 +133,8 @@ export default function CostsToolbar({ dateMeta, people, me, colorFor, canEdit,
|
||||
</>
|
||||
)}
|
||||
|
||||
{currency && <CostsCurrencyPicker {...currency} />}
|
||||
|
||||
{view && onView && (
|
||||
// The same switch the Bookings bar has for its views.
|
||||
<div role="group" aria-label={t('costs.view.label')} className="inline-flex flex-none rounded-[10px] bg-surface-card p-[3px]">
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// FE-BUDGET-COSTSCUR-001 to FE-BUDGET-COSTSCUR-003
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildTrip } from '../../../tests/helpers/factories';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useCostsCurrency } from './useCostsCurrency';
|
||||
|
||||
const trip = buildTrip({ id: 7, currency: 'VND' });
|
||||
|
||||
function setDisplayCurrency(currency: string) {
|
||||
useSettingsStore.setState((s) => ({ settings: { ...s.settings, default_currency: currency } }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
localStorage.removeItem('trek:costs-currency:8');
|
||||
});
|
||||
|
||||
describe('useCostsCurrency (#1683)', () => {
|
||||
it('FE-BUDGET-COSTSCUR-001: reads in the display currency, else in the trip currency, both on top of the picker', () => {
|
||||
setDisplayCurrency('SGD');
|
||||
const { result } = renderHook(() => useCostsCurrency(7, trip));
|
||||
expect(result.current.base).toBe('SGD');
|
||||
expect(result.current.baseOptions.slice(0, 2).map((o) => o.value)).toEqual(['SGD', 'VND']);
|
||||
setDisplayCurrency('');
|
||||
expect(renderHook(() => useCostsCurrency(7, trip)).result.current.base).toBe('VND');
|
||||
});
|
||||
|
||||
it('FE-BUDGET-COSTSCUR-002: another currency is kept for this trip in this browser, and the usual one drops it', () => {
|
||||
setDisplayCurrency('SGD');
|
||||
const { result, rerender } = renderHook(({ id }) => useCostsCurrency(id, trip), { initialProps: { id: 7 } });
|
||||
act(() => result.current.setBase('vnd'));
|
||||
expect(result.current.base).toBe('VND');
|
||||
expect(localStorage.getItem('trek:costs-currency:7')).toBe('VND');
|
||||
// Opened again later, the trip still reads in it; another trip does not.
|
||||
expect(renderHook(() => useCostsCurrency(7, trip)).result.current.base).toBe('VND');
|
||||
rerender({ id: 8 });
|
||||
expect(result.current.base).toBe('SGD');
|
||||
rerender({ id: 7 });
|
||||
act(() => result.current.setBase('SGD'));
|
||||
expect(result.current.base).toBe('SGD');
|
||||
expect(localStorage.getItem('trek:costs-currency:7')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-BUDGET-COSTSCUR-003: once the pick is dropped, a new display currency in Settings applies again', () => {
|
||||
setDisplayCurrency('SGD');
|
||||
const { result } = renderHook(() => useCostsCurrency(7, trip));
|
||||
act(() => result.current.setBase('SGD'));
|
||||
act(() => setDisplayCurrency('EUR'));
|
||||
expect(result.current.base).toBe('EUR');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { Trip } from '../../types';
|
||||
import { currencyOptions } from './costsModel';
|
||||
|
||||
const storageKey = (tripId: number) => `trek:costs-currency:${tripId}`;
|
||||
|
||||
/** The currency picked for one trip's Costs in this browser, or null for the usual one. */
|
||||
function readPicked(tripId: number): string | null {
|
||||
try {
|
||||
return localStorage.getItem(storageKey(tripId));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writePicked(tripId: number, currency: string | null) {
|
||||
try {
|
||||
if (currency) localStorage.setItem(storageKey(tripId), currency);
|
||||
else localStorage.removeItem(storageKey(tripId));
|
||||
} catch {
|
||||
/* storage unavailable: the choice lasts until reload */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The currency Costs shows a trip in (#1683). Usually the user's display currency
|
||||
* from Settings, else the trip's own; a trip can be read in another one, say the
|
||||
* currency of the country the travellers go on to, without touching Settings or
|
||||
* anything stored. The pick is per trip and kept in this browser, like the
|
||||
* list or table view: it is how this person reads the trip, not part of it. The
|
||||
* server converts the settlement into whatever base it is asked for.
|
||||
*/
|
||||
export function useCostsCurrency(tripId: number, trip: Trip | null | undefined) {
|
||||
const displayCurrency = useSettingsStore((s) => s.settings.default_currency);
|
||||
const usual = (displayCurrency || trip?.currency || 'EUR').toUpperCase();
|
||||
const stored = useMemo(() => readPicked(tripId), [tripId]);
|
||||
const [pickedByTrip, setPickedByTrip] = useState<Record<number, string | null>>({});
|
||||
const picked = tripId in pickedByTrip ? pickedByTrip[tripId] : stored;
|
||||
const base = (picked || usual).toUpperCase();
|
||||
|
||||
// Picking the usual currency drops the pick, so a later change in Settings applies again.
|
||||
const setBase = (next: string) => {
|
||||
const currency = next.toUpperCase() === usual ? null : next.toUpperCase();
|
||||
writePicked(tripId, currency);
|
||||
setPickedByTrip((prev) => ({ ...prev, [tripId]: currency }));
|
||||
};
|
||||
|
||||
// The usual currency and the trip's own lead the list, the two most read in.
|
||||
const baseOptions = currencyOptions(base, [usual, (trip?.currency || usual).toUpperCase()]);
|
||||
|
||||
return { base, usual, setBase, baseOptions };
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import type { CostsSettlementResponse } from './costsModel';
|
||||
import { useCostsLedger } from './useCostsLedger';
|
||||
import { useFreezeMissingRates } from './useFreezeMissingRates';
|
||||
|
||||
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-016
|
||||
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-017
|
||||
|
||||
const fx = vi.hoisted(() => ({
|
||||
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
|
||||
@@ -291,6 +291,22 @@ describe('useCostsLedger: categories left out (#2819)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCostsLedger: another currency for this trip (#1683)', () => {
|
||||
it('FE-BUDGET-LEDGER-017: the balances are read again in the currency picked, and the settle-ups go out in it', async () => {
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
const { result } = setup();
|
||||
await waitFor(() => expect(result.current.settlement).toEqual(SETTLEMENT));
|
||||
act(() => result.current.setBase('USD'));
|
||||
expect(result.current.base).toBe('USD');
|
||||
await waitFor(() => expect(settlementMock()).toHaveBeenLastCalledWith(7, 'USD', expect.anything()));
|
||||
await act(async () => {
|
||||
await result.current.settleFlow(1, 2, 15);
|
||||
});
|
||||
expect(createMock()).toHaveBeenCalledWith(7, expect.objectContaining({ amount: 15, currency: 'USD' }));
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCostsLedger: writes', () => {
|
||||
it('FE-BUDGET-LEDGER-009: deleting an expense reads the settlement again, a failure toasts', async () => {
|
||||
const { result } = setup();
|
||||
|
||||
@@ -7,7 +7,6 @@ import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { budgetRepo, type SettlementWriteResult } from '../../repo/budgetRepo';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { TripStoreState } from '../../store/tripStore';
|
||||
import { useServerPing } from '../../sync/useServerPing';
|
||||
import type { BudgetItem, Trip } from '../../types';
|
||||
@@ -28,6 +27,7 @@ import {
|
||||
type CostsSettlementResponse,
|
||||
} from './costsModel';
|
||||
import { knownPersonNames } from './CostsPanel.helpers';
|
||||
import { useCostsCurrency } from './useCostsCurrency';
|
||||
import { useFreezeMissingRates } from './useFreezeMissingRates';
|
||||
|
||||
/** The events after which the balances are read again from the server. */
|
||||
@@ -95,11 +95,11 @@ export function useCostsLedger({
|
||||
const me = useAuthStore((s) => s.user?.id ?? -1);
|
||||
|
||||
// Display/base currency = the user's preferred currency (Settings), falling back
|
||||
// to the trip's own currency. Everything in Costs is converted to and shown in it.
|
||||
const displayCurrency = useSettingsStore((s) => s.settings.default_currency);
|
||||
const base = (displayCurrency || trip?.currency || 'EUR').toUpperCase();
|
||||
// to the trip's own currency, unless this trip is read in another one (#1683).
|
||||
// Everything in Costs is converted to and shown in it.
|
||||
const { base, usual, setBase, baseOptions } = useCostsCurrency(tripId, trip);
|
||||
// Pre-rework rows stored currency = NULL, meaning "the trip's own currency".
|
||||
const tripCurrency = (trip?.currency || base).toUpperCase();
|
||||
const tripCurrency = (trip?.currency || usual).toUpperCase();
|
||||
// Anchored on the trip currency's quote, the one the server books with (#2525).
|
||||
const { convert, displayPerTrip } = useExchangeRates(base, tripCurrency);
|
||||
const ctx: CostsCtx = useMemo(
|
||||
@@ -326,6 +326,8 @@ export function useCostsLedger({
|
||||
return {
|
||||
me,
|
||||
base,
|
||||
setBase,
|
||||
baseOptions,
|
||||
tripCurrency,
|
||||
ctx,
|
||||
settlement,
|
||||
|
||||
Reference in New Issue
Block a user