From ee1f837a207761f35686705dfe7d28cfb0fe7760 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Tue, 10 Nov 2026 12:43:55 +0100 Subject: [PATCH] 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 --- admin/src/App.tsx | 2 + admin/src/lib/api.ts | 19 ++++++ admin/src/pages/ListPage.tsx | 3 +- admin/src/tabs/SentTab.test.tsx | 113 ++++++++++++++++++++++++++++++++ admin/src/tabs/SentTab.tsx | 81 +++++++++++++++++++++++ admin/src/test/fakeApi.ts | 10 ++- 6 files changed, 225 insertions(+), 3 deletions(-) create mode 100644 admin/src/tabs/SentTab.test.tsx create mode 100644 admin/src/tabs/SentTab.tsx diff --git a/admin/src/App.tsx b/admin/src/App.tsx index e832cba..91339ba 100644 --- a/admin/src/App.tsx +++ b/admin/src/App.tsx @@ -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() { } /> } /> } /> + } /> } /> diff --git a/admin/src/lib/api.ts b/admin/src/lib/api.ts index 0f25352..5f1d4a2 100644 --- a/admin/src/lib/api.ts +++ b/admin/src/lib/api.ts @@ -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('POST', `/held/${id}/approve`), discard: (id: number) => request('DELETE', `/held/${id}`), }, + posts: { + list: (listId: number) => request('GET', `/lists/${listId}/posts`), + }, queue: { get: () => request('GET', '/queue'), discard: (id: number) => request('DELETE', `/queue/${id}`), diff --git a/admin/src/pages/ListPage.tsx b/admin/src/pages/ListPage.tsx index 4d65251..77ff633 100644 --- a/admin/src/pages/ListPage.tsx +++ b/admin/src/pages/ListPage.tsx @@ -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 && {heldCount}} Archive + Sent diff --git a/admin/src/tabs/SentTab.test.tsx b/admin/src/tabs/SentTab.test.tsx new file mode 100644 index 0000000..35fc02f --- /dev/null +++ b/admin/src/tabs/SentTab.test.tsx @@ -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 => ({ + 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: '' })]) + expect(await screen.findByText('')).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') + }) +}) diff --git a/admin/src/tabs/SentTab.tsx b/admin/src/tabs/SentTab.tsx new file mode 100644 index 0000000..9426b0e --- /dev/null +++ b/admin/src/tabs/SentTab.tsx @@ -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() + 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 ( +
+

Sent posts

+ {posts.isPending &&

Loading…

} + {posts.isError &&

{posts.error.message}

} + {posts.data && items.length === 0 && ( +

Nothing has been sent to this list yet.

+ )} + {items.length > 0 && ( + + + + Subject + Date + Sent + Recipients + Pending + Failed + Dropped + + + + {items.map((p) => ( + + {p.subject || '(no subject)'} + {formatDate(p.created_at)} + + + + {p.recipients} + {p.pending} + {p.failed} + {p.dropped} + + ))} + +
+ )} +
+ ) +} + +function Progress({ post }: { post: Post }) { + if (post.recipients === 0) return No recipients + const pct = Math.round((100 * post.sent) / post.recipients) + return ( +
+
+
+
+ + {post.sent} of {post.recipients} + +
+ ) +} diff --git a/admin/src/test/fakeApi.ts b/admin/src/test/fakeApi.ts index c8bbfaf..b18176b 100644 --- a/admin/src/test/fakeApi.ts +++ b/admin/src/test/fakeApi.ts @@ -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 archive: Record queue: QueueItem[] + posts: Record /** 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 { - 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 { @@ -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])