diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index ce00209..27a54ef 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -56,6 +56,13 @@ export type ExpenseDebtRequest = { value?: string | null } +export type RepeatUnit = 'week' | 'month' | 'year' + +export type Repeat = { + unit: RepeatUnit + every: number +} + export type ExpenseRequest = { title: string amount: string @@ -65,6 +72,7 @@ export type ExpenseRequest = { splitType?: SplitType category?: ExpenseCategory description?: string | null + repeat?: Repeat | null } export type ExpenseDebtResponse = { @@ -84,6 +92,18 @@ export type ExpenseResponse = { splitType: SplitType category: ExpenseCategory debts: ExpenseDebtResponse[] + repeat: RepeatResponse | null + series: SeriesResponse | null +} + +export type RepeatResponse = Repeat & { + nextOn: string | null + active: boolean +} + +export type SeriesResponse = { + latestId: number + isLatest: boolean } export type CommentRequest = { @@ -138,6 +158,7 @@ export type ActivityItem = { /** Transfers only. */ payer: PersonRef | null category: ExpenseCategory | null + recurring: boolean } export type ContactRequest = { diff --git a/frontend/src/components/ConfirmSheet.tsx b/frontend/src/components/ConfirmSheet.tsx index 096d632..a555300 100644 --- a/frontend/src/components/ConfirmSheet.tsx +++ b/frontend/src/components/ConfirmSheet.tsx @@ -19,6 +19,7 @@ type ConfirmSheetProps = { onOpenChange: (open: boolean) => void title: string description: string + note?: ReactNode /** The destructive action: "Delete expense", "Discard". */ confirmLabel: string onConfirm: () => void @@ -35,6 +36,7 @@ export function ConfirmSheet({ onOpenChange, title, description, + note, confirmLabel, onConfirm, cancelLabel, @@ -48,7 +50,10 @@ export function ConfirmSheet({ {title} - {description} + + {description} + {note} + {!noteOpen && ( - + {repeatChoices.map((choice) => ( + + ))} + + + )} + {(isFuture || repeat) && ( + )} @@ -172,6 +201,9 @@ export function DateSheet({ open, onOpenChange, value, onChange }: DateSheetProp ) } +const pressedRepeatClassName = + 'aria-pressed:border-primary aria-pressed:bg-primary aria-pressed:font-semibold aria-pressed:text-primary-foreground aria-pressed:hover:bg-primary aria-pressed:active:bg-primary' + function startOfMonth(isoDate: string): string { return `${isoDate.slice(0, 7)}-01` } diff --git a/frontend/src/features/add/EditExpensePage.test.tsx b/frontend/src/features/add/EditExpensePage.test.tsx index ba524da..cc320d8 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,80 @@ 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: 'Yesterday' })) + expect(sheet).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..91f9a48 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 { continuesRepeat } from '@/lib/repeat' import { useMe } from '@/api/auth' import { useExpense } from '@/api/expenses' import type { ExpenseResponse, MeResponse } from '@/api/types' @@ -74,6 +75,11 @@ 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 + // 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 +88,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(expense) && draft.repeat !== 'off' + ? { on: scheduleKept && nextOn ? nextOn : null } + : null, + }} onSaved={guard.leaveAfterSave} /> diff --git a/frontend/src/features/add/ExpenseForm.tsx b/frontend/src/features/add/ExpenseForm.tsx index 5ebbdd9..6dc0591 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,14 @@ 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 + canRepeat: boolean + nextCopy: { on: string | null } | null + } initialFocus?: 'people' | 'title' /** Rendered at the top of the scrolling area (the Expense | Payment tabs). */ top?: ReactNode @@ -337,6 +345,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 +366,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..47c9870 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, continuesRepeat, 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: continuesRepeat(expense) ? 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,7 @@ export function buildExpenseRequest(draft: ExpenseDraft, meId: number): BuildRes splitType: draft.split.type, category: draft.category, description: draft.note.trim() === '' ? null : draft.note.trim(), + repeat: repeatOf(draft.repeat), } const parsed = expenseRequestSchema.safeParse(candidate) if (!parsed.success) { @@ -247,6 +254,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..2012db3 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' @@ -10,6 +11,7 @@ import { CategoryTile } from '@/components/CategoryTile' import { PersonAvatar } from '@/components/PersonAvatar' import { categoryLabel } from '@/lib/categories' import { formatShortDate } from '@/lib/dates' +import { continuesRepeat, partOfRepeatLabel, repeatsLabel, repeatStopsLabel } from '@/lib/repeat' import { balanceTextClassName, formatMoney } from '@/lib/money' import { cn } from '@/lib/utils' import { ItemError, ItemLoading, ItemNotFound } from '@/components/ItemStates' @@ -33,7 +35,7 @@ export function ExpenseDetailPage() { ) : ( - + ) } @@ -63,6 +65,14 @@ function ExpenseDetailScreen({ id }: { id: number }) { deleteLabel={t`Delete expense`} confirmTitle={t`Delete “${expenseTitle}”?`} confirmDescription={deleteWarning(otherParticipantNames(expense, me.id))} + confirmNote={ + continuesRepeat(expense) && expense.repeat ? ( + + + ) : undefined + } deletion={deletion} /> ) @@ -134,6 +144,7 @@ function ExpenseDetail({ expense, viewerId }: { expense: ExpenseResponse; viewer

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

+

@@ -163,3 +174,43 @@ 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 label = repeatsLabel(repeat) + const nextOn = formatShortDate(repeat.nextOn) + return ( +

+

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