Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -65,6 +72,7 @@ export type ExpenseRequest = {
splitType?: SplitType
category?: ExpenseCategory
description?: string | null
repeat?: Repeat | null
}

export type ExpenseDebtResponse = {
Expand All @@ -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 = {
Expand Down Expand Up @@ -138,6 +158,7 @@ export type ActivityItem = {
/** Transfers only. */
payer: PersonRef | null
category: ExpenseCategory | null
recurring: boolean
}

export type ContactRequest = {
Expand Down
7 changes: 6 additions & 1 deletion frontend/src/components/ConfirmSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -35,6 +36,7 @@ export function ConfirmSheet({
onOpenChange,
title,
description,
note,
confirmLabel,
onConfirm,
cancelLabel,
Expand All @@ -48,7 +50,10 @@ export function ConfirmSheet({
<SheetContent>
<SheetHeader className="pt-3">
<SheetTitle className="break-words">{title}</SheetTitle>
<SheetDescription className="leading-[1.45]">{description}</SheetDescription>
<SheetDescription className="leading-[1.45]">
{description}
{note}
</SheetDescription>
</SheetHeader>
<SheetFooter className="pb-6">
<Button
Expand Down
9 changes: 9 additions & 0 deletions frontend/src/features/activity/ActivityRows.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ describe('ExpenseRow', () => {
expect(label.parentElement).toHaveTextContent('zł 1,234.50')
})

it('marks an expense that is part of a repeat', () => {
renderRow(<ExpenseRow item={expenseItem({ recurring: true })} viewerId={viewer.id} />)
expect(screen.getByRole('img', { name: 'Repeats' })).toBeInTheDocument()
cleanup()

renderRow(<ExpenseRow item={expenseItem()} viewerId={viewer.id} />)
expect(screen.queryByRole('img', { name: 'Repeats' })).not.toBeInTheDocument()
})

it('shows what the viewer borrowed, unsigned, with the payer named', () => {
renderRow(
<ExpenseRow
Expand Down
13 changes: 11 additions & 2 deletions frontend/src/features/activity/ActivityRows.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Link } from 'react-router'
import { Trans, useLingui } from '@lingui/react/macro'
import { Banknote } from 'lucide-react'
import { Banknote, Repeat } from 'lucide-react'
import type { ActivityItem } from '@/api/types'
import { CategoryTile } from '@/components/CategoryTile'
import { PersonAvatar } from '@/components/PersonAvatar'
Expand Down Expand Up @@ -51,7 +51,16 @@ export function ExpenseRow({
<PersonAvatar id={payee.id} name={payee.displayName} />
)}
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate">{item.title}</span>{' '}
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate">{item.title}</span>
{item.recurring && (
<Repeat
role="img"
aria-label={t`Repeats`}
className="size-3.5 shrink-0 text-muted-foreground"
/>
)}
</span>{' '}
<span className="truncate text-[13px] text-muted-foreground">
{showDate ? t`${date} · ${subline}` : subline}
</span>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/features/add/AddPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ describe('AddPage', () => {
splitType: 'equal',
category: 'food_and_drink',
description: null,
repeat: null,
})
})

Expand Down
16 changes: 12 additions & 4 deletions frontend/src/features/add/DateNoteFields.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { useState, type RefObject } from 'react'
import { Textarea } from '@/components/ui/input'
import { flushSync } from 'react-dom'
import { Trans } from '@lingui/react/macro'
import { Calendar, FileText } from 'lucide-react'
import { Trans, useLingui } from '@lingui/react/macro'
import { Calendar, FileText, Repeat } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { formatDateLabel } from '@/lib/dates'
import { repeatChoiceLabel, type RepeatChoice } from '@/lib/repeat'
import { DateSheet } from './DateSheet'
import { FieldError } from '@/components/FieldError'

type DateNoteFieldsProps = {
idPrefix: string
occurredOn: string
onDateChange: (occurredOn: string) => void
repeat?: { value: RepeatChoice; onChange: (repeat: RepeatChoice) => void }
dateError?: string
note: string
onNoteChange: (note: string) => void
Expand All @@ -25,23 +27,28 @@ export function DateNoteFields({
idPrefix,
occurredOn,
onDateChange,
repeat,
dateError,
note,
onNoteChange,
noteError,
noteRef,
notePlaceholder,
}: DateNoteFieldsProps) {
const { t } = useLingui()
const [dateOpen, setDateOpen] = useState(false)
const [noteOpen, setNoteOpen] = useState(note !== '')
const noteId = `${idPrefix}-note`
const repeats = repeat !== undefined && repeat.value !== 'off'
const dateLabel = formatDateLabel(occurredOn)
const frequency = repeats ? repeatChoiceLabel(repeat.value) : ''

return (
<>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="pill" onClick={() => setDateOpen(true)}>
<Calendar aria-hidden="true" />
{formatDateLabel(occurredOn)}
{repeats ? <Repeat aria-hidden="true" /> : <Calendar aria-hidden="true" />}
{repeats ? t`${dateLabel} · ${frequency}` : dateLabel}
</Button>
{!noteOpen && (
<Button
Expand Down Expand Up @@ -90,6 +97,7 @@ export function DateNoteFields({
onOpenChange={setDateOpen}
value={occurredOn}
onChange={onDateChange}
repeat={repeat}
/>
</>
)
Expand Down
70 changes: 51 additions & 19 deletions frontend/src/features/add/DateSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,23 @@ import {
toIsoDate,
} from '@/lib/dates'
import { cn } from '@/lib/utils'
import { repeatChoiceLabel, repeatChoices, type RepeatChoice } from '@/lib/repeat'
import { Button } from '@/components/ui/button'

type DateSheetProps = {
open: boolean
onOpenChange: (open: boolean) => void
value: string
onChange: (isoDate: string) => void
/** Adds the repeat choices; the sheet then stays open until Done. */
repeat?: { value: RepeatChoice; onChange: (repeat: RepeatChoice) => void }
}

/**
* Today / Yesterday shortcuts and a month grid. Future dates are allowed; picking one keeps
* the sheet open to say it counts towards balances straight away.
*/
export function DateSheet({ open, onOpenChange, value, onChange }: DateSheetProps) {
export function DateSheet({ open, onOpenChange, value, onChange, repeat }: DateSheetProps) {
const { t } = useLingui()
const today = todayIso()
const [month, setMonth] = useState(() => startOfMonth(value))
Expand All @@ -42,7 +45,8 @@ export function DateSheet({ open, onOpenChange, value, onChange }: DateSheetProp

function pick(isoDate: string) {
onChange(isoDate)
if (isoDate <= today) {
setMonth(startOfMonth(isoDate))
if (isoDate <= today && !repeat) {
onOpenChange(false)
}
}
Expand Down Expand Up @@ -147,31 +151,59 @@ export function DateSheet({ open, onOpenChange, value, onChange }: DateSheetProp
})}
</div>
{isFuture && (
<>
<p role="status" className="flex items-start gap-2 text-[13px] text-foreground/80">
<Info className="mt-px size-4 shrink-0" aria-hidden="true" />
<span>
<Trans>
{futureDate} is in the future. It still counts towards your balances straight
away.
</Trans>
</span>
</p>
<button
type="button"
onClick={() => onOpenChange(false)}
className="h-12 rounded-full bg-primary text-base font-semibold text-primary-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
<p role="status" className="flex items-start gap-2 text-[13px] text-foreground/80">
<Info className="mt-px size-4 shrink-0" aria-hidden="true" />
<span>
<Trans>
{futureDate} is in the future. It still counts towards your balances straight
away.
</Trans>
</span>
</p>
)}
{repeat && (
<div className="flex flex-col gap-2 border-t pt-3">
<h3 id="date-sheet-repeat" className="text-sm font-medium">
<Trans>Repeat</Trans>
</h3>
<div
role="group"
aria-labelledby="date-sheet-repeat"
className="flex flex-wrap gap-2"
>
<Trans>Done</Trans>
</button>
</>
{repeatChoices.map((choice) => (
<Button
key={choice}
variant="outline"
size="pill"
aria-pressed={repeat.value === choice}
onClick={() => repeat.onChange(choice)}
className={pressedRepeatClassName}
>
{repeatChoiceLabel(choice)}
</Button>
))}
</div>
</div>
)}
{(isFuture || repeat) && (
<button
type="button"
onClick={() => onOpenChange(false)}
className="h-12 shrink-0 rounded-full bg-primary text-base font-semibold text-primary-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none"
>
<Trans>Done</Trans>
</button>
)}
</div>
</SheetContent>
</Sheet>
)
}

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`
}
Expand Down
75 changes: 74 additions & 1 deletion frontend/src/features/add/EditExpensePage.test.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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(() => {
Expand Down Expand Up @@ -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: <EditExpensePage /> },
{ path: '/expenses/:id', element: <p>Expense detail</p> },
],
'/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: <EditExpensePage /> }], '/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',
Expand Down
Loading