From dab3b953f545809c7e7774ed0c6757f9d383b9b2 Mon Sep 17 00:00:00 2001 From: Ame <37273244+ame180@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:48:34 +0100 Subject: [PATCH 1/3] feat: pick, show and stop expense repeats in the app --- frontend/src/api/types.ts | 26 ++++++ frontend/src/components/ConfirmSheet.tsx | 4 + .../features/activity/ActivityRows.test.tsx | 9 ++ .../src/features/activity/ActivityRows.tsx | 13 ++- frontend/src/features/add/AddPage.test.tsx | 1 + frontend/src/features/add/DateNoteFields.tsx | 13 ++- frontend/src/features/add/DateSheet.tsx | 66 +++++++++---- .../src/features/add/EditExpensePage.test.tsx | 73 ++++++++++++++- frontend/src/features/add/EditExpensePage.tsx | 17 +++- frontend/src/features/add/ExpenseForm.tsx | 37 +++++++- .../src/features/add/expenseDraft.test.ts | 28 +++++- frontend/src/features/add/expenseDraft.ts | 9 ++ frontend/src/features/detail/DetailParts.tsx | 3 + .../detail/ExpenseDetailPage.test.tsx | 41 +++++++++ .../src/features/detail/ExpenseDetailPage.tsx | 54 ++++++++++- frontend/src/lib/repeat.ts | 86 +++++++++++++++++ frontend/src/locales/en.po | 92 +++++++++++++++++++ frontend/src/locales/pl.po | 92 +++++++++++++++++++ frontend/src/test/activity.ts | 2 + frontend/src/test/detail.ts | 2 + 20 files changed, 636 insertions(+), 32 deletions(-) create mode 100644 frontend/src/lib/repeat.ts diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index ce00209..e52c4c7 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -56,6 +56,14 @@ export type ExpenseDebtRequest = { value?: string | null } +export type RepeatUnit = 'week' | 'month' | 'year' + +/** Weekly, every 2 weeks, monthly or yearly: the only combinations the API accepts for now. */ +export type Repeat = { + unit: RepeatUnit + every: number +} + export type ExpenseRequest = { title: string amount: string @@ -65,6 +73,8 @@ export type ExpenseRequest = { splitType?: SplitType category?: ExpenseCategory description?: string | null + /** null or omitted: no repeat (on the latest, that stops it). Only the latest in a repeat may set it. */ + repeat?: Repeat | null } export type ExpenseDebtResponse = { @@ -84,6 +94,20 @@ export type ExpenseResponse = { splitType: SplitType category: ExpenseCategory debts: ExpenseDebtResponse[] + /** Set on every expense in a repeat, the latest or an older one, active or stopped. */ + repeat: RepeatResponse | null + series: SeriesResponse | null +} + +export type RepeatResponse = Repeat & { + /** Null once the repeat has stopped. */ + nextOn: string | null + active: boolean +} + +export type SeriesResponse = { + latestId: number + isLatest: boolean } export type CommentRequest = { @@ -138,6 +162,8 @@ export type ActivityItem = { /** Transfers only. */ payer: PersonRef | null category: ExpenseCategory | null + /** The expense is part of a repeat, active or stopped. */ + recurring: boolean } export type ContactRequest = { diff --git a/frontend/src/components/ConfirmSheet.tsx b/frontend/src/components/ConfirmSheet.tsx index 096d632..0907c96 100644 --- a/frontend/src/components/ConfirmSheet.tsx +++ b/frontend/src/components/ConfirmSheet.tsx @@ -19,6 +19,8 @@ type ConfirmSheetProps = { onOpenChange: (open: boolean) => void title: string description: string + /** An extra line under the description, such as what else the action stops. */ + note?: ReactNode /** The destructive action: "Delete expense", "Discard". */ confirmLabel: string onConfirm: () => void @@ -35,6 +37,7 @@ export function ConfirmSheet({ onOpenChange, title, description, + note, confirmLabel, onConfirm, cancelLabel, @@ -49,6 +52,7 @@ export function ConfirmSheet({ {title} {description} + {note} {!noteOpen && ( - + {repeatChoices.map((choice) => ( + + ))} + + + )} + {(isFuture || repeat) && ( + )} diff --git a/frontend/src/features/add/EditExpensePage.test.tsx b/frontend/src/features/add/EditExpensePage.test.tsx index ba524da..d674383 100644 --- a/frontend/src/features/add/EditExpensePage.test.tsx +++ b/frontend/src/features/add/EditExpensePage.test.tsx @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { screen } from '@testing-library/react' +import { screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { ExpenseResponse } from '@/api/types' import { jsonResponse, renderRoutes } from '@/test/utils' @@ -22,6 +22,8 @@ const expense: ExpenseResponse = { { payer: meRef, amount: '40.00', splitValue: '2.00' }, { payer: anna, amount: '20.00', splitValue: '1.00' }, ], + repeat: null, + series: null, } afterEach(() => { @@ -70,9 +72,78 @@ describe('EditExpensePage', () => { splitType: 'shares', category: 'entertainment', description: null, + repeat: null, }) }) + it('edits the repeat of the latest, saying the next one copies the changes', async () => { + const latest: ExpenseResponse = { + ...expense, + repeat: { unit: 'month', every: 1, nextOn: '2026-11-20T00:00:00+00:00', active: true }, + series: { latestId: 7, isLatest: true }, + } + const fetchMock = vi.fn(async (path: string, init?: RequestInit) => { + const key = `${init?.method ?? 'GET'} ${path}` + if (key === 'GET /api/me') return jsonResponse(200, me) + if (key === 'GET /api/contacts') return jsonResponse(200, { totals: [], items: [] }) + if (key === 'GET /api/expenses/7') return jsonResponse(200, latest) + if (key === 'PUT /api/expenses/7') return jsonResponse(200, latest) + throw new Error(`Unexpected ${key}`) + }) + vi.stubGlobal('fetch', fetchMock) + renderRoutes( + [ + { path: '/expenses/:id/edit', element: }, + { path: '/expenses/:id', element:

Expense detail

}, + ], + '/expenses/7/edit', + ) + + const dateChip = await screen.findByRole('button', { name: /· Monthly$/ }) + expect( + screen.getByText(/^The next one, on 20 Nov(?: 2026)?, copies them\.$/), + ).toBeInTheDocument() + + await userEvent.click(dateChip) + const sheet = await screen.findByRole('dialog') + expect(within(sheet).getByRole('button', { name: 'Monthly' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + await userEvent.click(within(sheet).getByRole('button', { name: 'Every 2 weeks' })) + expect(screen.getByText('The next one copies them.')).toBeInTheDocument() + await userEvent.click(within(sheet).getByRole('button', { name: 'Done' })) + + await userEvent.click(screen.getByRole('button', { name: 'Save changes' })) + expect(await screen.findByText('Expense detail')).toBeInTheDocument() + const put = fetchMock.mock.calls.find(([, init]) => init?.method === 'PUT') + expect(JSON.parse(String(put?.[1]?.body)).repeat).toEqual({ unit: 'week', every: 2 }) + }) + + it('offers no repeat on an older expense of a repeat', async () => { + const older: ExpenseResponse = { + ...expense, + repeat: { unit: 'month', every: 1, nextOn: '2026-11-20T00:00:00+00:00', active: true }, + series: { latestId: 9, isLatest: false }, + } + vi.stubGlobal( + 'fetch', + vi.fn(async (path: string, init?: RequestInit) => { + const key = `${init?.method ?? 'GET'} ${path}` + if (key === 'GET /api/me') return jsonResponse(200, me) + if (key === 'GET /api/contacts') return jsonResponse(200, { totals: [], items: [] }) + if (key === 'GET /api/expenses/7') return jsonResponse(200, older) + throw new Error(`Unexpected ${key}`) + }), + ) + renderRoutes([{ path: '/expenses/:id/edit', element: }], '/expenses/7/edit') + + await userEvent.click(await screen.findByRole('button', { name: /^20 Oct/ })) + const sheet = await screen.findByRole('dialog') + expect(within(sheet).queryByRole('heading', { name: 'Repeat' })).not.toBeInTheDocument() + expect(screen.queryByText(/The next one/)).not.toBeInTheDocument() + }) + it('shows StateMessage with a way back when the expense is not found (404)', async () => { vi.stubGlobal( 'fetch', diff --git a/frontend/src/features/add/EditExpensePage.tsx b/frontend/src/features/add/EditExpensePage.tsx index 63d0a73..58afd45 100644 --- a/frontend/src/features/add/EditExpensePage.tsx +++ b/frontend/src/features/add/EditExpensePage.tsx @@ -2,6 +2,7 @@ import { useState } from 'react' import { useLingui } from '@lingui/react/macro' import { useParams } from 'react-router' import { parseIdParam } from '@/lib/parseIdParam' +import { calendarDayKey } from '@/lib/dates' import { useMe } from '@/api/auth' import { useExpense } from '@/api/expenses' import type { ExpenseResponse, MeResponse } from '@/api/types' @@ -74,6 +75,12 @@ function EditExpenseForm({ const [initialDraft] = useState(() => draftFromExpense(expense, me.id)) const [draft, setDraft] = useState(initialDraft) const guard = useLeaveGuard(draftChanged(draft, initialDraft), fallback) + const series = expense.series + const continuesRepeat = series?.isLatest === true && expense.repeat?.active === true + // The server's next date only holds while the date and the repeat stay as loaded. + const scheduleKept = + draft.occurredOn === initialDraft.occurredOn && draft.repeat === initialDraft.repeat + const nextOn = expense.repeat?.nextOn return (
@@ -82,7 +89,15 @@ function EditExpenseForm({ me={me} draft={draft} onDraftChange={setDraft} - mode={{ kind: 'edit', expenseId: expense.id }} + mode={{ + kind: 'edit', + expenseId: expense.id, + canRepeat: series === null || series.isLatest, + nextCopy: + continuesRepeat && draft.repeat !== 'off' + ? { on: scheduleKept && nextOn ? calendarDayKey(nextOn) : null } + : null, + }} onSaved={guard.leaveAfterSave} /> diff --git a/frontend/src/features/add/ExpenseForm.tsx b/frontend/src/features/add/ExpenseForm.tsx index 5ebbdd9..7e55a63 100644 --- a/frontend/src/features/add/ExpenseForm.tsx +++ b/frontend/src/features/add/ExpenseForm.tsx @@ -7,6 +7,7 @@ import { useCreateExpense, useUpdateExpense } from '@/api/expenses' import type { ExpenseRequest, MeResponse } from '@/api/types' import { CategoryTile } from '@/components/CategoryTile' import { categoryLabel } from '@/lib/categories' +import { formatShortDate } from '@/lib/dates' import { formatGrosze, formatPln } from '@/lib/money' import { getShortName, joinNames, ownDisplayName } from '@/lib/person' import { Input } from '@/components/ui/input' @@ -51,7 +52,16 @@ type ExpenseFormProps = { me: MeResponse draft: ExpenseDraft onDraftChange: (update: (draft: ExpenseDraft) => ExpenseDraft) => void - mode: { kind: 'create' } | { kind: 'edit'; expenseId: number } + mode: + | { kind: 'create' } + | { + kind: 'edit' + expenseId: number + /** False on an older expense of a repeat: only the latest can change it. */ + canRepeat: boolean + /** Editing the latest of an active repeat: the next one copies the changes. */ + nextCopy: { on: string | null } | null + } initialFocus?: 'people' | 'title' /** Rendered at the top of the scrolling area (the Expense | Payment tabs). */ top?: ReactNode @@ -337,6 +347,14 @@ export function ExpenseForm({ onDateChange={(occurredOn) => update('date', (current) => ({ ...current, occurredOn })) } + repeat={ + mode.kind === 'create' || mode.canRepeat + ? { + value: draft.repeat, + onChange: (repeat) => update('date', (current) => ({ ...current, repeat })), + } + : undefined + } dateError={errors.date} note={draft.note} onNoteChange={(note) => update('note', (current) => ({ ...current, note }))} @@ -350,9 +368,14 @@ export function ExpenseForm({ {/* While picking people the list gets all the room above the keyboard. */} {!peopleOpen && ( - {mode.kind === 'edit' && draft.others.length > 0 && ( + {mode.kind === 'edit' && (draft.others.length > 0 || mode.nextCopy) && (

- {recipients} will see your changes. + {draft.others.length > 0 && ( + + {recipients} will see your changes. + + )} + {mode.nextCopy && {nextCopyLine(mode.nextCopy.on)}}

)} {children}

} +function nextCopyLine(on: string | null): string { + if (on === null) { + return t`The next one copies them.` + } + const date = formatShortDate(on) + return t`The next one, on ${date}, copies them.` +} + function genericError(mode: 'create' | 'edit'): string { return mode === 'edit' ? t`Couldn’t save your changes. Nothing was changed and your entries are still here. Try again.` diff --git a/frontend/src/features/add/expenseDraft.test.ts b/frontend/src/features/add/expenseDraft.test.ts index 968f21a..4328acb 100644 --- a/frontend/src/features/add/expenseDraft.test.ts +++ b/frontend/src/features/add/expenseDraft.test.ts @@ -42,7 +42,7 @@ describe('draftChanged', () => { }) describe('buildExpenseRequest', () => { - it('builds the request, always sending category and split type', () => { + it('builds the request, always sending category, split type and repeat', () => { expect(buildExpenseRequest(draft(), ME)).toEqual({ ok: true, request: { @@ -54,6 +54,7 @@ describe('buildExpenseRequest', () => { splitType: 'equal', category: 'food_and_drink', description: null, + repeat: null, }, }) }) @@ -149,6 +150,8 @@ describe('draftFromExpense', () => { { payer: anna, amount: '61.43', splitValue: null }, { payer: ewa, amount: '61.43', splitValue: null }, ], + repeat: null, + series: null, } it('loads people, split and fields, and round-trips to the same request', () => { @@ -168,6 +171,29 @@ describe('draftFromExpense', () => { }) }) + it('loads the repeat only from the active latest, and always sends one', () => { + const repeat = { + unit: 'week' as const, + every: 2, + nextOn: '2026-11-03T00:00:00+00:00', + active: true, + } + const latest = { ...expense, repeat, series: { latestId: 7, isLatest: true } } + const older = { ...latest, series: { latestId: 9, isLatest: false } } + const stopped = { ...latest, repeat: { ...repeat, nextOn: null, active: false } } + + expect(draftFromExpense(latest, ME).repeat).toBe('biweekly') + expect(draftFromExpense(older, ME).repeat).toBe('off') + expect(draftFromExpense(stopped, ME).repeat).toBe('off') + + const sent = (draft: ExpenseDraft) => { + const result = buildExpenseRequest(draft, ME) + return result.ok ? result.request.repeat : undefined + } + expect(sent(draftFromExpense(latest, ME))).toEqual({ unit: 'week', every: 2 }) + expect(sent(draftFromExpense(older, ME))).toBeNull() + }) + it('keeps someone who paid but does not share out of the split, and shares as typed', () => { const loaded = draftFromExpense( { diff --git a/frontend/src/features/add/expenseDraft.ts b/frontend/src/features/add/expenseDraft.ts index 4c64ce9..21b1fa1 100644 --- a/frontend/src/features/add/expenseDraft.ts +++ b/frontend/src/features/add/expenseDraft.ts @@ -13,6 +13,7 @@ import { expenseCategories } from '@/lib/categories' import { calendarDayKey } from '@/lib/dates' import { trimDecimal } from '@/lib/decimal' import { peopleOtherThan } from '@/lib/person' +import { choiceOf, repeatOf, type RepeatChoice } from '@/lib/repeat' import { checkSplit, defaultSplit, splitDebts, type SplitDraft } from './splitModel' /** The Add expense form, as typed. The user is always in it and isn't listed in `others`. */ @@ -24,6 +25,8 @@ export type ExpenseDraft = { categoryPicked: boolean amount: string occurredOn: string + /** Only the latest expense of a repeat can change it; an older one keeps it off. */ + repeat: RepeatChoice note: string split: SplitDraft } @@ -50,6 +53,7 @@ export function emptyDraft(meId: number, occurredOn: string): ExpenseDraft { categoryPicked: false, amount: '', occurredOn, + repeat: 'off', note: '', split: defaultSplit(meId), } @@ -74,6 +78,7 @@ export function draftFromExpense(expense: ExpenseResponse, meId: number): Expens categoryPicked: true, amount: expense.amount, occurredOn: calendarDayKey(expense.occurredOn), + repeat: expense.series?.isLatest && expense.repeat?.active ? choiceOf(expense.repeat) : 'off', note: expense.description ?? '', split: { payerId: expense.payee.id, @@ -107,6 +112,7 @@ export const expenseRequestSchema = z.object({ splitType: z.enum(['exact', 'percentage', 'shares', 'equal']), category: z.enum(expenseCategories), description: z.string().nullish(), + repeat: z.object({ unit: z.enum(['week', 'month', 'year']), every: z.number() }).nullish(), }) /** Whether the user changed anything that gets saved; what other split types remember doesn't count. */ @@ -215,6 +221,8 @@ export function buildExpenseRequest(draft: ExpenseDraft, meId: number): BuildRes splitType: draft.split.type, category: draft.category, description: draft.note.trim() === '' ? null : draft.note.trim(), + // Always sent: an omitted repeat stops it. + repeat: repeatOf(draft.repeat), } const parsed = expenseRequestSchema.safeParse(candidate) if (!parsed.success) { @@ -247,6 +255,7 @@ export function fieldForPath(propertyPath: string): ExpenseField | null { case 'splitType': return 'split' case 'occurredOn': + case 'repeat': return 'date' case 'description': return 'note' diff --git a/frontend/src/features/detail/DetailParts.tsx b/frontend/src/features/detail/DetailParts.tsx index c958bbc..ab3008e 100644 --- a/frontend/src/features/detail/DetailParts.tsx +++ b/frontend/src/features/detail/DetailParts.tsx @@ -64,6 +64,7 @@ type DetailActionsProps = { deleteLabel: string confirmTitle: string confirmDescription: string + confirmNote?: ReactNode deletion: DeleteAndGoBack } @@ -74,6 +75,7 @@ export function DetailActions({ deleteLabel, confirmTitle, confirmDescription, + confirmNote, deletion, }: DetailActionsProps) { const { t } = useLingui() @@ -90,6 +92,7 @@ export function DetailActions({ onOpenChange={setConfirmOpen} title={confirmTitle} description={confirmDescription} + note={confirmNote} confirmLabel={deleteLabel} onConfirm={confirm} pending={isPending} diff --git a/frontend/src/features/detail/ExpenseDetailPage.test.tsx b/frontend/src/features/detail/ExpenseDetailPage.test.tsx index 2fe883f..b87d98f 100644 --- a/frontend/src/features/detail/ExpenseDetailPage.test.tsx +++ b/frontend/src/features/detail/ExpenseDetailPage.test.tsx @@ -142,6 +142,47 @@ describe('ExpenseDetailPage', () => { expect(screen.queryByRole('button', { name: 'Delete expense' })).not.toBeInTheDocument() }) + it('shows when the latest of a repeat comes next, and that deleting it stops the repeat', async () => { + stubDetailApi({ + 'GET /api/expenses/7': { + status: 200, + body: expenseResponse({ + repeat: { unit: 'month', every: 1, nextOn: '2026-11-20T00:00:00+00:00', active: true }, + series: { latestId: 7, isLatest: true }, + }), + }, + }) + renderExpense() + + expect(await screen.findByText('Repeats monthly · next on 20 Nov')).toBeInTheDocument() + await userEvent.click(screen.getByRole('button', { name: 'Delete expense' })) + const sheet = await screen.findByRole('dialog', { name: 'Delete “Zakupy Biedronka”?' }) + expect(within(sheet).getByText('The monthly repeat stops too.')).toBeInTheDocument() + }) + + it('links an older expense of a repeat to the latest', async () => { + stubDetailApi({ + 'GET /api/expenses/7': { + status: 200, + body: expenseResponse({ + repeat: { unit: 'week', every: 2, nextOn: null, active: false }, + series: { latestId: 9, isLatest: false }, + }), + }, + 'GET /api/expenses/9': { + status: 200, + body: expenseResponse({ id: 9, occurredOn: '2026-11-03T00:00:00+00:00' }), + }, + }) + renderExpense() + + const link = await screen.findByRole('link', { + name: 'Part of a repeat every 2 weeks · latest 3 Nov', + }) + expect(link).toHaveAttribute('href', '/expenses/9') + expect(screen.queryByText(/next on/)).not.toBeInTheDocument() + }) + it('deletes after confirming, then goes back and refreshes balances', async () => { const invalidate = vi.spyOn(QueryClient.prototype, 'invalidateQueries') const fetchMock = stubDetailApi({ diff --git a/frontend/src/features/detail/ExpenseDetailPage.tsx b/frontend/src/features/detail/ExpenseDetailPage.tsx index 54c02a1..2f5d6cb 100644 --- a/frontend/src/features/detail/ExpenseDetailPage.tsx +++ b/frontend/src/features/detail/ExpenseDetailPage.tsx @@ -1,5 +1,6 @@ import { useRef } from 'react' -import { useParams } from 'react-router' +import { Link, useParams } from 'react-router' +import { ChevronRight, Repeat } from 'lucide-react' import { Trans, useLingui } from '@lingui/react/macro' import { parseIdParam } from '@/lib/parseIdParam' import { useMe } from '@/api/auth' @@ -9,7 +10,8 @@ import type { ExpenseResponse } from '@/api/types' import { CategoryTile } from '@/components/CategoryTile' import { PersonAvatar } from '@/components/PersonAvatar' import { categoryLabel } from '@/lib/categories' -import { formatShortDate } from '@/lib/dates' +import { calendarDayKey, formatShortDate } from '@/lib/dates' +import { partOfRepeatLabel, repeatsLabel, repeatStopsLabel } from '@/lib/repeat' import { balanceTextClassName, formatMoney } from '@/lib/money' import { cn } from '@/lib/utils' import { ItemError, ItemLoading, ItemNotFound } from '@/components/ItemStates' @@ -63,6 +65,14 @@ function ExpenseDetailScreen({ id }: { id: number }) { deleteLabel={t`Delete expense`} confirmTitle={t`Delete “${expenseTitle}”?`} confirmDescription={deleteWarning(otherParticipantNames(expense, me.id))} + confirmNote={ + expense.series?.isLatest && expense.repeat?.active ? ( +

+

+ ) : undefined + } deletion={deletion} /> ) @@ -134,6 +144,7 @@ function ExpenseDetail({ expense, viewerId }: { expense: ExpenseResponse; viewer

{formatShortDate(expense.occurredOn)} · {categoryLabel(expense.category)}

+

@@ -163,3 +174,42 @@ function ExpenseDetail({ expense, viewerId }: { expense: ExpenseResponse; viewer ) } + +function RepeatLine({ expense }: { expense: ExpenseResponse }) { + const { t } = useLingui() + const { repeat, series } = expense + if (repeat === null || series === null) { + return null + } + if (!series.isLatest) { + return + } + if (!repeat.active || repeat.nextOn === null) { + return null + } + + const nextOn = formatShortDate(calendarDayKey(repeat.nextOn)) + return ( +

+

+ ) +} + +function OlderRepeatLink({ label, latestId }: { label: string; latestId: number }) { + const { t } = useLingui() + const latest = useExpense(latestId).data + const latestOn = latest ? formatShortDate(calendarDayKey(latest.occurredOn)) : null + + return ( + +