mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 02:56:10 +00:00
fix(costs): settle up only in the currency the debts were read in
After switching the display currency the flows stayed in the old one until the new read landed, or for good when it failed offline, and a settle-up booked those amounts in the new currency. The ledger now remembers the currency it read, drops answers to older reads and only settles flows read in the one shown.
This commit is contained in:
@@ -77,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, countedCount, leftOutLabel, toggleLeftOutCat, countAllCats, exportCsv: handleExportCsv,
|
||||
deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll, setBase, baseOptions,
|
||||
deleteExpense: handleDelete, undoSettlement, settleFlow, settleAll, canSettle, setBase, baseOptions,
|
||||
} = useCostsLedger({
|
||||
tripId, trip, budgetItems, memberCount: tripMembers.length, actions: { loadBudgetItems, deleteBudgetItem }, canEdit, t, toast,
|
||||
settlementOnTripChange: true, skipUnfinishedShares: true, csvCurrencyAsStored: true,
|
||||
@@ -271,7 +271,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
{isMobile ? MobileBody() : (
|
||||
<div style={{ maxWidth: '100%', margin: '0 auto' }}>
|
||||
<CostsToolbar dateMeta={dateMeta} people={people} me={me} colorFor={colorFor} splitting={splitting}
|
||||
canEdit={canEdit} canSettle={(settlement?.flows || []).length > 0}
|
||||
canEdit={canEdit} canSettle={canSettle}
|
||||
onSettleAll={settleAll} onAddExpense={() => { setEditing(null); setModalOpen(true) }}
|
||||
onScanReceipt={receiptScan.offered ? receiptScan.open : undefined}
|
||||
view={view} onView={setView} currency={{ value: base, options: baseOptions, onChange: setBase }}
|
||||
@@ -472,7 +472,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</Tooltip>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
|
||||
<span className="text-content" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700 }}>{fmt(f.amount)}</span>
|
||||
{canEdit && <button type="button" aria-label={`${t('costs.settle')}: ${transferLabel(f.from.user_id, f.to.user_id)}, ${fmt(f.amount)}`} onClick={() => settleFlow(f.from.user_id, f.to.user_id, f.amount)} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '7px 12px', borderRadius: 9, fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>{t('costs.settle')}</button>}
|
||||
{canSettle && <button type="button" aria-label={`${t('costs.settle')}: ${transferLabel(f.from.user_id, f.to.user_id)}, ${fmt(f.amount)}`} onClick={() => settleFlow(f.from.user_id, f.to.user_id, f.amount)} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{ padding: '7px 12px', borderRadius: 9, fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, border: 0, cursor: 'pointer', fontFamily: 'inherit' }}>{t('costs.settle')}</button>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -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-017
|
||||
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-021
|
||||
|
||||
const fx = vi.hoisted(() => ({
|
||||
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
|
||||
@@ -299,12 +299,101 @@ describe('useCostsLedger: another currency for this trip (#1683)', () => {
|
||||
act(() => result.current.setBase('USD'));
|
||||
expect(result.current.base).toBe('USD');
|
||||
await waitFor(() => expect(settlementMock()).toHaveBeenLastCalledWith(7, 'USD', expect.anything()));
|
||||
await waitFor(() => expect(result.current.canSettle).toBe(true));
|
||||
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');
|
||||
});
|
||||
|
||||
it('FE-BUDGET-LEDGER-018: while the read in the new currency runs, nothing is settled in it', async () => {
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
const { result } = setup();
|
||||
await waitFor(() => expect(result.current.canSettle).toBe(true));
|
||||
let answer: (s: CostsSettlementResponse) => void = () => undefined;
|
||||
settlementMock().mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
})
|
||||
);
|
||||
act(() => result.current.setBase('JPY'));
|
||||
await waitFor(() => expect(settlementMock()).toHaveBeenLastCalledWith(7, 'JPY', expect.anything()));
|
||||
// The flows held are still the euro ones.
|
||||
expect(result.current.settlement).toEqual(SETTLEMENT);
|
||||
expect(result.current.canSettle).toBe(false);
|
||||
await act(async () => {
|
||||
await result.current.settleFlow(1, 2, 15);
|
||||
await result.current.settleAll();
|
||||
});
|
||||
expect(createMock()).not.toHaveBeenCalled();
|
||||
await act(async () => answer(SETTLEMENT));
|
||||
await waitFor(() => expect(result.current.canSettle).toBe(true));
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
});
|
||||
|
||||
it('FE-BUDGET-LEDGER-019: a read in the new currency that fails, offline say, leaves the old flows unsettleable', async () => {
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
await clearAll();
|
||||
const { result } = setup();
|
||||
await waitFor(() => expect(result.current.canSettle).toBe(true));
|
||||
settlementMock().mockRejectedValueOnce(new Error('Settlement not available offline'));
|
||||
act(() => result.current.setBase('JPY'));
|
||||
await waitFor(() => expect(result.current.settlementError).toBe(true));
|
||||
expect(result.current.canSettle).toBe(false);
|
||||
await act(async () => {
|
||||
await result.current.settleAll();
|
||||
await result.current.settleFlow(1, 2, 15);
|
||||
});
|
||||
expect(createMock()).not.toHaveBeenCalled();
|
||||
expect(await offlineDb.mutationQueue.count()).toBe(0);
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
});
|
||||
|
||||
it('FE-BUDGET-LEDGER-020: a late answer for the currency picked before does not overwrite the current one', async () => {
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
let answerEur: (s: CostsSettlementResponse) => void = () => undefined;
|
||||
settlementMock().mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
answerEur = resolve;
|
||||
})
|
||||
);
|
||||
const usd: CostsSettlementResponse = { ...SETTLEMENT, flows: [flow(1, 2, 30)], currency: 'USD' };
|
||||
settlementMock().mockResolvedValueOnce(usd);
|
||||
const { result } = setup();
|
||||
await waitFor(() => expect(settlementMock()).toHaveBeenCalledTimes(1));
|
||||
act(() => result.current.setBase('USD'));
|
||||
await waitFor(() => expect(result.current.settlement).toEqual(usd));
|
||||
await act(async () => answerEur(SETTLEMENT));
|
||||
expect(result.current.settlement).toEqual(usd);
|
||||
expect(result.current.canSettle).toBe(true);
|
||||
await act(async () => {
|
||||
await result.current.settleAll();
|
||||
});
|
||||
expect(createMock()).toHaveBeenCalledTimes(1);
|
||||
expect(createMock()).toHaveBeenCalledWith(7, expect.objectContaining({ amount: 30, currency: 'USD' }));
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
});
|
||||
|
||||
it('FE-BUDGET-LEDGER-021: a settlement the server answers in the trip currency, lacking a quote, is not booked in the one picked', async () => {
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
const { result } = setup();
|
||||
await waitFor(() => expect(result.current.canSettle).toBe(true));
|
||||
settlementMock().mockResolvedValueOnce({ ...SETTLEMENT, currency: 'EUR' });
|
||||
act(() => result.current.setBase('JPY'));
|
||||
await waitFor(() => expect(settlementMock()).toHaveBeenLastCalledWith(7, 'JPY', expect.anything()));
|
||||
await waitFor(() => expect(result.current.settlement).toEqual({ ...SETTLEMENT, currency: 'EUR' }));
|
||||
expect(result.current.settlementError).toBe(false);
|
||||
expect(result.current.canSettle).toBe(false);
|
||||
await act(async () => {
|
||||
await result.current.settleFlow(1, 2, 15);
|
||||
await result.current.settleAll();
|
||||
});
|
||||
expect(createMock()).not.toHaveBeenCalled();
|
||||
localStorage.removeItem('trek:costs-currency:7');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCostsLedger: writes', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CostCategory } from '@trek/shared';
|
||||
import { liveQuery } from 'dexie';
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { useExchangeRates, withFallbackFx } from '../../hooks/useExchangeRates';
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
@@ -112,20 +112,31 @@ export function useCostsLedger({
|
||||
// A failed settlement read leaves `settlement` null, which the views would
|
||||
// otherwise present as "everyone is square", a balance claim we cannot make.
|
||||
const [settlementError, setSettlementError] = useState(false);
|
||||
// The currency the flows held in `settlement` are in. After the currency is
|
||||
// switched they stay in the old one until the new read lands, or for good when
|
||||
// that read fails offline, so a settle-up must not book them in the new one.
|
||||
const [settledIn, setSettledIn] = useState<string | null>(null);
|
||||
// Only the latest read may land: an answer for the currency picked before would
|
||||
// otherwise overwrite the one for the currency shown now.
|
||||
const latestRead = useRef(0);
|
||||
|
||||
// The browser's own figure for the display currency goes along, for the server to
|
||||
// answer in it when it cannot fetch a quote itself.
|
||||
const readSettlement = useCallback(
|
||||
() =>
|
||||
budgetRepo
|
||||
.settlement(tripId, base, base !== tripCurrency ? displayPerTrip : null)
|
||||
.then((s) => {
|
||||
setSettlement(s);
|
||||
setSettlementError(false);
|
||||
})
|
||||
.catch(() => setSettlementError(true)),
|
||||
[tripId, base, tripCurrency, displayPerTrip]
|
||||
);
|
||||
const readSettlement = useCallback(() => {
|
||||
const read = ++latestRead.current;
|
||||
return budgetRepo
|
||||
.settlement(tripId, base, base !== tripCurrency ? displayPerTrip : null)
|
||||
.then((s: CostsSettlementResponse) => {
|
||||
if (read !== latestRead.current) return;
|
||||
setSettlement(s);
|
||||
// Without a quote for the display currency the server answers in the trip's own.
|
||||
setSettledIn((s.currency || base).toUpperCase());
|
||||
setSettlementError(false);
|
||||
})
|
||||
.catch(() => {
|
||||
if (read === latestRead.current) setSettlementError(true);
|
||||
});
|
||||
}, [tripId, base, tripCurrency, displayPerTrip]);
|
||||
const loadSettlement = useCallback(() => {
|
||||
void readSettlement();
|
||||
}, [readSettlement]);
|
||||
@@ -202,6 +213,10 @@ export function useCostsLedger({
|
||||
|
||||
const shareOf = skipUnfinishedShares ? settledShareOf : myShareOf;
|
||||
const flows = useMemo(() => settlement?.flows || [], [settlement]);
|
||||
// A settle-up books the flows in the display currency, so only flows read in it
|
||||
// may be booked: not after a failed read, and not while they are in another one.
|
||||
// And only by someone who may edit the costs at all.
|
||||
const canSettle = canEdit && !settlementError && settledIn === base && flows.length > 0;
|
||||
const splitting = useMemo(
|
||||
() => showsSplitting(trip?.costs_mode, memberCount, budgetItems, settlement, me),
|
||||
[trip?.costs_mode, memberCount, budgetItems, settlement, me]
|
||||
@@ -283,6 +298,7 @@ export function useCostsLedger({
|
||||
// A quick settle is dated on the viewer's own day, as the payment dialog dates
|
||||
// it, so it is not left to the server's UTC clock (#2604).
|
||||
const settleFlow = async (fromId: number, toId: number, amount: number) => {
|
||||
if (!canSettle) return;
|
||||
try {
|
||||
const result = await budgetRepo.createSettlement(
|
||||
tripId,
|
||||
@@ -298,7 +314,7 @@ export function useCostsLedger({
|
||||
};
|
||||
|
||||
const settleAll = async () => {
|
||||
if (!flows.length) return;
|
||||
if (!canSettle) return;
|
||||
let queued = false;
|
||||
try {
|
||||
for (const f of flows) {
|
||||
@@ -337,6 +353,7 @@ export function useCostsLedger({
|
||||
settlementError,
|
||||
loadSettlement,
|
||||
flows,
|
||||
canSettle,
|
||||
splitting,
|
||||
knownNames,
|
||||
search,
|
||||
|
||||
Reference in New Issue
Block a user