feat(assistant): expense, payment and settle-up cards, and expense links into Costs

This commit is contained in:
Maurice
2026-10-22 15:50:49 +02:00
parent c94545419b
commit b52990bf27
65 changed files with 4763 additions and 95 deletions
+4 -10
View File
@@ -1,5 +1,4 @@
import { Fragment, useState, useEffect, useMemo, useCallback, useId, type ReactNode } from 'react'
import { useSearchParams } from 'react-router'
import { Fragment, useState, useMemo, useCallback, useId, type ReactNode } from 'react'
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download, StickyNote, ChevronDown, Receipt, Paperclip, ScanLine, Users } from 'lucide-react'
import { useTripStore } from '../../store/tripStore'
import { useCanDo } from '../../store/permissionsStore'
@@ -22,6 +21,7 @@ import {
type CostsSettlement as Settlement, type CostsSettlementResponse,
} from './costsModel'
import { useCostsLedger } from './useCostsLedger'
import { useExpenseLinks } from './useExpenseLinks'
import { useSettlementForm } from './useSettlementForm'
import { usePercentSplit, type CustomSplitUnit } from './usePercentSplit'
import { useExpenseForm } from './useExpenseForm'
@@ -119,14 +119,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const fmt = useCallback((v: number, c = base) => formatMoney(v, c, locale), [base, locale])
const fmt0 = useCallback((v: number, c = base) => formatMoney(v, c, locale, { decimals: 0 }), [base, locale])
// The bottom-nav "+" on the Costs tab opens the add-expense modal via ?create=expense.
const [searchParams, setSearchParams] = useSearchParams()
useEffect(() => {
if (searchParams.get('create') === 'expense') {
setEditing(null); setModalOpen(true)
setSearchParams(p => { p.delete('create'); return p }, { replace: true })
}
}, [searchParams])
// The bottom-nav "+" (?create=expense) and a link to one expense (?expense=<id>) open the expense modal.
useExpenseLinks(tripId, budgetItems, e => { setEditing(e); setModalOpen(true) }, { create: true })
// ── derived expense maths (everything converted to the base currency) ────
// Booked, not live: an expense entered in a foreign currency keeps the rate it was
@@ -0,0 +1,119 @@
/**
* FE-COSTS-LINK-001 to FE-COSTS-LINK-006
*
* The links into the Costs tab that open the expense dialog: one expense
* (`?expense=<id>`, the assistant's "Open in Costs"), reading the expenses
* once more when the store does not hold it yet, dropped once taken or when
* that read does not bring it either; and the bottom bar's "+"
* (`?create=expense`) where the view asks for it.
*/
import { useSearchParams } from 'react-router';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { buildBudgetItem } from '../../../tests/helpers/factories';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTripStore } from '../../store/tripStore';
import type { BudgetItem } from '../../types';
import { useExpenseLinks } from './useExpenseLinks';
let reload: Mock<(tripId: number | string) => Promise<void>>;
function Probe({
items,
open,
create = false,
}: {
items: BudgetItem[];
open: (expense: BudgetItem | null) => void;
create?: boolean;
}) {
useExpenseLinks(4, items, open, { create });
const [params] = useSearchParams();
return <output aria-label="search">{params.toString()}</output>;
}
const search = () => screen.getByRole('status', { name: 'search' }).textContent;
describe('useExpenseLinks', () => {
beforeEach(() => {
resetAllStores();
reload = vi.fn<(tripId: number | string) => Promise<void>>(async () => undefined);
useTripStore.setState({ loadBudgetItems: reload });
});
it('FE-COSTS-LINK-001: opens the expense a link names and drops only its own part of the address', () => {
const dinner = buildBudgetItem({ id: 31 });
const open = vi.fn();
render(<Probe items={[buildBudgetItem({ id: 30 }), dinner]} open={open} />, {
initialEntries: ['/trips/4?tab=finanzplan&expense=31'],
});
expect(open).toHaveBeenCalledTimes(1);
expect(open).toHaveBeenCalledWith(dinner);
expect(search()).toBe('tab=finanzplan');
expect(reload).not.toHaveBeenCalled();
});
it('FE-COSTS-LINK-002: an expense not in the store yet reads the expenses again and opens once it arrives', async () => {
let arrive: () => void = () => undefined;
reload.mockImplementation(
() =>
new Promise<void>((resolve) => {
arrive = resolve;
})
);
const open = vi.fn();
const first = render(<Probe items={[buildBudgetItem({ id: 30 })]} open={open} />, {
initialEntries: ['/trips/4?expense=31'],
});
expect(reload).toHaveBeenCalledTimes(1);
expect(reload).toHaveBeenCalledWith(4);
expect(search()).toBe('expense=31');
const dinner = buildBudgetItem({ id: 31 });
first.rerender(<Probe items={[buildBudgetItem({ id: 30 }), dinner]} open={open} />);
expect(open).toHaveBeenCalledWith(dinner);
expect(search()).toBe('');
// The read that was still under way changes nothing once it lands.
arrive();
await waitFor(() => expect(open).toHaveBeenCalledTimes(1));
expect(search()).toBe('');
});
it('FE-COSTS-LINK-003: a malformed id is dropped at once, expenses or not', () => {
const open = vi.fn();
render(<Probe items={[]} open={open} />, { initialEntries: ['/trips/4?expense=dinner'] });
expect(open).not.toHaveBeenCalled();
expect(reload).not.toHaveBeenCalled();
expect(search()).toBe('');
});
it('FE-COSTS-LINK-004: the "+" opens an empty dialog where the view asks for it, and is left alone elsewhere', () => {
const open = vi.fn();
const first = render(<Probe items={[]} open={open} create />, { initialEntries: ['/trips/4?create=expense'] });
expect(open).toHaveBeenCalledWith(null);
expect(search()).toBe('');
first.unmount();
const phone = vi.fn();
render(<Probe items={[]} open={phone} />, { initialEntries: ['/trips/4?create=expense'] });
expect(phone).not.toHaveBeenCalled();
expect(search()).toBe('create=expense');
});
it('FE-COSTS-LINK-005: an id the second read does not bring either is dropped without opening anything', async () => {
const open = vi.fn();
render(<Probe items={[buildBudgetItem({ id: 5 })]} open={open} />, { initialEntries: ['/trips/4?expense=99'] });
expect(search()).toBe('expense=99');
await waitFor(() => expect(search()).toBe(''));
expect(reload).toHaveBeenCalledTimes(1);
expect(open).not.toHaveBeenCalled();
});
it('FE-COSTS-LINK-006: on a trip without any expense the link is still dropped after the read', async () => {
const open = vi.fn();
render(<Probe items={[]} open={open} />, { initialEntries: ['/trips/4?tab=finanzplan&expense=31'] });
await waitFor(() => expect(search()).toBe('tab=finanzplan'));
expect(reload).toHaveBeenCalledTimes(1);
expect(open).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,62 @@
import { useEffect, useEffectEvent, useState } from 'react';
import { useSearchParams } from 'react-router';
import { useTripStore } from '../../store/tripStore';
import type { BudgetItem } from '../../types';
/**
* The links into the Costs tab that open the expense dialog, taken once and
* then dropped from the URL so a reload or the way back does not repeat them.
* `?expense=<id>` opens that expense the way a click on its row does: the
* assistant's "Open in Costs" on an expense lands here, on the desktop and on
* the phone alike. An id the store does not hold yet (an expense the
* assistant just created, before its broadcast arrived) reads the expenses
* once more; an id that read does not bring either is dropped without a word,
* on a trip without any expense too. What opening means is the view's: the
* phone opens its edit sheet only for an editor, as its rows do. With
* `create`, the bottom bar's "+" opens an empty dialog, as on the desktop.
*/
export function useExpenseLinks(
tripId: number | string,
budgetItems: readonly BudgetItem[],
open: (expense: BudgetItem | null) => void,
{ create = false }: { create?: boolean } = {}
): void {
const [searchParams, setSearchParams] = useSearchParams();
const loadBudgetItems = useTripStore((state) => state.loadBudgetItems);
// The link whose expenses were read again for it: after that read it is done, found or not.
const [checked, setChecked] = useState<string | null>(null);
const creating = create && searchParams.get('create') === 'expense';
const asked = searchParams.get('expense');
const id = asked === null ? null : Number(asked);
const malformed = id !== null && (!Number.isInteger(id) || id <= 0);
const found = id === null || malformed ? undefined : budgetItems.find((item) => item.id === id);
const settled = asked !== null && (found !== undefined || malformed || checked === asked);
const openExpense = useEffectEvent(open);
const readAgain = useEffectEvent(() => Promise.resolve(loadBudgetItems(tripId)));
useEffect(() => {
if (asked === null || settled) return;
let live = true;
void readAgain().finally(() => {
if (live) setChecked(asked);
});
return () => {
live = false;
};
}, [asked, settled]);
useEffect(() => {
if (!creating && !settled) return;
if (creating) openExpense(null);
else if (found) openExpense(found);
setSearchParams(
(params) => {
if (creating) params.delete('create');
if (settled) params.delete('expense');
return params;
},
{ replace: true }
);
}, [creating, settled, found, setSearchParams]);
}