feat(admin): a Sent tab with the posts of a list and their progress

- route /lists/:id/sent and a Sent tab on the list page
- a table of posts (subject, date, sent of recipients with a progress
  bar, recipients, pending, failed, dropped) and an empty state; a post
  with no recipients shows no bar
- refreshes every 5 seconds while any post has pending deliveries, and
  stops when none has
- api.posts.list, the Post type and the fake API route; tests
This commit is contained in:
tgiachi 2026-11-10 12:43:55 +01:00
commit ee1f837a20
6 changed files with 225 additions and 3 deletions

View file

@ -7,6 +7,7 @@ import { NotFoundPage } from '@/pages/NotFoundPage'
import { ArchiveTab } from '@/tabs/ArchiveTab'
import { HeldTab } from '@/tabs/HeldTab'
import { MembersTab } from '@/tabs/MembersTab'
import { SentTab } from '@/tabs/SentTab'
import { SettingsTab } from '@/tabs/SettingsTab'
import { QueuePage } from '@/pages/QueuePage'
import { Toaster } from '@/components/ui/sonner'
@ -25,6 +26,7 @@ export function App() {
<Route path="members" element={<MembersTab />} />
<Route path="held" element={<HeldTab />} />
<Route path="archive" element={<ArchiveTab />} />
<Route path="sent" element={<SentTab />} />
</Route>
<Route path="*" element={<NotFoundPage />} />
</Route>

View file

@ -79,6 +79,22 @@ export interface Queue {
items: QueueItem[]
}
/** A post queued to a list, with how far its delivery got. */
export interface Post {
id: number
message_id: string
subject: string
created_at: string
/** Deliveries queued: the members when it was posted. */
recipients: number
sent: number
failed: number
/** The mailbox does not exist, or the delivery was discarded. */
dropped: number
/** Still in the queue. */
pending: number
}
export class ApiError extends Error {
readonly status: number
constructor(status: number, message: string) {
@ -164,6 +180,9 @@ export const api = {
approve: (id: number) => request<void>('POST', `/held/${id}/approve`),
discard: (id: number) => request<void>('DELETE', `/held/${id}`),
},
posts: {
list: (listId: number) => request<Post[]>('GET', `/lists/${listId}/posts`),
},
queue: {
get: () => request<Queue>('GET', '/queue'),
discard: (id: number) => request<void>('DELETE', `/queue/${id}`),

View file

@ -4,7 +4,7 @@ import { Badge } from '@/components/ui/badge'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { api } from '@/lib/api'
const tabs = ['settings', 'members', 'held', 'archive'] as const
const tabs = ['settings', 'members', 'held', 'archive', 'sent'] as const
export function ListPage() {
const params = useParams()
@ -42,6 +42,7 @@ export function ListPage() {
{heldCount > 0 && <Badge className="ml-1">{heldCount}</Badge>}
</TabsTrigger>
<TabsTrigger value="archive">Archive</TabsTrigger>
<TabsTrigger value="sent">Sent</TabsTrigger>
</TabsList>
</Tabs>
<Outlet context={list.data} />

View file

@ -0,0 +1,113 @@
import { act, screen, within } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Post } from '@/lib/api'
import { aList, installFakeApi, newState } from '@/test/fakeApi'
import { renderApp } from '@/test/render'
const post = (id: number, over: Partial<Post> = {}): Post => ({
id,
message_id: `<${id}@example.org>`,
subject: `Issue ${id}`,
created_at: '2030-01-02T03:04:05Z',
recipients: 4,
sent: 4,
failed: 0,
dropped: 0,
pending: 0,
...over,
})
async function setup(posts: Post[]) {
const state = installFakeApi(newState({ lists: [aList({ id: 1 })], posts: { 1: posts } }))
const ctx = renderApp('/lists/1/sent', { token: 'good' })
await screen.findByRole('heading', { name: /sent posts/i, level: 2 })
return { ...ctx, state }
}
const postCalls = (calls: string[]) => calls.filter((c) => c === 'GET /lists/1/posts').length
afterEach(() => vi.useRealTimers())
describe('sent tab', () => {
it('is a tab of the list page', async () => {
installFakeApi(newState({ lists: [aList({ id: 1 })], posts: { 1: [post(1)] } }))
const { user } = renderApp('/lists/1', { token: 'good' })
await user.click(await screen.findByRole('tab', { name: /^sent$/i }))
expect(await screen.findByRole('heading', { name: /sent posts/i, level: 2 })).toBeInTheDocument()
expect(await screen.findByText('Issue 1')).toBeInTheDocument()
expect(screen.getByRole('tab', { name: /^sent$/i })).toHaveAttribute('aria-selected', 'true')
})
it('says when nothing was sent yet', async () => {
await setup([])
expect(await screen.findByText(/nothing has been sent to this list yet/i)).toBeInTheDocument()
expect(screen.queryByRole('table')).not.toBeInTheDocument()
})
it('shows each post with its counts and progress', async () => {
await setup([
post(2, { subject: '', recipients: 10, sent: 6, failed: 1, dropped: 1, pending: 2 }),
post(1),
])
const row = (await screen.findByText('(no subject)')).closest('tr')!
expect(within(row).getByText('2030-01-02 03:04 UTC')).toBeInTheDocument()
const bar = within(row).getByRole('progressbar')
expect(bar).toHaveAttribute('aria-valuenow', '6')
expect(bar).toHaveAttribute('aria-valuemax', '10')
expect(within(row).getByText('6 of 10')).toBeInTheDocument()
const cells = within(row).getAllByRole('cell').map((c) => c.textContent)
expect(cells.slice(3)).toEqual(['10', '2', '1', '1'])
const headers = screen.getAllByRole('columnheader').map((h) => h.textContent)
expect(headers).toEqual(['Subject', 'Date', 'Sent', 'Recipients', 'Pending', 'Failed', 'Dropped'])
const done = screen.getByText('Issue 1').closest('tr')!
expect(within(done).getByRole('progressbar')).toHaveAttribute('aria-valuenow', '4')
const rows = screen.getAllByRole('row').slice(1).map((r) => r.textContent ?? '')
expect(rows[0]).toContain('(no subject)') // the order of the server: newest first
})
it('shows a post nobody received without a progress bar', async () => {
await setup([post(1, { recipients: 0, sent: 0 })])
const row = (await screen.findByText('Issue 1')).closest('tr')!
expect(within(row).queryByRole('progressbar')).not.toBeInTheDocument()
expect(within(row).getByText(/no recipients/i)).toBeInTheDocument()
})
it('shows subjects as text', async () => {
await setup([post(1, { subject: '<img src=x onerror="alert(1)">' })])
expect(await screen.findByText('<img src=x onerror="alert(1)">')).toBeInTheDocument()
expect(document.querySelector('img[src="x"]')).toBeNull()
})
it('refreshes every few seconds while a post is being sent', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
const { state } = await setup([post(1, { sent: 1, pending: 3 })])
await screen.findByText('1 of 4')
state.posts[1] = [post(1)]
await act(async () => {
await vi.advanceTimersByTimeAsync(6000)
})
expect(await screen.findByText('4 of 4')).toBeInTheDocument()
// Everything is sent: no more polling.
const before = postCalls(state.calls)
await act(async () => {
await vi.advanceTimersByTimeAsync(12000)
})
expect(postCalls(state.calls)).toBe(before)
})
it('does not refresh when nothing is pending', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
const { state } = await setup([post(1)])
await screen.findByText('4 of 4')
await act(async () => {
await vi.advanceTimersByTimeAsync(12000)
})
expect(postCalls(state.calls)).toBe(1)
})
it('shows a loading error', async () => {
installFakeApi(newState({ lists: [aList({ id: 1 })], fail: { 'GET /lists/1/posts': { status: 500, error: 'database is locked' } } }))
renderApp('/lists/1/sent', { token: 'good' })
expect(await screen.findByRole('alert')).toHaveTextContent('database is locked')
})
})

View file

@ -0,0 +1,81 @@
import { useQuery } from '@tanstack/react-query'
import { useOutletContext } from 'react-router'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { api, type List, type Post } from '@/lib/api'
import { formatDate } from '@/lib/format'
/** How often the tab reloads by itself while a post is still being sent. */
export const REFRESH_MS = 5000
export function SentTab() {
const list = useOutletContext<List>()
const posts = useQuery({
queryKey: ['posts', list.id],
queryFn: () => api.posts.list(list.id),
refetchInterval: (q) => (q.state.data?.some((p) => p.pending > 0) ? REFRESH_MS : false),
})
const items = posts.data ?? []
return (
<div className="space-y-4">
<h2 className="text-lg font-semibold">Sent posts</h2>
{posts.isPending && <p className="text-muted-foreground">Loading…</p>}
{posts.isError && <p role="alert" className="text-destructive">{posts.error.message}</p>}
{posts.data && items.length === 0 && (
<p className="text-muted-foreground">Nothing has been sent to this list yet.</p>
)}
{items.length > 0 && (
<Table>
<TableHeader>
<TableRow>
<TableHead>Subject</TableHead>
<TableHead>Date</TableHead>
<TableHead>Sent</TableHead>
<TableHead>Recipients</TableHead>
<TableHead>Pending</TableHead>
<TableHead>Failed</TableHead>
<TableHead>Dropped</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{items.map((p) => (
<TableRow key={p.id}>
<TableCell className="max-w-xs whitespace-normal font-medium">{p.subject || '(no subject)'}</TableCell>
<TableCell>{formatDate(p.created_at)}</TableCell>
<TableCell>
<Progress post={p} />
</TableCell>
<TableCell>{p.recipients}</TableCell>
<TableCell>{p.pending}</TableCell>
<TableCell>{p.failed}</TableCell>
<TableCell>{p.dropped}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
)
}
function Progress({ post }: { post: Post }) {
if (post.recipients === 0) return <span className="text-muted-foreground">No recipients</span>
const pct = Math.round((100 * post.sent) / post.recipients)
return (
<div className="flex items-center gap-2">
<div
role="progressbar"
aria-label={`Sent to ${post.sent} of ${post.recipients}`}
aria-valuemin={0}
aria-valuemax={post.recipients}
aria-valuenow={post.sent}
className="h-2 w-24 overflow-hidden rounded-full bg-muted"
>
<div className="h-full bg-primary" style={{ width: `${pct}%` }} />
</div>
<span className="text-sm text-muted-foreground">
{post.sent} of {post.recipients}
</span>
</div>
)
}

View file

@ -1,6 +1,6 @@
// An in-memory stand-in for the Parsimony API, used by component tests.
import { vi } from 'vitest'
import type { Held, List, Member, Message, QueueItem } from '@/lib/api'
import type { Held, List, Member, Message, Post, QueueItem } from '@/lib/api'
export interface FakeState {
token: string
@ -9,6 +9,7 @@ export interface FakeState {
held: Record<number, Held[]>
archive: Record<number, Message[]>
queue: QueueItem[]
posts: Record<number, Post[]>
/** Like the server, the queue listing is capped. */
queueLimit: number
/** Content types seen on archive imports. */
@ -23,7 +24,7 @@ export interface FakeState {
}
export function newState(overrides: Partial<FakeState> = {}): FakeState {
return { token: 'good', lists: [], members: {}, held: {}, archive: {}, queue: [], queueLimit: 100, importTypes: [], nextId: 100, calls: [], fail: {}, ...overrides }
return { token: 'good', lists: [], members: {}, held: {}, archive: {}, queue: [], posts: {}, queueLimit: 100, importTypes: [], nextId: 100, calls: [], fail: {}, ...overrides }
}
export function aList(over: Partial<List> = {}): List {
@ -125,6 +126,11 @@ export function installFakeApi(state: FakeState) {
state.members[id] = before.filter((x) => x.address !== addr)
return json(204)
}
if ((m = path.match(/^\/lists\/(\d+)\/posts$/)) && method === 'GET') {
const id = Number(m[1])
if (!state.lists.some((l) => l.id === id)) return err(404, 'not found')
return json(200, state.posts[id] ?? [])
}
if ((m = path.match(/^\/lists\/(\d+)\/held$/)) && method === 'GET') return json(200, state.held[Number(m[1])] ?? [])
if ((m = path.match(/^\/held\/(\d+)(\/approve)?$/))) {
const id = Number(m[1])