Skip to content
47 changes: 47 additions & 0 deletions frontend/src/app/ErrorPages.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Link } from 'react-router'
import { CircleAlert, RefreshCw, SearchX } from 'lucide-react'
import { Trans, useLingui } from '@lingui/react/macro'
import { BackLink } from '@/components/BackLink'
import { PageHeader } from '@/components/PageHeader'
import { StateMessage } from '@/components/StateMessage'
import { Button } from '@/components/ui/button'
import { buttonClassName } from '@/components/ui/button-variants'

export function NotFoundPage() {
const { t } = useLingui()
return (
<>
<PageHeader title={t`Not found`} leading={<BackLink to="/" label={t`Back`} />} />
<StateMessage
icon={<SearchX className="size-7.5" aria-hidden="true" />}
title={t`This page doesn’t exist`}
description={t`Check the address or go back to your contacts.`}
>
<Link to="/" className={buttonClassName({ variant: 'outline', size: 'pill' })}>
<Trans>Go to contacts</Trans>
</Link>
</StateMessage>
</>
)
}

export function RouteErrorPage() {
const { t } = useLingui()

return (
<main className="h-full overflow-y-auto">
<StateMessage
role="alert"
icon={<CircleAlert className="size-7.5" aria-hidden="true" />}
iconClassName="bg-destructive/10 text-destructive"
title={t`Something went wrong`}
description={t`Reload the page to try again.`}
>
<Button variant="outline" size="pill" onClick={() => window.location.reload()}>
<RefreshCw aria-hidden="true" />
<Trans>Reload</Trans>
</Button>
</StateMessage>
</main>
)
}
83 changes: 83 additions & 0 deletions frontend/src/app/RequireAuth.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useLocation } from 'react-router'
import { jsonResponse, renderRoutes } from '@/test/utils'
import type { LoginLocationState } from '@/features/auth/LoginPage'
import { RequireAuth } from './RequireAuth'

function LoginProbe() {
const location = useLocation()
const state = location.state as LoginLocationState
return <p data-testid="login-from">{state?.from ?? ''}</p>
}

function renderProtected(initialEntry: string) {
return renderRoutes(
[
{ path: '/login', element: <LoginProbe /> },
{
element: <RequireAuth />,
children: [
{ path: '/', element: <p>Protected home</p> },
{ path: '/add', element: <p>Add screen</p> },
],
},
],
initialEntry,
)
}

afterEach(() => {
vi.unstubAllGlobals()
})

describe('RequireAuth', () => {
it('redirects to /login with pathname, search and hash on 401', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(jsonResponse(401, { status: 401, title: 'Unauthorized' })),
)
const router = renderProtected('/add?tab=payment&contact=2#note')

expect(await screen.findByTestId('login-from')).toHaveTextContent(
'/add?tab=payment&contact=2#note',
)
expect(router.state.location.pathname).toBe('/login')
})

it('shows a retryable error instead of redirecting when /api/me fails with 500', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(jsonResponse(500, { status: 500, title: 'Internal Server Error' }))
.mockResolvedValueOnce(jsonResponse(200, { id: 1, email: 'a@example.com', name: 'Ame' }))
vi.stubGlobal('fetch', fetchMock)

const router = renderProtected('/add')

expect(await screen.findByRole('alert')).toHaveTextContent('Couldn’t reach Settle')
expect(router.state.location.pathname).toBe('/add')
expect(screen.queryByTestId('login-from')).not.toBeInTheDocument()

await userEvent.click(screen.getByRole('button', { name: 'Try again' }))

expect(await screen.findByText('Add screen')).toBeInTheDocument()
expect(fetchMock).toHaveBeenCalledTimes(2)
})

it('shows a retryable error on network failure and redirects if retry returns 401', async () => {
const fetchMock = vi
.fn()
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(jsonResponse(401, { status: 401, title: 'Unauthorized' }))
vi.stubGlobal('fetch', fetchMock)

const router = renderProtected('/add?contact=2')

expect(await screen.findByRole('alert')).toHaveTextContent('Couldn’t reach Settle')
await userEvent.click(screen.getByRole('button', { name: 'Try again' }))

await waitFor(() => expect(router.state.location.pathname).toBe('/login'))
expect(screen.getByTestId('login-from')).toHaveTextContent('/add?contact=2')
})
})
25 changes: 20 additions & 5 deletions frontend/src/app/RequireAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
import { Trans } from '@lingui/react/macro'
import { Trans, useLingui } from '@lingui/react/macro'
import { Navigate, Outlet, useLocation } from 'react-router'
import { useMe } from '@/api/auth'
import { LoadError } from '@/components/LoadError'

export function RequireAuth() {
const { data: me, isPending } = useMe()
const { t } = useLingui()
const meQuery = useMe()
const location = useLocation()

if (isPending) {
if (meQuery.isPending) {
return (
<div className="flex h-full items-center justify-center text-muted-foreground">
<Trans>Loading…</Trans>
</div>
)
}

if (!me) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />
if (!meQuery.data && meQuery.isError) {
return (
<main className="h-full overflow-y-auto">
<LoadError
title={t`Couldn’t reach Settle`}
onRetry={() => meQuery.refetch()}
isRetrying={meQuery.isFetching}
/>
</main>
)
}

if (!meQuery.data) {
const from = `${location.pathname}${location.search}${location.hash}`
return <Navigate to="/login" replace state={{ from }} />
}

return <Outlet />
Expand Down
73 changes: 73 additions & 0 deletions frontend/src/app/router.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { screen } from '@testing-library/react'
import { jsonResponse, renderRoutes } from '@/test/utils'
import { routes } from './router'

const me = { id: 1, email: 'ame@example.com', name: 'Ame' }

afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})

describe('router', () => {
it('renders a not-found screen inside AppShell for unknown routes', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, me)),
)
renderRoutes(routes, '/nope')

expect(
await screen.findByRole('heading', { name: 'This page doesn’t exist' }),
).toBeInTheDocument()
expect(screen.getByRole('navigation', { name: 'Main' })).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Go to contacts' })).toHaveAttribute('href', '/')
expect(screen.queryByText(/Hey developer/)).not.toBeInTheDocument()
})

it('redirects unknown routes to /login when signed out', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(401, { status: 401, title: 'Unauthorized' })),
)
const router = renderRoutes(routes, '/nope?x=1')

expect(await screen.findByRole('heading', { name: 'Sign in' })).toBeInTheDocument()
expect(router.state.location.pathname).toBe('/login')
})

it('keeps specific routes outside AppShell matched ahead of the catch-all', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, me)),
)
renderRoutes(routes, '/expenses/abc')

expect(
await screen.findByRole('heading', { name: 'This expense doesn’t exist' }),
).toBeInTheDocument()
expect(screen.queryByRole('navigation', { name: 'Main' })).not.toBeInTheDocument()
})

it('renders the root errorElement instead of React Router’s developer page on crash', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
function Boom(): never {
throw new Error('render failure')
}
const rootErrorElement = routes[0].errorElement
renderRoutes(
[
{
errorElement: rootErrorElement,
children: [{ path: '/boom', element: <Boom /> }],
},
],
'/boom',
)

expect(await screen.findByRole('alert')).toHaveTextContent('Something went wrong')
expect(screen.getByRole('button', { name: 'Reload' })).toBeInTheDocument()
expect(screen.queryByText(/Hey developer/)).not.toBeInTheDocument()
})
})
49 changes: 29 additions & 20 deletions frontend/src/app/router.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createBrowserRouter } from 'react-router'
import { createBrowserRouter, type RouteObject } from 'react-router'
import { AppShell } from './AppShell'
import { NotFoundPage, RouteErrorPage } from './ErrorPages'
import { RequireAuth } from './RequireAuth'
import { LoginPage } from '@/features/auth/LoginPage'
import { SignUpPage } from '@/features/auth/SignUpPage'
Expand All @@ -17,30 +18,38 @@ import { ProfilePage } from '@/features/profile/ProfilePage'
import { EditNamePage } from '@/features/profile/EditNamePage'
import { ChangePasswordPage } from '@/features/profile/ChangePasswordPage'

export const router = createBrowserRouter([
{ path: '/login', element: <LoginPage /> },
{ path: '/signup', element: <SignUpPage /> },
export const routes: RouteObject[] = [
{
element: <RequireAuth />,
errorElement: <RouteErrorPage />,
children: [
{ path: '/login', element: <LoginPage /> },
{ path: '/signup', element: <SignUpPage /> },
{
element: <AppShell />,
element: <RequireAuth />,
children: [
{ index: true, element: <ContactsPage /> },
{ path: 'activity', element: <ActivityPage /> },
{ path: 'profile', element: <ProfilePage /> },
{ path: 'contacts/:userId', element: <ContactPage /> },
{
element: <AppShell />,
children: [
{ index: true, element: <ContactsPage /> },
{ path: 'activity', element: <ActivityPage /> },
{ path: 'profile', element: <ProfilePage /> },
{ path: 'contacts/:userId', element: <ContactPage /> },
{ path: '*', element: <NotFoundPage /> },
],
},
{ path: 'contacts/new', element: <AddContactPage /> },
{ path: 'contacts/:userId/edit', element: <EditContactPage /> },
{ path: 'profile/name', element: <EditNamePage /> },
{ path: 'profile/password', element: <ChangePasswordPage /> },
{ path: 'expenses/:id', element: <ExpenseDetailPage /> },
{ path: 'transfers/:id', element: <TransferDetailPage /> },
{ path: 'add', element: <AddPage /> },
{ path: 'expenses/:id/edit', element: <EditExpensePage /> },
{ path: 'transfers/:id/edit', element: <EditTransferPage /> },
],
},
{ path: 'contacts/new', element: <AddContactPage /> },
{ path: 'contacts/:userId/edit', element: <EditContactPage /> },
{ path: 'profile/name', element: <EditNamePage /> },
{ path: 'profile/password', element: <ChangePasswordPage /> },
{ path: 'expenses/:id', element: <ExpenseDetailPage /> },
{ path: 'transfers/:id', element: <TransferDetailPage /> },
{ path: 'add', element: <AddPage /> },
{ path: 'expenses/:id/edit', element: <EditExpensePage /> },
{ path: 'transfers/:id/edit', element: <EditTransferPage /> },
],
},
])
]

export const router = createBrowserRouter(routes)
22 changes: 22 additions & 0 deletions frontend/src/features/add/EditExpensePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,28 @@ describe('EditExpensePage', () => {
description: null,
})
})

it('shows StateMessage with a way back when the expense is not found (404)', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (path: string) => {
if (path === '/api/me') return jsonResponse(200, me)
return jsonResponse(404, { status: 404, title: 'Not Found' })
}),
)
renderRoutes(
[{ path: '/expenses/:id/edit', element: <EditExpensePage /> }],
'/expenses/999999/edit',
)

expect(
await screen.findByRole('heading', { name: 'This expense doesn’t exist' }),
).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Go to activity' })).toHaveAttribute(
'href',
'/activity',
)
})
})

describe('EditExpensePage with a malformed id', () => {
Expand Down
42 changes: 42 additions & 0 deletions frontend/src/features/add/EditTransferPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,46 @@ describe('EditTransferPage', () => {
description: 'BLIK',
})
})

it('shows not found without calling the API for a malformed id', async () => {
const fetchMock = vi.fn(async (_path: string) => jsonResponse(200, me))
vi.stubGlobal('fetch', fetchMock)
renderRoutes(
[{ path: '/transfers/:id/edit', element: <EditTransferPage /> }],
'/transfers/abc/edit',
)

expect(
await screen.findByRole('heading', { name: 'This payment doesn’t exist' }),
).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Go to activity' })).toHaveAttribute(
'href',
'/activity',
)
expect(fetchMock.mock.calls.some(([path]) => String(path).startsWith('/api/transfers'))).toBe(
false,
)
})

it('shows StateMessage with a way back when the payment is not found (404)', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (path: string) => {
if (path === '/api/me') return jsonResponse(200, me)
return jsonResponse(404, { status: 404, title: 'Not Found' })
}),
)
renderRoutes(
[{ path: '/transfers/:id/edit', element: <EditTransferPage /> }],
'/transfers/999999/edit',
)

expect(
await screen.findByRole('heading', { name: 'This payment doesn’t exist' }),
).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Go to activity' })).toHaveAttribute(
'href',
'/activity',
)
})
})
Loading