Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Page through the dashboard and search all of it
Claude544b9e4b40d3
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 4e3165e..dabd563 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -1378,6 +1378,16 @@ test("a signer who declines is told the decline was recorded, not that the linkconst card = page.getByRole("link").filter({ hasText: "Terms to decline" });await expect(card).toContainText(senderLabel);++ // Enter searches every envelope, the sender's address included.+ const search = page.getByRole("searchbox", {+ name: "Search by title or email...",+ });++ await search.fill(memberEmail);+ await search.press("Enter");+ await expect(page).toHaveURL(/\/dashboard\?view=all&q=/);+ await expect(card).toBeVisible();await card.click();await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}$`));await expect(page.getByText(`Sent by ${senderLabel}`)).toBeVisible();diff --git a/src/app/(app)/dashboard/page.tsx b/src/app/(app)/dashboard/page.tsxindex df73f55..3ea7c77 100644--- a/src/app/(app)/dashboard/page.tsx+++ b/src/app/(app)/dashboard/page.tsx@@ -5,43 +5,108 @@ import { getDb } from "@/lib/db/connection";import {listAllEnvelopesForAdmin,listEnvelopesForUser,+ type DashboardEnvelopePage,} from "@/lib/envelopes";+/** Envelopes on one page of the dashboard. */+const DASHBOARD_PAGE_SIZE = 48;+type DashboardPageProps = {searchParams: Promise<Record<string, string | string[] | undefined>>;};+function firstValue(value: string | string[] | undefined): string {+ return (Array.isArray(value) ? value[0] : value) ?? "";+}++function buildDashboardHref({+ page,+ search,+ showAll,+}: {+ page: number;+ search: string;+ showAll: boolean;+}): string {+ const params = new URLSearchParams();++ if (showAll) {+ params.set("view", "all");+ }++ if (search) {+ params.set("q", search);+ }++ if (page > 1) {+ params.set("page", String(page));+ }++ const query = params.toString();++ return query ? `/dashboard?${query}` : "/dashboard";+}+export default async function DashboardPage({searchParams,}: DashboardPageProps) {const session = await getAuthSession();const database = getDb();- const { view } = await searchParams;- let envelopes: Awaited<ReturnType<typeof listEnvelopesForUser>> | undefined;+ const params = await searchParams;+ const view = firstValue(params.view);+ const search = firstValue(params.q).trim().slice(0, 160);+ const requestedPage = Number.parseInt(firstValue(params.page), 10);+ const page =+ Number.isSafeInteger(requestedPage) && requestedPage > 1+ ? requestedPage+ : 1;+ let result: DashboardEnvelopePage | undefined;let initialState: "default" | "empty" | "error" = "error";let isAdmin = false;+ let showAll = false;try {isAdmin = session ? await isAdminUser(session.user.id, database) : false;// An administrator can see every envelope in the install, not only// their own.- const showAll = isAdmin && view === "all";+ showAll = isAdmin && view === "all";++ const filters = {+ limit: DASHBOARD_PAGE_SIZE,+ page,+ ...(search ? { search } : {}),+ };- envelopes = !session- ? []+ result = !session+ ? { envelopes: [], hasMore: false }: showAll- ? await listAllEnvelopesForAdmin({}, database)- : await listEnvelopesForUser(session.user.id, {}, database);- initialState = envelopes.length === 0 ? "empty" : "default";+ ? await listAllEnvelopesForAdmin(filters, database)+ : await listEnvelopesForUser(session.user.id, filters, database);+ // Nothing at all yet, as opposed to nothing that matches or nothing+ // on this page.+ initialState =+ result.envelopes.length === 0 && !search && page === 1+ ? "empty"+ : "default";} catch {initialState = "error";}return (<DashboardShell- envelopes={envelopes}+ envelopes={result?.envelopes}+ initialSearch={search}initialState={initialState}- view={isAdmin ? (view === "all" ? "all" : "mine") : undefined}+ pagination={{+ newerHref:+ page > 1+ ? buildDashboardHref({ page: page - 1, search, showAll })+ : undefined,+ olderHref: result?.hasMore+ ? buildDashboardHref({ page: page + 1, search, showAll })+ : undefined,+ }}+ view={isAdmin ? (showAll ? "all" : "mine") : undefined}/>);}diff --git a/src/app/api/envelopes/[id]/thumbnail/route.ts b/src/app/api/envelopes/[id]/thumbnail/route.tsindex a648a24..ba0f4f4 100644--- a/src/app/api/envelopes/[id]/thumbnail/route.ts+++ b/src/app/api/envelopes/[id]/thumbnail/route.ts@@ -39,8 +39,8 @@ const privateNoStore = { "cache-control": "private, no-store" };const privateRevalidate = { "cache-control": "private, no-cache" };// The picture of a document's first page that the dashboard shows. The-// account that owns the envelope can read and write it; an administrator,-// who sees every envelope, can read it.+// account that owns the envelope can read and write it, and so can an+// administrator, who sees every envelope.export async function GET(request: Request,context: EnvelopeThumbnailRouteContext,@@ -55,8 +55,7 @@ export async function GET(const { id } = await context.params;try {- // Its sender's, or any envelope for an administrator. Saving a picture- // (POST) stays with the sender.+ // Its sender's, or any envelope for an administrator.const access = await resolveEnvelopeViewerAccess(session.user.id,id,@@ -165,9 +164,20 @@ export async function PUT();}- await saveEnvelopeThumbnailForUser(session.user.id, id, body, {- database: getDb(),- });+ // An administrator's browser draws a missing picture too, and keeps it+ // for everyone, so it is not drawn again on every visit.+ const access = await resolveEnvelopeViewerAccess(+ session.user.id,+ id,+ getDb(),+ );++ await saveEnvelopeThumbnailForUser(+ access?.ownerUserId ?? session.user.id,+ id,+ body,+ { database: getDb() },+ );return new Response(null, { headers: privateNoStore, status: 204 });} catch (error) {diff --git a/src/components/dashboard/dashboard-documents-surface.tsx b/src/components/dashboard/dashboard-documents-surface.tsxindex b73c8d9..5bcbe31 100644--- a/src/components/dashboard/dashboard-documents-surface.tsx+++ b/src/components/dashboard/dashboard-documents-surface.tsx@@ -1,6 +1,6 @@import { PlusIcon, SearchIcon } from "lucide-react";import Link from "next/link";-import type { ChangeEventHandler } from "react";+import type { ChangeEventHandler, ReactNode } from "react";import { cn } from "@/lib/cn";import type { DashboardEnvelopeListItem } from "@/lib/envelopes";@@ -16,6 +16,12 @@ export type DashboardShellState = "default" | "empty" | "error";/** An administrator's dashboard: their own envelopes, or everyone's. */export type DashboardView = "all" | "mine";+/** Links to the pages before and after this one, when there are any. */+export type DashboardPagination = {+ newerHref?: string;+ olderHref?: string;+};+export type DashboardFilter ="All" | "Draft" | "Sent" | "Completed" | "Declined" | "Voided";@@ -75,8 +81,10 @@ type DashboardDocumentsPanelProps = {onReset?: () => void;onRetry?: () => void;onSearchChange?: ChangeEventHandler<HTMLInputElement>;+ pagination?: DashboardPagination;searchValue: string;selectedFilter: DashboardFilter;+ view?: DashboardView;};type EnvelopeGridProps = {@@ -159,8 +167,10 @@ export function DashboardDocumentsPanel({onReset,onRetry,onSearchChange,+ pagination,searchValue,selectedFilter,+ view,}: DashboardDocumentsPanelProps) {const hasSeededEnvelopes = envelopes.length > 0;@@ -201,19 +211,27 @@ export function DashboardDocumentsPanel({})}</div>- <label className="flex min-h-[2.625rem] w-full items-center gap-2.5 rounded-xl bg-white px-3.5 text-(--tertiary) transition focus-within:ring-3 focus-within:ring-ring/50 lg:w-[19rem]">- <SearchIcon aria-hidden="true" className="size-4 shrink-0" />- <input- aria-label="Search by title or email..."- className="min-w-0 flex-1 bg-transparent py-2 text-sm text-(--fg) outline-none placeholder:text-(--placeholder)"- onChange={interactive ? onSearchChange : undefined}- placeholder="Search by title or email..."- readOnly={!interactive}- tabIndex={interactive ? undefined : -1}- type="search"- value={searchValue}- />- </label>+ {/* Typing narrows what is shown; Enter searches every envelope,+ not only this page. */}+ <SearchForm interactive={interactive}>+ {view === "all" ? (+ <input name="view" type="hidden" value="all" />+ ) : null}+ <label className="flex min-h-[2.625rem] w-full items-center gap-2.5 rounded-xl bg-white px-3.5 text-(--tertiary) transition focus-within:ring-3 focus-within:ring-ring/50">+ <SearchIcon aria-hidden="true" className="size-4 shrink-0" />+ <input+ aria-label="Search by title or email..."+ className="min-w-0 flex-1 bg-transparent py-2 text-sm text-(--fg) outline-none placeholder:text-(--placeholder)"+ name="q"+ onChange={interactive ? onSearchChange : undefined}+ placeholder="Search by title or email..."+ readOnly={!interactive}+ tabIndex={interactive ? undefined : -1}+ type="search"+ value={searchValue}+ />+ </label>+ </SearchForm></div>{isError ? (@@ -222,19 +240,59 @@ export function DashboardDocumentsPanel({{filteredEnvelopes.length > 0 ? (<EnvelopeGrid envelopes={filteredEnvelopes} interactive={interactive} />- ) : hasSeededEnvelopes ? (+ ) : hasSeededEnvelopes || searchValue || pagination?.newerHref ? (<NoResultsState interactive={interactive} onReset={onReset} />) : null}- {!isError && hasSeededEnvelopes ? (- <p className="px-1 text-[0.8125rem] text-(--tertiary)">- Showing {filteredEnvelopes.length} of {envelopes.length} envelopes- </p>+ {!isError && (hasSeededEnvelopes || pagination?.newerHref) ? (+ <div className="flex flex-wrap items-center justify-between gap-3 px-1">+ <p className="text-[0.8125rem] text-(--tertiary)">+ Showing {filteredEnvelopes.length} of {envelopes.length} envelopes+ {pagination?.newerHref || pagination?.olderHref+ ? " on this page"+ : ""}+ </p>+ {interactive && (pagination?.newerHref || pagination?.olderHref) ? (+ <nav aria-label="Pages" className="flex items-center gap-2">+ {pagination.newerHref ? (+ <ShellButton href={pagination.newerHref} variant="secondary">+ Newer+ </ShellButton>+ ) : null}+ {pagination.olderHref ? (+ <ShellButton href={pagination.olderHref} variant="secondary">+ Older+ </ShellButton>+ ) : null}+ </nav>+ ) : null}+ </div>) : null}</section>);}+/** A real form on the dashboard; in the landing page's picture, a box. */+function SearchForm({+ children,+ interactive,+}: {+ children: ReactNode;+ interactive: boolean;+}) {+ const className = "w-full lg:w-[19rem]";++ if (!interactive) {+ return <div className={className}>{children}</div>;+ }++ return (+ <form action="/dashboard" className={className} method="get" role="search">+ {children}+ </form>+ );+}+function ErrorBanner({ interactive, onRetry }: ErrorBannerProps) {return (<divdiff --git a/src/components/dashboard/dashboard-shell.tsx b/src/components/dashboard/dashboard-shell.tsxindex 3a3bcfe..c13bb8b 100644--- a/src/components/dashboard/dashboard-shell.tsx+++ b/src/components/dashboard/dashboard-shell.tsx@@ -9,6 +9,7 @@ import {DashboardDocumentsPanel,dashboardStatusFilterMap,type DashboardFilter,+ type DashboardPagination,type DashboardShellState,type DashboardView,} from "@/components/dashboard/dashboard-documents-surface";@@ -17,17 +18,22 @@ import { ShellButton } from "@/components/shared/form-shell";type DashboardShellProps = {envelopes?: readonly DashboardEnvelopeListItem[];+ /** The search the page was loaded with, run on the server. */+ initialSearch?: string;initialState?: DashboardShellState;+ pagination?: DashboardPagination;/** For an administrator: their own envelopes, or everyone's. */view?: DashboardView;};export function DashboardShell({envelopes: providedEnvelopes,+ initialSearch = "",initialState = "default",+ pagination,view,}: DashboardShellProps) {- const [searchValue, setSearchValue] = useState("");+ const [searchValue, setSearchValue] = useState(initialSearch);const [selectedFilter, setSelectedFilter] = useState<DashboardFilter>("All");const envelopes =@@ -43,6 +49,8 @@ export function DashboardShell({const matchesSearch =normalizedSearchValue.length === 0 ||envelope.title.toLowerCase().includes(normalizedSearchValue) ||+ (envelope.senderLabel?.toLowerCase().includes(normalizedSearchValue) ??+ false) ||envelope.searchableEmails.some((email) =>email.toLowerCase().includes(normalizedSearchValue),);@@ -60,6 +68,14 @@ export function DashboardShell({}function handleResetFilters() {+ if (initialSearch || pagination?.newerHref) {+ // The list itself was searched, or is a later page: load the start.+ window.location.assign(+ view === "all" ? "/dashboard?view=all" : "/dashboard",+ );+ return;+ }+setSearchValue("");setSelectedFilter("All");}@@ -87,7 +103,9 @@ export function DashboardShell({onReset={handleResetFilters}onRetry={handleRetry}onSearchChange={handleSearchChange}+ pagination={pagination}searchValue={searchValue}+ view={view}selectedFilter={selectedFilter}/>)}diff --git a/src/lib/envelope-access.dbtest.ts b/src/lib/envelope-access.dbtest.tsindex 9bfe8a4..e6b12b8 100644--- a/src/lib/envelope-access.dbtest.ts+++ b/src/lib/envelope-access.dbtest.ts@@ -113,7 +113,9 @@ test("an administrator's list of every envelope names each sender", async () =>const secondEnvelope = await createEnvelope(second.userId, "Second lease");const all = await listAllEnvelopesForAdmin({ limit: 100 }, database);- const byId = new Map(all.map((envelope) => [envelope.id, envelope]));+ const byId = new Map(+ all.envelopes.map((envelope) => [envelope.id, envelope]),+ );assert.equal(byId.get(firstEnvelope)?.senderLabel,@@ -121,13 +123,71 @@ test("an administrator's list of every envelope names each sender", async () =>);// No name: the address alone.assert.equal(byId.get(secondEnvelope)?.senderLabel, second.email);+ // The sender's address is searchable on the page too.+ assert.ok(byId.get(firstEnvelope)?.searchableEmails.includes(first.email));// A sender's own list stays theirs, without the sender on each card.const own = await listEnvelopesForUser(first.userId, {}, database);assert.deepEqual(- own.map((envelope) => envelope.id),+ own.envelopes.map((envelope) => envelope.id),[firstEnvelope],);- assert.equal(own[0]?.senderLabel, undefined);+ assert.equal(own.envelopes[0]?.senderLabel, undefined);+ assert.equal(own.hasMore, false);+});++test("every envelope can be reached, a page at a time", async () => {+ const sender = await createUser("user", "Paige Pager");+ const ids: string[] = [];++ for (let index = 0; index < 5; index += 1) {+ ids.push(await createEnvelope(sender.userId, `Page test ${String(index)}`));+ }++ const seen: string[] = [];+ let page = 1;+ let hasMore = true;++ while (hasMore) {+ const result = await listEnvelopesForUser(+ sender.userId,+ { limit: 2, page },+ database,+ );++ assert.ok(result.envelopes.length <= 2);+ seen.push(...result.envelopes.map((envelope) => envelope.id));+ hasMore = result.hasMore;+ page += 1;+ }++ assert.deepEqual([...seen].sort(), [...ids].sort());+ assert.equal(page - 1, 3);+});++test("searching every envelope finds a sender by name or address", async () => {+ const sender = await createUser("user", "Quentin Quarry");+ const envelopeId = await createEnvelope(sender.userId, "Unrelated title");++ for (const search of ["quentin quarry", sender.email.slice(0, 12)]) {+ const result = await listAllEnvelopesForAdmin(+ { limit: 100, search },+ database,+ );++ assert.ok(+ result.envelopes.some((envelope) => envelope.id === envelopeId),+ `expected "${search}" to find the envelope`,+ );+ }++ // A sender's own search does not look at the sender.+ const own = await listEnvelopesForUser(+ sender.userId,+ { search: "quentin" },+ database,+ );++ assert.deepEqual(own.envelopes, []);});diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 381c602..f01b01e 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -1785,11 +1785,18 @@ function buildDetailSignerMetaLabel(return `${pluralize(assignedFieldCount, "field")} assigned`;}+/** One page of a dashboard list, newest first. */+export type DashboardEnvelopePage = {+ envelopes: DashboardEnvelopeListItem[];+ /** There are older envelopes on the next page. */+ hasMore: boolean;+};+export async function listEnvelopesForUser(userId: string,filters: Partial<EnvelopeListFilters> = {},database: DbExecutor = getDb(),-): Promise<DashboardEnvelopeListItem[]> {+): Promise<DashboardEnvelopePage> {return listEnvelopes(userId, filters, database);}@@ -1800,7 +1807,7 @@ export async function listEnvelopesForUser(export async function listAllEnvelopesForAdmin(filters: Partial<EnvelopeListFilters> = {},database: DbExecutor = getDb(),-): Promise<DashboardEnvelopeListItem[]> {+): Promise<DashboardEnvelopePage> {return listEnvelopes(null, filters, database);}@@ -1808,7 +1815,7 @@ async function listEnvelopes(ownerUserId: string | null,filters: Partial<EnvelopeListFilters>,database: DbExecutor,-): Promise<DashboardEnvelopeListItem[]> {+): Promise<DashboardEnvelopePage> {const parsedFilters = envelopeListFiltersSchema.parse(filters);const values: unknown[] = ownerUserId === null ? [] : [ownerUserId];const clauses = ownerUserId === null ? ["TRUE"] : ["user_id = $1"];@@ -1830,7 +1837,21 @@ async function listEnvelopes(FROM signersWHERE signers.envelope_id = envelopes.idAND lower(signers.email) LIKE ${searchPlaceholder} ESCAPE '\\'- )+ )${+ // Across the install, the sender too.+ ownerUserId === null+ ? `+ OR EXISTS (+ SELECT 1+ FROM public."user" sender+ WHERE sender.id = envelopes.user_id+ AND (+ lower(sender.email) LIKE ${searchPlaceholder} ESCAPE '\\'+ OR lower(sender.name) LIKE ${searchPlaceholder} ESCAPE '\\'+ )+ )`+ : ""+ })`,);values.push(`%${escapeLike(parsedFilters.search.toLowerCase())}%`);@@ -1838,7 +1859,8 @@ async function listEnvelopes(}const limitPlaceholder = `$${String(nextParamIndex)}`;- values.push(parsedFilters.limit);+ // One more than a page, to tell whether there is a next one.+ values.push(parsedFilters.limit + 1);nextParamIndex += 1;const offsetPlaceholder = `$${String(nextParamIndex)}`;values.push((parsedFilters.page - 1) * parsedFilters.limit);@@ -1877,7 +1899,8 @@ async function listEnvelopes(values,);- const envelopes = rows.map(mapEnvelopeRow);+ const hasMore = rows.length > parsedFilters.limit;+ const envelopes = rows.slice(0, parsedFilters.limit).map(mapEnvelopeRow);const envelopeIds = envelopes.map((envelope) => envelope.id);const [signersByEnvelope, fieldsByEnvelope, copyRecipientsByEnvelope] =await Promise.all([@@ -1893,7 +1916,7 @@ async function listEnvelopes(): null;- return envelopes.map((envelope) => {+ const items = envelopes.map((envelope) => {const signers = signersByEnvelope.get(envelope.id) ?? [];const fields = fieldsByEnvelope.get(envelope.id) ?? [];const sender = sendersById?.get(envelope.userId);@@ -1917,12 +1940,16 @@ async function listEnvelopes(searchableEmails: [...signers,...(copyRecipientsByEnvelope.get(envelope.id) ?? []),+ // Across the install, the sender too.+ ...(sender ? [sender] : []),].map((recipient) => recipient.email),status: envelope.status,statusLabel: buildDashboardStatusLabel(envelope, signers),title: envelope.title,};});++ return { envelopes: items, hasMore };}type SenderRow = { email: string; id: string; name: string | null };