Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Send one template to many signers from a CSV

Matt Van Horn9bcba19c56c2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ea04e9..a089403 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,21 @@ release says when it does.
## [Unreleased]
+Send the same template to many people at once from a CSV. This needs a
+migration step (`20261118090000_bulk_send_batches.sql`): a confirmed batch
+stores its results so a retry does not send the same envelopes again.
+
+### Templates
+
+- **Send to many** on a template: upload or paste a CSV of names and email
+ addresses and send one envelope per row, with a preview that flags missing
+ or invalid addresses, duplicate rows and batches over 200 before anything
+ is created. Each row is sent on its own, so one failure does not take the
+ others with it. Confirming is idempotent: the same batch key returns the
+ stored results instead of sending again. After sending, the results can be
+ downloaded as a CSV. In Part 11 mode, a row is skipped when the signer
+ does not have a verified, identity-checked account.
+
## [0.3.0] - 2026-11-16
Sign-in security and audit features for organizations that need them, and
diff --git a/README.md b/README.md
index 03bbcae..337b3fd 100644
--- a/README.md
+++ b/README.md
@@ -68,7 +68,7 @@ The dashboard shows each document as a card with its first page, its status (dra
### Templates for the documents you send every week
-Open any envelope and choose Save as template. The template keeps the document, the fields and the signing order, with roles instead of names. Using it asks who signs this time and opens a draft ready to send.
+Open any envelope and choose Save as template. The template keeps the document, the fields and the signing order, with roles instead of names. Using it asks who signs this time and opens a draft ready to send. Send to many takes a CSV of names and addresses and sends one envelope per row.
### Sealed, certified, and checkable by anyone
diff --git a/db/migrations/20261118090000_bulk_send_batches.sql b/db/migrations/20261118090000_bulk_send_batches.sql
new file mode 100644
index 0000000..253449c
--- /dev/null
+++ b/db/migrations/20261118090000_bulk_send_batches.sql
@@ -0,0 +1,30 @@
+-- Confirmed "send to many" batches, so a retry of the same confirm does not
+-- create another envelope for a row that already went out.
+--
+-- The client gives each confirm a batch_key. The first request stores each
+-- row as it is sent. A later request with that key returns or finishes those
+-- stored results instead of sending the list again.
+
+create table if not exists public.bulk_send_batches (
+ id text primary key,
+ user_id text not null references public."user"(id) on delete cascade,
+ template_id text not null references public.templates(id) on delete cascade,
+ batch_key text not null,
+ request_fingerprint text not null,
+ created_at bigint not null default (extract(epoch from now())::bigint),
+ constraint bulk_send_batches_user_key unique (user_id, batch_key)
+);
+
+create table if not exists public.bulk_send_batch_rows (
+ batch_id text not null references public.bulk_send_batches(id) on delete cascade,
+ row_number integer not null,
+ status text not null
+ check (status in ('processing', 'sent', 'skipped', 'failed')),
+ envelope_id text references public.envelopes(id) on delete set null,
+ reason text,
+ primary key (batch_id, row_number)
+);
+
+create index if not exists idx_bulk_send_batch_rows_envelope_id
+ on public.bulk_send_batch_rows(envelope_id)
+ where envelope_id is not null;
diff --git a/docs/development.md b/docs/development.md
index ea806a7..934f672 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -73,7 +73,7 @@ The first time you open the app it takes you to `/setup`, where you name the org
People added to receive a copy do not sign. They are sent the finished document and its certificate at step 7 and nothing before it.
-A document you send often can be kept as a template: open any envelope, sent or not, and choose Save as template. The template keeps the document, the fields and the signing order, and no one's name or email address. Using it asks who signs this time and opens a draft at step 4.
+A document you send often can be kept as a template: open any envelope, sent or not, and choose Save as template. The template keeps the document, the fields and the signing order, and no one's name or email address. Using it asks who signs this time and opens a draft at step 4. Send to many takes a CSV of names and addresses and sends one envelope per row, so the same form can go out to many people without repeating those steps.
## Storage
diff --git a/src/app/(app)/templates/[id]/send-many/page.tsx b/src/app/(app)/templates/[id]/send-many/page.tsx
new file mode 100644
index 0000000..dd20e69
--- /dev/null
+++ b/src/app/(app)/templates/[id]/send-many/page.tsx
@@ -0,0 +1,81 @@
+import { notFound } from "next/navigation";
+
+import { BulkSendShell } from "@/components/templates/bulk-send-shell";
+import { getAuthSession } from "@/lib/auth/server";
+import { exampleCsvForRoles, MAX_BULK_SEND_ROWS } from "@/lib/bulk-send-csv";
+import { getDb } from "@/lib/db/connection";
+import { getSettings } from "@/lib/settings";
+import {
+ describeUnsendableTemplate,
+ getTemplateForBulkSend,
+ TemplateError,
+} from "@/lib/templates";
+
+type BulkSendPageProps = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+export default async function BulkSendPage({ params }: BulkSendPageProps) {
+ const { id } = await params;
+ let template: Awaited<ReturnType<typeof getTemplateForBulkSend>> = null;
+ let errorMessage: string | undefined;
+ let failed = false;
+ let part11Mode = false;
+
+ try {
+ const session = await getAuthSession();
+ const loaded = session
+ ? await getTemplateForBulkSend(session.user.id, id, getDb())
+ : null;
+ const unsendable = loaded
+ ? describeUnsendableTemplate(loaded.roles, loaded.fields)
+ : null;
+
+ if (unsendable) {
+ failed = true;
+ errorMessage = unsendable;
+ } else {
+ template = loaded;
+ }
+ } catch (error) {
+ failed = true;
+ errorMessage = error instanceof TemplateError ? error.message : undefined;
+ }
+
+ try {
+ part11Mode = (await getSettings()).part11Mode;
+ } catch {
+ part11Mode = false;
+ }
+
+ if (!failed && !template) {
+ notFound();
+ }
+
+ const shellTemplate = template
+ ? {
+ fieldCountLabel: template.fieldCountLabel,
+ id: template.id,
+ name: template.name,
+ pageCountLabel: template.pageCountLabel,
+ roles: template.roles,
+ }
+ : undefined;
+
+ return (
+ <BulkSendShell
+ errorMessage={errorMessage}
+ exampleCsv={
+ shellTemplate
+ ? exampleCsvForRoles(shellTemplate.roles.map((role) => role.name))
+ : ""
+ }
+ key={id}
+ maxRows={MAX_BULK_SEND_ROWS}
+ part11Mode={part11Mode}
+ template={shellTemplate}
+ />
+ );
+}
diff --git a/src/app/api/templates/[id]/bulk-send/route.ts b/src/app/api/templates/[id]/bulk-send/route.ts
new file mode 100644
index 0000000..8874775
--- /dev/null
+++ b/src/app/api/templates/[id]/bulk-send/route.ts
@@ -0,0 +1,137 @@
+import { NextResponse } from "next/server";
+import { ZodError } from "zod";
+
+import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
+import { BulkSendError, bulkSendFromTemplate } from "@/lib/bulk-send";
+import { getDb } from "@/lib/db/connection";
+import { EnvelopeMutationError } from "@/lib/envelopes";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import {
+ getClientIpAddress,
+ getRequestPathname,
+ getRequestUserAgent,
+} from "@/lib/security/request";
+import { DocumentImportError } from "@/lib/services/document-import";
+import { TemplateError } from "@/lib/templates";
+import { readLimitedBody } from "@/lib/utils/limited-body";
+
+type BulkSendRouteContext = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+const MAX_BULK_SEND_BODY_BYTES = 1024 * 1024;
+
+// Preview or send a template to many people from a CSV.
+
+export async function POST(request: Request, context: BulkSendRouteContext) {
+ const sessionResult = await requireVerifiedSenderSession(request);
+
+ if (sessionResult instanceof Response) {
+ return sessionResult;
+ }
+
+ const session = sessionResult;
+ const ipAddress = getClientIpAddress(request.headers);
+ const bodyBytes = await readLimitedBody(request, MAX_BULK_SEND_BODY_BYTES);
+
+ if (bodyBytes === null) {
+ return NextResponse.json(
+ { error: "This CSV is too large to send in one batch." },
+ { status: 413 },
+ );
+ }
+
+ let body: { confirm?: unknown } | null = null;
+
+ try {
+ body = JSON.parse(new TextDecoder().decode(bodyBytes)) as {
+ confirm?: unknown;
+ };
+ } catch {
+ return NextResponse.json(
+ { error: "This request was not valid JSON." },
+ { status: 400 },
+ );
+ }
+
+ const confirm = body?.confirm === true;
+ const rateLimitResponse = await applyRateLimit({
+ category: confirm ? "template_bulk_send" : "template_bulk_send_preview",
+ key: buildRateLimitKey([
+ confirm ? "bulk-send" : "bulk-send-preview",
+ session.user.id,
+ ]),
+ limit: confirm ? 10 : 30,
+ request,
+ userId: session.user.id,
+ windowMs: confirm ? 60 * 60 * 1000 : 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ rateLimitResponse.headers.set("cache-control", "private, no-store");
+ return rateLimitResponse;
+ }
+
+ const { id } = await context.params;
+
+ try {
+ const result = await bulkSendFromTemplate(session.user.id, id, body, {
+ database: getDb(),
+ sender: {
+ email: session.user.email,
+ ipAddress,
+ name:
+ typeof session.user.name === "string" && session.user.name.trim()
+ ? session.user.name
+ : session.user.email,
+ userAgent: getRequestUserAgent(request.headers),
+ },
+ });
+
+ return NextResponse.json(result, {
+ headers: { "cache-control": "private, no-store" },
+ status: 200,
+ });
+ } catch (error) {
+ if (error instanceof ZodError) {
+ return NextResponse.json(
+ { error: error.issues[0]?.message ?? "Invalid bulk send request." },
+ { status: 400 },
+ );
+ }
+
+ if (
+ error instanceof BulkSendError ||
+ error instanceof TemplateError ||
+ error instanceof EnvelopeMutationError
+ ) {
+ return NextResponse.json(
+ { error: error.message },
+ { status: error.statusCode },
+ );
+ }
+
+ if (error instanceof DocumentImportError) {
+ return NextResponse.json({ error: error.message }, { status: 400 });
+ }
+
+ logRouteError(error, {
+ category: "template_bulk_send_failure",
+ ipAddress,
+ message: "Unexpected failure while sending a template to many people.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "Unable to send this template to many people." },
+ { status: 500 },
+ );
+ }
+}
diff --git a/src/components/templates/bulk-send-shell.tsx b/src/components/templates/bulk-send-shell.tsx
new file mode 100644
index 0000000..966b03d
--- /dev/null
+++ b/src/components/templates/bulk-send-shell.tsx
@@ -0,0 +1,771 @@
+"use client";
+
+import Link from "next/link";
+import { useRef, useState, type ChangeEvent } from "react";
+
+import { ShellButton } from "@/components/shared/form-shell";
+import { PageHeader } from "@/components/shared/page-header";
+import { StatusPanel } from "@/components/shared/status-panel";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ type BulkSendResult,
+ type BulkSendRowResult,
+ bulkSendPreviewKey,
+ copyRecipientPairError,
+ serializeBulkSendResultsCsv,
+} from "@/lib/bulk-send-csv";
+import { PERMITTED_USE_PATH } from "@/lib/permitted-uses";
+import { formatReminderInterval } from "@/lib/services/reminders";
+import { SIGNATURE_MEANING_DETAILS } from "@/lib/signature-meanings";
+import type { UseTemplateData } from "@/lib/templates";
+import {
+ DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ DEFAULT_ENVELOPE_REMINDER_DAYS,
+ ENVELOPE_DEADLINE_DAY_OPTIONS,
+ ENVELOPE_REMINDER_DAY_OPTIONS,
+ signatureMeanings,
+ type SignatureMeaning,
+} from "@/lib/types/domain";
+
+type BulkSendRequest = {
+ copyRecipients: { email: string; name: string }[] | undefined;
+ csv: string;
+ expiresInDays: number;
+ reminderIntervalDays: number | null;
+ requireEmailCode: boolean;
+ signatureMeaning: SignatureMeaning | null;
+};
+
+type BulkSendShellProps = {
+ errorMessage?: string;
+ exampleCsv: string;
+ maxRows: number;
+ part11Mode?: boolean;
+ template?: UseTemplateData;
+};
+
+const genericError = "Something went wrong. Please try again.";
+
+function statusPill(status: BulkSendRowResult["status"]) {
+ if (status === "sent" || status === "ok") {
+ return "pill pill-success";
+ }
+
+ if (status === "failed") {
+ return "pill pill-danger";
+ }
+
+ return "pill pill-warning";
+}
+
+function statusLabel(status: BulkSendRowResult["status"]) {
+ if (status === "ok") {
+ return "Ready";
+ }
+
+ if (status === "sent") {
+ return "Sent";
+ }
+
+ if (status === "failed") {
+ return "Failed";
+ }
+
+ return "Skipped";
+}
+
+function downloadResults(
+ result: BulkSendResult,
+ roleNames: readonly string[],
+ templateName: string,
+) {
+ const csv = serializeBulkSendResultsCsv(result.rows, roleNames);
+ const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+
+ link.href = url;
+ link.download = `${templateName.replace(/[^\w-]+/g, "-").replace(/^-|-$/g, "") || "bulk-send"}-results.csv`;
+ link.click();
+ URL.revokeObjectURL(url);
+}
+
+function newBulkSendBatchKey(): string {
+ return crypto.randomUUID();
+}
+
+function csvColumnHelp(roleNames: readonly string[]): string {
+ if (roleNames.length === 1) {
+ return "For this template the header is name,email. You can add a title column. Each row becomes its own envelope.";
+ }
+
+ return `For this template name the columns after each signer: ${roleNames
+ .map((name) => `${name} name, ${name} email`)
+ .join("; ")}. A title column is optional.`;
+}
+
+export function BulkSendShell({
+ errorMessage,
+ exampleCsv,
+ maxRows,
+ part11Mode = false,
+ template,
+}: BulkSendShellProps) {
+ const [csv, setCsv] = useState("");
+ const [deadlineDays, setDeadlineDays] = useState(
+ DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ );
+ const [reminderDays, setReminderDays] = useState<number | null>(
+ DEFAULT_ENVELOPE_REMINDER_DAYS,
+ );
+ const [copyName, setCopyName] = useState("");
+ const [copyEmail, setCopyEmail] = useState("");
+ const batchKeyRef = useRef(newBulkSendBatchKey());
+ const [requireEmailCode, setRequireEmailCode] = useState(false);
+ const [signatureMeaning, setSignatureMeaning] = useState<
+ SignatureMeaning | ""
+ >("");
+ // The preview is only valid for the exact inputs that were checked, so it
+ // is stored with the request it came from and sending reuses that request.
+ const [checked, setChecked] = useState<{
+ key: string;
+ preview: BulkSendResult;
+ request: BulkSendRequest;
+ } | null>(null);
+ const [results, setResults] = useState<BulkSendResult | null>(null);
+ const [isChecking, setIsChecking] = useState(false);
+ const [isSending, setIsSending] = useState(false);
+ const [isConfirming, setIsConfirming] = useState(false);
+ const [actionError, setActionError] = useState<string | null>(null);
+
+ if (!template) {
+ return (
+ <div className="space-y-5">
+ <PageHeader title="Send to many" />
+ <StatusPanel
+ action={{ href: "/templates", label: "Back to templates" }}
+ description={
+ errorMessage ??
+ "We couldn't load this template. Try again in a moment."
+ }
+ title="This template can't be used"
+ tone="error"
+ />
+ </div>
+ );
+ }
+
+ const current = template;
+ const roleNames = current.roles.map((role) => role.name);
+ const copyError = copyRecipientPairError(copyName, copyEmail);
+ const copyRecipients =
+ copyError === null &&
+ copyName.trim().length > 0 &&
+ copyEmail.trim().length > 0
+ ? [{ email: copyEmail, name: copyName }]
+ : [];
+ const requestBody: BulkSendRequest = {
+ copyRecipients: copyRecipients.length > 0 ? copyRecipients : undefined,
+ csv,
+ expiresInDays: deadlineDays,
+ reminderIntervalDays: reminderDays,
+ requireEmailCode,
+ signatureMeaning: signatureMeaning || null,
+ };
+ const requestKey = bulkSendPreviewKey({
+ copyEmail,
+ copyName,
+ csv,
+ expiresInDays: deadlineDays,
+ reminderIntervalDays: reminderDays,
+ requireEmailCode,
+ signatureMeaning: signatureMeaning || null,
+ });
+ // A check that finishes after the inputs changed describes a different
+ // batch, so it is ignored until the list is checked again.
+ const preview =
+ checked && checked.key === requestKey ? checked.preview : null;
+
+ async function postBulkSend(
+ request: BulkSendRequest,
+ confirm: boolean,
+ permittedUseConfirmed = false,
+ ) {
+ const response = await fetch(`/api/templates/${current.id}/bulk-send`, {
+ body: JSON.stringify({
+ ...request,
+ batchKey: confirm ? batchKeyRef.current : undefined,
+ confirm,
+ permittedUseConfirmed,
+ }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as
+ (BulkSendResult & { error?: string }) | { error?: string } | null;
+
+ if (!response.ok) {
+ throw new Error(payload?.error ?? genericError);
+ }
+
+ if (!payload || !("rows" in payload) || !Array.isArray(payload.rows)) {
+ throw new Error(genericError);
+ }
+
+ return payload;
+ }
+
+ async function handleCheck() {
+ if (isChecking || isSending || csv.trim().length === 0) {
+ return;
+ }
+
+ if (copyError) {
+ setActionError(copyError);
+ return;
+ }
+
+ setActionError(null);
+ setResults(null);
+ setIsChecking(true);
+
+ const request = requestBody;
+ const key = requestKey;
+
+ try {
+ const checkedPreview = await postBulkSend(request, false);
+
+ setChecked({
+ key,
+ preview: checkedPreview,
+ request,
+ });
+ } catch (error) {
+ setChecked(null);
+ setActionError(error instanceof Error ? error.message : genericError);
+ } finally {
+ setIsChecking(false);
+ }
+ }
+
+ async function handleFile(event: ChangeEvent<HTMLInputElement>) {
+ const file = event.target.files?.[0];
+
+ event.target.value = "";
+
+ if (!file) {
+ return;
+ }
+
+ const text = await file.text();
+
+ setCsv(text);
+ setChecked(null);
+ setResults(null);
+ setActionError(null);
+ }
+
+ async function handleConfirmSend() {
+ if (isSending || !checked || !preview || preview.summary.ok === 0) {
+ return;
+ }
+
+ setActionError(null);
+ setIsSending(true);
+
+ try {
+ const sent = await postBulkSend(checked.request, true, true);
+
+ setResults(sent);
+ setChecked(null);
+ setIsConfirming(false);
+ batchKeyRef.current = newBulkSendBatchKey();
+ } catch (error) {
+ setActionError(error instanceof Error ? error.message : genericError);
+ } finally {
+ setIsSending(false);
+ }
+ }
+
+ const readyCount = preview?.summary.ok ?? 0;
+
+ return (
+ <div className="space-y-5">
+ <PageHeader
+ description={`${template.name} · ${template.pageCountLabel} · ${template.fieldCountLabel}`}
+ title="Send to many"
+ />
+
+ {results ? (
+ <section className="panel space-y-5 p-5 sm:p-8" data-animate="enter">
+ <div className="space-y-1">
+ <h2 className="text-lg font-extrabold text-(--fg)">Results</h2>
+ <p className="text-sm leading-6 text-(--secondary)">
+ {results.summary.sent} sent
+ {results.summary.skipped > 0
+ ? ` · ${String(results.summary.skipped)} skipped`
+ : ""}
+ {results.summary.failed > 0
+ ? ` · ${String(results.summary.failed)} failed`
+ : ""}
+ . Each sent envelope is independent.
+ </p>
+ </div>
+ <RowTable result={results} roleNames={roleNames} />
+ <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
+ <ShellButton href="/dashboard" variant="secondary">
+ Go to documents
+ </ShellButton>
+ <ShellButton
+ onClick={() => downloadResults(results, roleNames, current.name)}
+ variant="secondary"
+ >
+ Download results CSV
+ </ShellButton>
+ <ShellButton
+ onClick={() => {
+ batchKeyRef.current = newBulkSendBatchKey();
+ setResults(null);
+ setChecked(null);
+ setActionError(null);
+ }}
+ >
+ Send another batch
+ </ShellButton>
+ </div>
+ </section>
+ ) : (
+ <form
+ className="panel space-y-6 p-5 sm:p-8"
+ data-animate="enter"
+ data-animate-delay="1"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void handleCheck();
+ }}
+ >
+ <div className="space-y-2">
+ <h2 className="text-lg font-extrabold text-(--fg)">
+ Who should sign?
+ </h2>
+ <p className="text-sm leading-6 text-(--secondary)">
+ Upload a CSV or paste it below. {csvColumnHelp(roleNames)} A batch
+ can send at most {String(maxRows)} envelopes. Nothing is created
+ until you confirm.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-3">
+ <label className="btn-quiet cursor-pointer">
+ Upload a CSV
+ <input
+ accept=".csv,text/csv,text/plain"
+ aria-label="Upload a CSV"
+ className="sr-only"
+ onChange={(event) => {
+ void handleFile(event);
+ }}
+ type="file"
+ />
+ </label>
+ <button
+ className="btn-quiet"
+ onClick={() => {
+ setCsv(exampleCsv);
+ setChecked(null);
+ setResults(null);
+ setActionError(null);
+ }}
+ type="button"
+ >
+ Use the example
+ </button>
+ </div>
+
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ CSV
+ </span>
+ <textarea
+ aria-label="People who should sign"
+ className="field-input min-h-40 font-mono text-[0.8125rem] leading-6"
+ onChange={(event) => {
+ setCsv(event.target.value);
+ setChecked(null);
+ setActionError(null);
+ }}
+ spellCheck={false}
+ value={csv}
+ />
+ </label>
+
+ <div className="well space-y-4 p-4">
+ <div className="grid gap-4 sm:grid-cols-2">
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Signing deadline
+ </span>
+ <select
+ className="field-input"
+ onChange={(event) =>
+ setDeadlineDays(Number(event.target.value))
+ }
+ value={deadlineDays}
+ >
+ {ENVELOPE_DEADLINE_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {days} days
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Automatic reminders
+ </span>
+ <select
+ className="field-input"
+ onChange={(event) =>
+ setReminderDays(
+ event.target.value === "off"
+ ? null
+ : Number(event.target.value),
+ )
+ }
+ value={reminderDays ?? "off"}
+ >
+ <option value="off">{formatReminderInterval(null)}</option>
+ {ENVELOPE_REMINDER_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {formatReminderInterval(days)}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <p className="text-sm leading-6 text-(--secondary)">
+ Every envelope in the batch gets the same deadline, reminders,
+ copy recipient and extra check. Consent and the audit trail are
+ the same as a hand-sent envelope.
+ </p>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Copy recipient name
+ </span>
+ <input
+ className="field-input"
+ maxLength={120}
+ onChange={(event) => setCopyName(event.target.value)}
+ placeholder="Optional"
+ type="text"
+ value={copyName}
+ />
+ </label>
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Copy recipient email
+ </span>
+ <input
+ className="field-input"
+ maxLength={320}
+ onChange={(event) => setCopyEmail(event.target.value)}
+ placeholder="Optional"
+ type="email"
+ value={copyEmail}
+ />
+ </label>
+ </div>
+ {copyError ? (
+ <p className="notice notice-danger" role="alert">
+ {copyError}
+ </p>
+ ) : null}
+ <label className="flex items-start gap-3 text-sm leading-6 text-(--secondary)">
+ <Checkbox
+ checked={requireEmailCode}
+ className="mt-1"
+ onCheckedChange={(checked) =>
+ setRequireEmailCode(checked === true)
+ }
+ />
+ Email a one-time code when each signer opens the link
+ </label>
+ {part11Mode ? (
+ <label className="grid max-w-md gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ What each signature means
+ </span>
+ <select
+ className="field-input"
+ onChange={(event) =>
+ setSignatureMeaning(
+ event.target.value as SignatureMeaning | "",
+ )
+ }
+ value={signatureMeaning}
+ >
+ <option value="">Choose one</option>
+ {signatureMeanings.map((meaning) => (
+ <option key={meaning} value={meaning}>
+ {SIGNATURE_MEANING_DETAILS[meaning].label}
+ </option>
+ ))}
+ </select>
+ <span className="text-sm leading-6 text-(--secondary)">
+ Part 11 mode only lets people sign with a verified account
+ whose identity an administrator has confirmed. Rows that do
+ not meet that are skipped, with the reason.
+ </span>
+ </label>
+ ) : null}
+ </div>
+
+ {actionError ? (
+ <div className="notice notice-danger" role="alert">
+ <p>{actionError}</p>
+ </div>
+ ) : null}
+
+ {preview ? (
+ <div className="space-y-3">
+ <p className="text-sm leading-6 text-(--secondary)">
+ {readyCount} {readyCount === 1 ? "envelope" : "envelopes"} can
+ be sent
+ {preview.summary.skipped > 0
+ ? ` · ${String(preview.summary.skipped)} skipped`
+ : ""}
+ . Check the table before confirming.
+ </p>
+ <RowTable result={preview} roleNames={roleNames} />
+ </div>
+ ) : null}
+
+ <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
+ <ShellButton href="/templates" variant="secondary">
+ Cancel
+ </ShellButton>
+ <ShellButton
+ disabled={csv.trim().length === 0 || Boolean(copyError)}
+ loading={isChecking}
+ type="submit"
+ variant="secondary"
+ >
+ {isChecking ? "Checking..." : "Check this list"}
+ </ShellButton>
+ <ShellButton
+ disabled={
+ !preview || readyCount === 0 || isChecking || Boolean(copyError)
+ }
+ onClick={() => {
+ setActionError(null);
+ setIsConfirming(true);
+ }}
+ >
+ {readyCount > 0
+ ? `Send ${String(readyCount)} ${readyCount === 1 ? "envelope" : "envelopes"}`
+ : "Send envelopes"}
+ </ShellButton>
+ </div>
+ </form>
+ )}
+
+ {isConfirming && preview ? (
+ <SendManyDialog
+ errorMessage={actionError}
+ isSending={isSending}
+ onCancel={() => {
+ if (!isSending) {
+ setIsConfirming(false);
+ }
+ }}
+ onConfirm={() => {
+ void handleConfirmSend();
+ }}
+ readyCount={readyCount}
+ skippedCount={preview.summary.skipped}
+ templateName={current.name}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function RowTable({
+ result,
+ roleNames,
+}: {
+ result: BulkSendResult;
+ roleNames: readonly string[];
+}) {
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full min-w-[40rem] border-separate border-spacing-y-2 text-left text-sm">
+ <caption className="sr-only">
+ {result.summary.sent > 0 ? "Bulk send results" : "Bulk send preview"}
+ </caption>
+ <thead>
+ <tr className="text-[0.8125rem] text-(--secondary)">
+ <th className="px-3 py-1 font-semibold">Row</th>
+ <th className="px-3 py-1 font-semibold">Status</th>
+ {roleNames.map((name) => (
+ <th className="px-3 py-1 font-semibold" key={name}>
+ {name}
+ </th>
+ ))}
+ <th className="px-3 py-1 font-semibold">Title</th>
+ <th className="px-3 py-1 font-semibold">Notes</th>
+ </tr>
+ </thead>
+ <tbody>
+ {result.rows.map((row) => (
+ <tr className="well" key={row.rowNumber}>
+ <td className="rounded-l-xl px-3 py-3 font-semibold">
+ {row.rowNumber}
+ </td>
+ <td className="px-3 py-3">
+ <span className={statusPill(row.status)}>
+ {statusLabel(row.status)}
+ </span>
+ </td>
+ {row.signers.map((signer) => (
+ <td className="px-3 py-3" key={signer.roleName}>
+ <span className="block font-semibold text-(--fg)">
+ {signer.name || "—"}
+ </span>
+ <span className="block text-(--secondary)">
+ {signer.email || "—"}
+ </span>
+ </td>
+ ))}
+ <td className="px-3 py-3">{row.title}</td>
+ <td className="rounded-r-xl px-3 py-3">
+ {row.envelopePath ? (
+ <Link
+ className="font-semibold text-(--accent-ink) underline-offset-4 hover:underline"
+ href={row.envelopePath}
+ >
+ Open envelope
+ </Link>
+ ) : null}
+ {row.reason ? (
+ <p className="text-(--secondary)">{row.reason}</p>
+ ) : null}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+function SendManyDialog({
+ errorMessage,
+ isSending,
+ onCancel,
+ onConfirm,
+ readyCount,
+ skippedCount,
+ templateName,
+}: {
+ errorMessage: string | null;
+ isSending: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+ readyCount: number;
+ skippedCount: number;
+ templateName: string;
+}) {
+ const [isPermittedUseConfirmed, setIsPermittedUseConfirmed] = useState(false);
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !isSending) {
+ onCancel();
+ }
+ }}
+ >
+ <DialogContent className="max-w-md sm:p-8" showCloseButton={false}>
+ <div className="space-y-4">
+ <DialogHeader className="space-y-3">
+ <DialogTitle>Send these envelopes?</DialogTitle>
+ <DialogDescription asChild>
+ <div className="space-y-3 text-sm leading-6 text-(--secondary)">
+ <p>
+ &quot;{templateName}&quot; will be sent as {readyCount}{" "}
+ {readyCount === 1 ? "envelope" : "envelopes"}
+ {skippedCount > 0
+ ? `, and ${String(skippedCount)} ${skippedCount === 1 ? "row" : "rows"} will be skipped`
+ : ""}
+ . Each envelope is sent on its own, so one failure does not
+ take the others with it.
+ </p>
+ </div>
+ </DialogDescription>
+ </DialogHeader>
+
+ <label className="well block px-4 py-4">
+ <span className="flex items-start gap-3">
+ <Checkbox
+ autoFocus
+ checked={isPermittedUseConfirmed}
+ className="mt-1"
+ disabled={isSending}
+ onCheckedChange={(checked) =>
+ setIsPermittedUseConfirmed(checked === true)
+ }
+ />
+ <span className="text-sm leading-6 text-(--secondary)">
+ By sending, you confirm these documents are ordinary business
+ agreements and not a will, court order, legally required
+ consumer disclosure, or other{" "}
+ <a
+ className="font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4"
+ href={PERMITTED_USE_PATH}
+ rel="noreferrer"
+ target="_blank"
+ >
+ document that cannot be signed electronically
+ </a>
+ .
+ </span>
+ </span>
+ </label>
+
+ {errorMessage ? (
+ <div className="notice notice-danger" role="alert">
+ <p>{errorMessage}</p>
+ </div>
+ ) : null}
+
+ <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-end">
+ <ShellButton
+ disabled={isSending}
+ onClick={onCancel}
+ variant="secondary"
+ >
+ Cancel
+ </ShellButton>
+ <ShellButton
+ disabled={!isPermittedUseConfirmed}
+ loading={isSending}
+ onClick={onConfirm}
+ >
+ {isSending ? "Sending..." : "Send now"}
+ </ShellButton>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/templates/templates-shell.tsx b/src/components/templates/templates-shell.tsx
index e5064d3..a0d1e2f 100644
--- a/src/components/templates/templates-shell.tsx
+++ b/src/components/templates/templates-shell.tsx
@@ -153,6 +153,13 @@ export function TemplatesShell({
>
Delete
</button>
+ <ShellButton
+ className="min-h-11"
+ href={`/templates/${template.id}/send-many`}
+ variant="secondary"
+ >
+ Send to many
+ </ShellButton>
<ShellButton
className="min-h-11"
href={`/templates/${template.id}/use`}
diff --git a/src/lib/bulk-send-csv.test.ts b/src/lib/bulk-send-csv.test.ts
new file mode 100644
index 0000000..c336ddc
--- /dev/null
+++ b/src/lib/bulk-send-csv.test.ts
@@ -0,0 +1,337 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ ambiguousBulkSendColumnsMessage,
+ bulkSendCapMessage,
+ bulkSendPreviewKey,
+ copyRecipientPairError,
+ exampleCsvForRoles,
+ MAX_BULK_SEND_ROWS,
+ missingBulkSendColumnsMessage,
+ parseBulkSendCsv,
+ parseCsv,
+ serializeBulkSendResultsCsv,
+ serializeCsv,
+ validateBulkSendRows,
+} from "./bulk-send-csv.ts";
+import { duplicateSignerEmailMessage } from "./schemas/signer.ts";
+
+const oneRole = [{ name: "Signer 1" }];
+const twoRoles = [{ name: "Tenant" }, { name: "Landlord" }];
+
+test("quoted commas, doubled quotes, CRLF and a UTF-8 BOM are read as they were written", () => {
+ const text =
+ '\uFEFFname,email,note\r\n"Smith, Jane",[email protected],"said ""hello"""\r\n';
+
+ assert.deepEqual(parseCsv(text), [
+ ["name", "email", "note"],
+ ["Smith, Jane", "[email protected]", 'said "hello"'],
+ ]);
+ assert.deepEqual(parseCsv("a,b\n\n,\n c ,d \n"), [
+ ["a", "b"],
+ [" c ", "d "],
+ ]);
+ assert.deepEqual(parseCsv("a,b\r1,2"), [
+ ["a", "b"],
+ ["1", "2"],
+ ]);
+});
+
+test("a one-signer CSV uses name and email, or the role's columns, and title is optional", () => {
+ const named = parseBulkSendCsv(
+ "name,email\nJane Smith,[email protected]\n",
+ oneRole,
+ "Company NDA",
+ );
+
+ assert.equal(named.error, null);
+ assert.deepEqual(named.rows, [
+ {
+ rowNumber: 1,
+ signers: [
+ {
+ email: "[email protected]",
+ name: "Jane Smith",
+ roleName: "Signer 1",
+ },
+ ],
+ title: "Company NDA",
+ },
+ ]);
+
+ const prefixed = parseBulkSendCsv(
+ "Signer 1 name,Signer 1 email,title\nLou,[email protected],NDA for Lou\n",
+ oneRole,
+ "Company NDA",
+ );
+
+ assert.equal(prefixed.rows[0]?.title, "NDA for Lou");
+ assert.equal(prefixed.rows[0]?.signers[0]?.name, "Lou");
+});
+
+test("the example CSV round-trips for role names a spreadsheet would read as formulas", () => {
+ const roles = [{ name: "- Client" }, { name: "=Vendor" }];
+ const csv = exampleCsvForRoles(roles.map((role) => role.name));
+ const parsed = parseBulkSendCsv(csv, roles, "Lease");
+
+ assert.equal(parsed.error, null);
+ assert.equal(parsed.rows[0]?.signers[0]?.name, "- Client person");
+ assert.match(csv, /^- Client name,- Client email,=Vendor name,/);
+});
+
+test("a multi-role CSV names each role's columns, and the example round-trips", () => {
+ const csv = exampleCsvForRoles(["Tenant", "Landlord"]);
+ const parsed = parseBulkSendCsv(csv, twoRoles, "Lease");
+
+ assert.equal(parsed.error, null);
+ assert.equal(parsed.rows.length, 1);
+ assert.deepEqual(
+ parsed.rows[0]?.signers.map((signer) => signer.roleName),
+ ["Tenant", "Landlord"],
+ );
+ assert.match(
+ csv,
+ /Tenant name,Tenant email,Landlord name,Landlord email,title/,
+ );
+});
+
+test("roles that differ only in spacing keep their own columns", () => {
+ const roleNames = ["Client Advisor", "Client Advisor"];
+ const roles = roleNames.map((name) => ({ name }));
+ const example = parseBulkSendCsv(
+ exampleCsvForRoles(roleNames),
+ roles,
+ "Engagement",
+ );
+
+ assert.equal(example.error, null);
+ assert.equal(validateBulkSendRows(example.rows)[0]?.status, "ok");
+ assert.deepEqual(
+ example.rows[0]?.signers.map((signer) => [signer.roleName, signer.email]),
+ [
+ ["Client Advisor", "[email protected]"],
+ ["Client Advisor", "[email protected]"],
+ ],
+ );
+
+ const parsed = parseBulkSendCsv(
+ "Client Advisor name,Client Advisor email,Client Advisor name,Client Advisor email\n" +
+ roles,
+ "Engagement",
+ );
+
+ assert.equal(parsed.error, null);
+ assert.deepEqual(
+ parsed.rows[0]?.signers.map((signer) => [signer.roleName, signer.email]),
+ [
+ ["Client Advisor", "[email protected]"],
+ ["Client Advisor", "[email protected]"],
+ ],
+ );
+ assert.equal(
+ parseBulkSendCsv(
+ "Client Advisor name,Client Advisor email\nAnn,[email protected]\n",
+ roles,
+ "Engagement",
+ ).error,
+ ambiguousBulkSendColumnsMessage,
+ );
+});
+
+test("a header's extra spacing still matches a role", () => {
+ const parsed = parseBulkSendCsv(
+ " Tenant name ,Tenant email,Landlord name,Landlord email\n" +
+ twoRoles,
+ "Lease",
+ );
+
+ assert.equal(parsed.error, null);
+ assert.equal(parsed.rows[0]?.signers[1]?.email, "[email protected]");
+});
+
+test("a partly filled copy recipient is refused, and a late preview does not match changed copy fields", () => {
+ assert.equal(copyRecipientPairError("", ""), null);
+ assert.equal(
+ copyRecipientPairError("Zofia Copy", "[email protected]"),
+ null,
+ );
+ assert.match(
+ copyRecipientPairError("Zofia Copy", "") ?? "",
+ /copy recipient's email/,
+ );
+ assert.match(
+ copyRecipientPairError("", "[email protected]") ?? "",
+ /copy recipient's name/,
+ );
+
+ const checked = {
+ copyEmail: "",
+ copyName: "",
+ csv: "name,email\nAnn,[email protected]\n",
+ expiresInDays: 14,
+ reminderIntervalDays: 3,
+ requireEmailCode: false,
+ signatureMeaning: null,
+ };
+
+ assert.notEqual(
+ bulkSendPreviewKey(checked),
+ bulkSendPreviewKey({ ...checked, copyEmail: "[email protected]" }),
+ );
+ assert.equal(bulkSendPreviewKey(checked), bulkSendPreviewKey({ ...checked }));
+});
+
+test("the header is refused when a signer's columns are missing", () => {
+ assert.equal(
+ parseBulkSendCsv("name,email\nA,[email protected]\n", twoRoles, "Lease").error,
+ missingBulkSendColumnsMessage,
+ );
+ assert.equal(
+ parseBulkSendCsv("", oneRole, "NDA").error,
+ missingBulkSendColumnsMessage,
+ );
+ assert.equal(
+ parseBulkSendCsv("name,email\n", oneRole, "NDA").error,
+ "Add at least one person.",
+ );
+});
+
+test("a missing name, a bad email, a duplicate row and a duplicate address are skipped", () => {
+ const parsed = parseBulkSendCsv(
+ [
+ "name,email,title",
+ "Alice,[email protected],NDA for Alice",
+ ",[email protected],NDA for Bob",
+ "Cara,not-an-email,NDA for Cara",
+ "Alice,[email protected],NDA for Alice again",
+ "Dana,[email protected],NDA for Dana",
+ "Dana,[email protected],NDA for Dana too",
+ ].join("\n"),
+ oneRole,
+ "Company NDA",
+ );
+ const rows = validateBulkSendRows(parsed.rows);
+
+ assert.deepEqual(
+ rows.map((row) => [row.rowNumber, row.status, row.reason]),
+ [
+ [1, "ok", null],
+ [2, "skipped", "Name is required."],
+ [3, "skipped", "Enter a valid email address."],
+ [4, "skipped", "This row is the same as row 1."],
+ [5, "ok", null],
+ [6, "skipped", "This row is the same as row 5."],
+ ],
+ );
+
+ const sameRow = validateBulkSendRows(
+ parseBulkSendCsv(
+ "Tenant name,Tenant email,Landlord name,Landlord email\nA,[email protected],B,[email protected]\n",
+ twoRoles,
+ "Lease",
+ ).rows,
+ );
+
+ assert.equal(sameRow[0]?.status, "skipped");
+ assert.equal(sameRow[0]?.reason, duplicateSignerEmailMessage);
+});
+
+test("a title that is too long is skipped, and a copy recipient's address cannot also sign", () => {
+ const longTitle = "T".repeat(161);
+ const parsed = parseBulkSendCsv(
+ `name,email,title\nJane,[email protected],${longTitle}\n`,
+ oneRole,
+ "NDA",
+ );
+ const rows = validateBulkSendRows(parsed.rows);
+
+ assert.equal(rows[0]?.status, "skipped");
+ assert.ok(rows[0]?.reason);
+
+ const copyClash = validateBulkSendRows(
+ parseBulkSendCsv("name,email\nJane,[email protected]\n", oneRole, "NDA")
+ .rows,
+ );
+
+ assert.equal(copyClash[0]?.status, "skipped");
+ assert.match(copyClash[0]?.reason ?? "", /copy recipient/);
+});
+
+test("the 201st row is skipped and the first 200 stay", () => {
+ const lines = [
+ "name,email",
+ ...Array.from({ length: MAX_BULK_SEND_ROWS + 1 }, (_, index) => {
+ const n = String(index + 1);
+
+ return `Person ${n},person${n}@example.test`;
+ }),
+ ];
+ const rows = validateBulkSendRows(
+ parseBulkSendCsv(lines.join("\n"), oneRole, "NDA").rows,
+ );
+
+ assert.equal(rows.length, MAX_BULK_SEND_ROWS + 1);
+ assert.equal(rows[MAX_BULK_SEND_ROWS - 1]?.status, "ok");
+ assert.equal(rows[MAX_BULK_SEND_ROWS]?.status, "skipped");
+ assert.equal(rows[MAX_BULK_SEND_ROWS]?.reason, bulkSendCapMessage);
+ assert.equal(
+ rows.filter((row) => row.status === "ok").length,
+ MAX_BULK_SEND_ROWS,
+ );
+});
+
+test("a results CSV records each row without turning a cell into a formula", () => {
+ const csv = serializeBulkSendResultsCsv(
+ [
+ {
+ envelopeId: "e1",
+ envelopePath: "/envelopes/e1",
+ reason: null,
+ rowNumber: 1,
+ signers: [
+ {
+ email: "[email protected]",
+ name: "Jane",
+ roleName: "Signer 1",
+ },
+ ],
+ status: "sent",
+ title: "NDA for Jane",
+ },
+ {
+ envelopeId: null,
+ envelopePath: null,
+ reason: '=HYPERLINK("x")',
+ rowNumber: 2,
+ signers: [
+ {
+ email: "bad",
+ name: "Bob",
+ roleName: "Signer 1",
+ },
+ ],
+ status: "skipped",
+ title: "NDA",
+ },
+ ],
+ ["Signer 1"],
+ );
+
+ assert.match(
+ csv,
+ /^Row,Status,Reason,Title,Signer 1 name,Signer 1 email,Envelope\r\n/,
+ );
+ assert.match(csv, /sent,.*\/envelopes\/e1/);
+ assert.match(csv, /"'=HYPERLINK\(""x""\)"/);
+ assert.equal(
+ serializeCsv([
+ ["a", "b"],
+ ["1", "2"],
+ ]),
+ "a,b\r\n1,2\r\n",
+ );
+});
diff --git a/src/lib/bulk-send-csv.ts b/src/lib/bulk-send-csv.ts
new file mode 100644
index 0000000..4aeabfc
--- /dev/null
+++ b/src/lib/bulk-send-csv.ts
@@ -0,0 +1,524 @@
+import {
+ emailSchema,
+ envelopeTitleSchema,
+ nameSchema,
+} from "./schemas/common.ts";
+import { duplicateSignerEmailMessage } from "./schemas/signer.ts";
+
+// CSV for sending one template to many people: a header that names the
+// template's signer roles, then one envelope per row. The parser is small
+// on purpose, so a quoted comma or a Windows line ending does not need a
+// library.
+
+/** Most envelopes one batch may send. Said on the form. */
+export const MAX_BULK_SEND_ROWS = 200;
+
+export const missingBulkSendColumnsMessage =
+ "This CSV needs a name and email column for each signer. For one signer, use name,email. For more than one, name the columns after each role, such as Tenant name,Tenant email.";
+
+export const ambiguousBulkSendColumnsMessage =
+ "Two signers in this template have names that only differ in spacing, so their columns read the same. Write each signer's columns with the role name exactly as the template spells it, as in the example CSV.";
+
+export const bulkSendCapMessage = `A batch can send at most ${String(MAX_BULK_SEND_ROWS)} envelopes.`;
+
+export type BulkSendSigner = {
+ email: string;
+ name: string;
+ roleName: string;
+};
+
+export type BulkSendRowStatus = "failed" | "ok" | "sent" | "skipped";
+
+export type BulkSendRowResult = {
+ envelopeId: string | null;
+ envelopePath: string | null;
+ reason: string | null;
+ rowNumber: number;
+ signers: BulkSendSigner[];
+ status: BulkSendRowStatus;
+ title: string;
+};
+
+export type BulkSendSummary = {
+ failed: number;
+ ok: number;
+ sent: number;
+ skipped: number;
+};
+
+export type BulkSendResult = {
+ error: string | null;
+ maxRows: number;
+ rows: BulkSendRowResult[];
+ summary: BulkSendSummary;
+ templateId: string;
+ templateName: string;
+};
+
+export type BulkSendRole = {
+ name: string;
+};
+
+type ParsedBulkSendRow = {
+ rowNumber: number;
+ signers: BulkSendSigner[];
+ title: string;
+};
+
+// Template role names may differ only in inner spacing ("Client Advisor"
+// and "Client Advisor" are two roles), so a header is matched with its
+// spacing first and only then with runs of spaces collapsed.
+function exactHeader(value: string): string {
+ return value.trim().toLowerCase();
+}
+
+function looseHeader(value: string): string {
+ return exactHeader(value).replace(/\s+/g, " ");
+}
+
+/** The CSV and copy fields that decide which rows a preview describes. */
+export function bulkSendPreviewKey(input: {
+ copyEmail: string;
+ copyName: string;
+ csv: string;
+ expiresInDays: number;
+ reminderIntervalDays: number | null;
+ requireEmailCode: boolean;
+ signatureMeaning: string | null;
+}): string {
+ return JSON.stringify({
+ copyEmail: input.copyEmail,
+ copyName: input.copyName,
+ csv: input.csv,
+ expiresInDays: input.expiresInDays,
+ reminderIntervalDays: input.reminderIntervalDays,
+ requireEmailCode: input.requireEmailCode,
+ signatureMeaning: input.signatureMeaning,
+ });
+}
+
+/**
+ * A copy recipient needs both a name and an email, or neither. One filled
+ * field is not sent as an empty list: the sender has to finish it or clear
+ * it.
+ */
+export function copyRecipientPairError(
+ name: string,
+ email: string,
+): string | null {
+ const hasName = name.trim().length > 0;
+ const hasEmail = email.trim().length > 0;
+
+ if (hasName === hasEmail) {
+ return null;
+ }
+
+ return hasName
+ ? "Enter the copy recipient's email, or clear the name."
+ : "Enter the copy recipient's name, or clear the email.";
+}
+
+function quoteCsvCell(text: string): string {
+ return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
+}
+
+/**
+ * One CSV line. A cell that a spreadsheet would run as a formula is
+ * prefixed with an apostrophe, so a downloaded value can never execute.
+ */
+function csvCell(value: string): string {
+ return quoteCsvCell(/^[=+\-@\t\r]/.test(value) ? `'${value}` : value);
+}
+
+function joinCsv(
+ rows: readonly (readonly string[])[],
+ cell: (value: string) => string,
+): string {
+ return `${rows.map((row) => row.map(cell).join(",")).join("\r\n")}\r\n`;
+}
+
+export function serializeCsv(rows: readonly (readonly string[])[]): string {
+ return joinCsv(rows, csvCell);
+}
+
+/**
+ * Splits CSV text into rows of cells. Quoted fields may hold commas,
+ * quotes (as ""), CR, LF or CRLF. A UTF-8 BOM at the start is ignored.
+ * Blank lines are dropped.
+ */
+export function parseCsv(text: string): string[][] {
+ const input = text.startsWith("\uFEFF") ? text.slice(1) : text;
+ const rows: string[][] = [];
+ let row: string[] = [];
+ let field = "";
+ let inQuotes = false;
+ let i = 0;
+
+ const pushRow = () => {
+ if (row.some((cell) => cell.trim().length > 0)) {
+ rows.push(row);
+ }
+
+ row = [];
+ };
+
+ while (i < input.length) {
+ const character = input[i]!;
+
+ if (inQuotes) {
+ if (character === '"') {
+ if (input[i + 1] === '"') {
+ field += '"';
+ i += 2;
+ continue;
+ }
+
+ inQuotes = false;
+ i += 1;
+ continue;
+ }
+
+ field += character;
+ i += 1;
+ continue;
+ }
+
+ if (character === '"') {
+ inQuotes = true;
+ i += 1;
+ continue;
+ }
+
+ if (character === ",") {
+ row.push(field);
+ field = "";
+ i += 1;
+ continue;
+ }
+
+ if (character === "\n" || character === "\r") {
+ if (character === "\r" && input[i + 1] === "\n") {
+ i += 1;
+ }
+
+ row.push(field);
+ field = "";
+ pushRow();
+ i += 1;
+ continue;
+ }
+
+ field += character;
+ i += 1;
+ }
+
+ if (inQuotes || field.length > 0 || row.length > 0) {
+ row.push(field);
+ pushRow();
+ }
+
+ return rows;
+}
+
+function findColumn(headers: readonly string[], aliases: readonly string[]) {
+ for (const normalize of [exactHeader, looseHeader]) {
+ const normalized = headers.map(normalize);
+
+ for (const alias of aliases) {
+ const index = normalized.indexOf(normalize(alias));
+
+ if (index >= 0) {
+ return index;
+ }
+ }
+ }
+
+ return -1;
+}
+
+function cellAt(row: readonly string[], index: number): string {
+ return (row[index] ?? "").trim();
+}
+
+export function csvHeadersForRoles(roleNames: readonly string[]): string[] {
+ if (roleNames.length === 1) {
+ return ["name", "email", "title"];
+ }
+
+ return [
+ ...roleNames.flatMap((name) => [`${name} name`, `${name} email`]),
+ "title",
+ ];
+}
+
+/**
+ * The sample CSV the send-many page fills in for the sender. It is read
+ * back by parseBulkSendCsv, never opened in a spreadsheet, so its cells
+ * skip the formula apostrophe: a role named "- Client" must give a
+ * "- Client name" header the importer matches.
+ */
+export function exampleCsvForRoles(roleNames: readonly string[]): string {
+ const headers = csvHeadersForRoles(roleNames);
+
+ if (roleNames.length === 1) {
+ return joinCsv(
+ [headers, ["Jane Smith", "[email protected]", "NDA for Jane Smith"]],
+ quoteCsvCell,
+ );
+ }
+
+ const usedLocalParts = new Set<string>();
+ const sample = [
+ ...roleNames.flatMap((name, index) => {
+ const base = name.trim().replace(/\s+/g, ".").toLowerCase();
+ const localPart = usedLocalParts.has(base)
+ ? `${base}.${String(index + 1)}`
+ : base;
+
+ usedLocalParts.add(localPart);
+
+ return [`${name} person`, `${localPart}@company.com`];
+ }),
+ "Agreement",
+ ];
+
+ return joinCsv([headers, sample], quoteCsvCell);
+}
+
+function nameColumnAliases(roleName: string, soleRole: boolean): string[] {
+ return soleRole ? ["name", `${roleName} name`] : [`${roleName} name`];
+}
+
+function emailColumnAliases(roleName: string, soleRole: boolean): string[] {
+ return soleRole ? ["email", `${roleName} email`] : [`${roleName} email`];
+}
+
+export function parseBulkSendCsv(
+ csv: string,
+ roles: readonly BulkSendRole[],
+ templateName: string,
+): { error: string | null; rows: ParsedBulkSendRow[] } {
+ if (roles.length === 0) {
+ return { error: missingBulkSendColumnsMessage, rows: [] };
+ }
+
+ const table = parseCsv(csv);
+
+ if (table.length === 0) {
+ return { error: missingBulkSendColumnsMessage, rows: [] };
+ }
+
+ const headers = table[0]!;
+ const soleRole = roles.length === 1;
+ const titleIndex = findColumn(headers, ["title"]);
+ const columns = roles.map((role) => ({
+ emailIndex: findColumn(headers, emailColumnAliases(role.name, soleRole)),
+ nameIndex: findColumn(headers, nameColumnAliases(role.name, soleRole)),
+ roleName: role.name,
+ }));
+
+ if (columns.some((column) => column.emailIndex < 0 || column.nameIndex < 0)) {
+ return { error: missingBulkSendColumnsMessage, rows: [] };
+ }
+
+ const claimed = columns.flatMap((column) => [
+ column.emailIndex,
+ column.nameIndex,
+ ]);
+
+ if (new Set(claimed).size !== claimed.length) {
+ return { error: ambiguousBulkSendColumnsMessage, rows: [] };
+ }
+
+ const dataRows = table.slice(1);
+
+ if (dataRows.length === 0) {
+ return { error: "Add at least one person.", rows: [] };
+ }
+
+ const rows = dataRows.map((cells, index) => {
+ const title = titleIndex >= 0 ? cellAt(cells, titleIndex) : "";
+
+ return {
+ rowNumber: index + 1,
+ signers: columns.map((column) => ({
+ email: cellAt(cells, column.emailIndex),
+ name: cellAt(cells, column.nameIndex),
+ roleName: column.roleName,
+ })),
+ title: title.length > 0 ? title : templateName,
+ };
+ });
+
+ return { error: null, rows };
+}
+
+function duplicateRowMessage(rowNumber: number): string {
+ return `This row is the same as row ${String(rowNumber)}.`;
+}
+
+function signerEmailKey(signers: readonly BulkSendSigner[]): string {
+ return signers
+ .map((signer) => signer.email.trim().toLowerCase())
+ .join("\u0000");
+}
+
+export function summarizeBulkSendRows(
+ rows: readonly BulkSendRowResult[],
+): BulkSendSummary {
+ return {
+ failed: rows.filter((row) => row.status === "failed").length,
+ ok: rows.filter((row) => row.status === "ok").length,
+ sent: rows.filter((row) => row.status === "sent").length,
+ skipped: rows.filter((row) => row.status === "skipped").length,
+ };
+}
+
+function skipped(row: ParsedBulkSendRow, reason: string): BulkSendRowResult {
+ return {
+ envelopeId: null,
+ envelopePath: null,
+ reason,
+ rowNumber: row.rowNumber,
+ signers: row.signers,
+ status: "skipped",
+ title: row.title,
+ };
+}
+
+function firstSignerProblem(
+ signers: readonly BulkSendSigner[],
+ copyRecipientEmails: ReadonlySet<string>,
+): string | null {
+ const emails = new Set<string>();
+
+ for (const signer of signers) {
+ if (signer.name.length === 0) {
+ return "Name is required.";
+ }
+
+ const named = nameSchema.safeParse(signer.name);
+
+ if (!named.success) {
+ return named.error.issues[0]?.message ?? "Name is required.";
+ }
+
+ if (signer.email.length === 0) {
+ return "Email is required.";
+ }
+
+ const addressed = emailSchema.safeParse(signer.email);
+
+ if (!addressed.success) {
+ return "Enter a valid email address.";
+ }
+
+ const email = addressed.data.toLowerCase();
+
+ if (emails.has(email)) {
+ return duplicateSignerEmailMessage;
+ }
+
+ if (copyRecipientEmails.has(email)) {
+ return "This address is already a signer or a copy recipient.";
+ }
+
+ emails.add(email);
+ }
+
+ return null;
+}
+
+/**
+ * Marks rows that cannot be sent: a missing or invalid name or email, a
+ * duplicate of an earlier row, a title the envelope cannot keep, or a row
+ * past the batch cap. Does not create anything.
+ */
+export function validateBulkSendRows(
+ rows: readonly ParsedBulkSendRow[],
+ copyRecipientEmails: readonly string[] = [],
+): BulkSendRowResult[] {
+ const seen = new Map<string, number>();
+ const copyEmails = new Set(
+ copyRecipientEmails.map((email) => email.trim().toLowerCase()),
+ );
+ const results: BulkSendRowResult[] = [];
+
+ for (const [index, row] of rows.entries()) {
+ if (index >= MAX_BULK_SEND_ROWS) {
+ results.push(skipped(row, bulkSendCapMessage));
+ continue;
+ }
+
+ const title = envelopeTitleSchema.safeParse(row.title);
+
+ if (!title.success) {
+ results.push(
+ skipped(
+ row,
+ title.error.issues[0]?.message ?? "Give the envelope a title.",
+ ),
+ );
+ continue;
+ }
+
+ const signerProblem = firstSignerProblem(row.signers, copyEmails);
+
+ if (signerProblem) {
+ results.push(skipped(row, signerProblem));
+ continue;
+ }
+
+ const key = signerEmailKey(row.signers);
+ const earlier = seen.get(key);
+
+ if (earlier !== undefined) {
+ results.push(skipped(row, duplicateRowMessage(earlier)));
+ continue;
+ }
+
+ seen.set(key, row.rowNumber);
+ results.push({
+ envelopeId: null,
+ envelopePath: null,
+ reason: null,
+ rowNumber: row.rowNumber,
+ signers: row.signers.map((signer) => ({
+ email: emailSchema.parse(signer.email),
+ name: nameSchema.parse(signer.name),
+ roleName: signer.roleName,
+ })),
+ status: "ok",
+ title: title.data,
+ });
+ }
+
+ return results;
+}
+
+export function serializeBulkSendResultsCsv(
+ rows: readonly BulkSendRowResult[],
+ roleNames: readonly string[],
+): string {
+ const headers = [
+ "Row",
+ "Status",
+ "Reason",
+ "Title",
+ ...roleNames.flatMap((name) => [`${name} name`, `${name} email`]),
+ "Envelope",
+ ];
+ const body = rows.map((row) => [
+ String(row.rowNumber),
+ row.status,
+ row.reason ?? "",
+ row.title,
+ ...roleNames.flatMap((_, index) => [
+ row.signers[index]?.name ?? "",
+ row.signers[index]?.email ?? "",
+ ]),
+ row.envelopePath ?? "",
+ ]);
+
+ return serializeCsv([headers, ...body]);
+}
diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.ts
new file mode 100644
index 0000000..b4fbc78
--- /dev/null
+++ b/src/lib/bulk-send.dbtest.ts
@@ -0,0 +1,929 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, before, test } from "node:test";
+
+import { PDFDocument } from "pdf-lib";
+import type pg from "pg";
+import { ZodError } from "zod";
+
+import {
+ bulkSendBatchMismatchMessage,
+ bulkSendFromTemplate,
+ bulkSendInvitationUnconfirmedMessage,
+ BulkSendError,
+ missingBulkSendBatchKeyMessage,
+} from "./bulk-send.ts";
+import { MAX_BULK_SEND_ROWS } from "./bulk-send-csv.ts";
+import { openTestDatabase } from "./db/test-database.ts";
+import {
+ createDraftEnvelope,
+ getEnvelopeDetailDataForUser,
+ getPrepareEnvelopeDataForUser,
+ replaceDraftEnvelopeFields,
+ replaceDraftEnvelopeSigners,
+} from "./envelopes.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import { saveEnvelopeAsTemplate, TemplateError } from "./templates.ts";
+
+// Bulk send against a real Postgres: a CSV of people becomes envelopes
+// sent from a template, with the template's fields and the chosen
+// settings. Run with `npm run test:db`.
+
+const SETTINGS = [
+ "APP_URL",
+ "DATABASE_URL",
+ "EMAIL_CAPTURE_DIR",
+ "EMAIL_DRIVER",
+ "STORAGE_DRIVER",
+ "STORAGE_LOCAL_DIR",
+] as const;
+
+let database: pg.Pool;
+let storageDir: string;
+let storageService: StorageService;
+let sourcePdf: Uint8Array;
+let workDir: string;
+const createdUsers: string[] = [];
+const settingsBefore = new Map<string, string | undefined>();
+
+before(async () => {
+ database = await openTestDatabase();
+ workDir = await mkdtemp(path.join(tmpdir(), "signudoc-bulk-send-"));
+ storageDir = path.join(workDir, "storage");
+ storageService = createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
+ });
+
+ for (const name of SETTINGS) {
+ settingsBefore.set(name, process.env[name]);
+ }
+
+ process.env.APP_URL = "http://localhost:3000";
+ process.env.DATABASE_URL =
+ process.env.E2E_DATABASE_URL ??
+ "postgres://signudoc:[email protected]:5432/signudoc_e2e";
+ process.env.EMAIL_CAPTURE_DIR = path.join(workDir, "outbox");
+ process.env.EMAIL_DRIVER = "capture";
+ process.env.STORAGE_DRIVER = "local";
+ process.env.STORAGE_LOCAL_DIR = storageDir;
+
+ const pdf = await PDFDocument.create();
+
+ pdf.addPage([612, 792]);
+ pdf.addPage([612, 792]);
+ sourcePdf = await pdf.save();
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+
+ for (const [name, value] of settingsBefore) {
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ }
+
+ await rm(workDir, { force: true, recursive: true });
+});
+
+async function createUser(): Promise<string> {
+ const userId = randomUUID();
+
+ createdUsers.push(userId);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,
+ [userId, `${userId}@example.test`],
+ );
+
+ return userId;
+}
+
+function field(
+ signerId: string,
+ type: string,
+ y: number,
+ extra: Record<string, unknown> = {},
+) {
+ return {
+ height: 0.03,
+ page: 1,
+ required: true,
+ signerId,
+ type,
+ width: 0.2,
+ x: 0.1,
+ y,
+ ...extra,
+ };
+}
+
+const options = () => ({ database, storageService });
+
+async function createTwoRoleTemplate(userId: string) {
+ const draft = await createDraftEnvelope(
+ userId,
+ {
+ sourcePdf: { body: sourcePdf, filename: "lease.pdf" },
+ title: "Lease for 12 Harbour Road",
+ },
+ options(),
+ );
+ const envelopeId = draft.envelope.id;
+ const saved = await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ {
+ signers: [
+ { email: "[email protected]", name: "Riley Recipient" },
+ { email: "[email protected]", name: "Casey Second" },
+ ],
+ },
+ database,
+ );
+ const [riley, casey] = saved.signers.map((signer) => signer.id);
+
+ await replaceDraftEnvelopeFields(
+ userId,
+ envelopeId,
+ {
+ fields: [
+ field(riley!, "signature", 0.1),
+ field(casey!, "signature", 0.15, { page: 2 }),
+ field(riley!, "text", 0.2, { label: "Unit number", required: false }),
+ ],
+ },
+ database,
+ );
+
+ return saveEnvelopeAsTemplate(
+ userId,
+ envelopeId,
+ { name: "Residential lease", roleNames: ["Tenant", "Landlord"] },
+ options(),
+ );
+}
+
+async function createOneRoleTemplate(userId: string) {
+ const draft = await createDraftEnvelope(
+ userId,
+ {
+ sourcePdf: { body: sourcePdf, filename: "nda.pdf" },
+ title: "Company NDA",
+ },
+ options(),
+ );
+ const saved = await replaceDraftEnvelopeSigners(
+ userId,
+ draft.envelope.id,
+ {
+ signers: [{ email: "[email protected]", name: "Riley Recipient" }],
+ },
+ database,
+ );
+
+ await replaceDraftEnvelopeFields(
+ userId,
+ draft.envelope.id,
+ { fields: [field(saved.signers[0]!.id, "signature", 0.1)] },
+ database,
+ );
+
+ return saveEnvelopeAsTemplate(
+ userId,
+ draft.envelope.id,
+ { name: "Company NDA", roleNames: ["Signer"] },
+ options(),
+ );
+}
+
+async function countEnvelopes(userId: string): Promise<number> {
+ const result = await database.query<{ total: number }>(
+ `select count(*)::int as total from envelopes where user_id = $1`,
+ [userId],
+ );
+
+ return result.rows[0]!.total;
+}
+
+async function countSent(userId: string): Promise<number> {
+ const result = await database.query<{ total: number }>(
+ `select count(*)::int as total from envelopes where user_id = $1 and status = 'sent'`,
+ [userId],
+ );
+
+ return result.rows[0]!.total;
+}
+
+function senderFor(userId: string) {
+ return { email: `${userId}@example.test`, name: "Sam Sender" };
+}
+
+function confirmBody(
+ csv: string,
+ extra: Record<string, unknown> = {},
+): Record<string, unknown> {
+ return {
+ batchKey: randomUUID(),
+ confirm: true,
+ csv,
+ permittedUseConfirmed: true,
+ ...extra,
+ };
+}
+
+function twoRoleCsv(rows: readonly (readonly string[])[]): string {
+ return [
+ "Tenant name,Tenant email,Landlord name,Landlord email,title",
+ ...rows.map((row) => row.join(",")),
+ ].join("\n");
+}
+
+async function capturedInvitations(): Promise<
+ { template: string; to: string[] }[]
+> {
+ const names = await readdir(process.env.EMAIL_CAPTURE_DIR!).catch(() => []);
+ const emails = await Promise.all(
+ names
+ .filter((name) => name.endsWith(".json"))
+ .map(async (name) =>
+ JSON.parse(
+ await readFile(
+ path.join(process.env.EMAIL_CAPTURE_DIR!, name),
+ "utf8",
+ ),
+ ),
+ ),
+ );
+
+ return emails.filter((email) => email.template === "signing_invitation");
+}
+
+test("a 3-row batch creates and sends three envelopes with the template's fields and settings", async () => {
+ const userId = await createUser();
+ const template = await createTwoRoleTemplate(userId);
+ const before = await countEnvelopes(userId);
+ const copyEmail = `zofia-${randomUUID()}@example.test`;
+ const people = [
+ [
+ "Tess One",
+ `tess1-${randomUUID()}@example.test`,
+ "Lou One",
+ `lou1-${randomUUID()}@example.test`,
+ "Lease 1",
+ ],
+ [
+ "Tess Two",
+ `tess2-${randomUUID()}@example.test`,
+ "Lou Two",
+ `lou2-${randomUUID()}@example.test`,
+ "Lease 2",
+ ],
+ [
+ "Tess Three",
+ `tess3-${randomUUID()}@example.test`,
+ "Lou Three",
+ `lou3-${randomUUID()}@example.test`,
+ "Lease 3",
+ ],
+ ] as const;
+ const result = await bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ ...confirmBody(twoRoleCsv(people), {
+ copyRecipients: [{ email: copyEmail, name: "Zofia Copy" }],
+ expiresInDays: 14,
+ reminderIntervalDays: 3,
+ requireEmailCode: true,
+ }),
+ },
+ { ...options(), sender: senderFor(userId) },
+ );
+
+ assert.equal(result.summary.sent, 3);
+ assert.equal(result.summary.skipped, 0);
+ assert.equal(result.summary.failed, 0);
+ assert.equal(await countEnvelopes(userId), before + 3);
+ assert.equal(await countSent(userId), 3);
+
+ for (const [index, row] of result.rows.entries()) {
+ assert.equal(row.status, "sent");
+ assert.ok(row.envelopeId);
+ assert.equal(row.envelopePath, `/envelopes/${row.envelopeId}`);
+
+ const envelope = await database.query<{
+ expires_at: number;
+ reminder_interval_days: number | null;
+ sent_at: number;
+ status: string;
+ title: string;
+ }>(
+ `
+ select status, title, sent_at, expires_at, reminder_interval_days
+ from envelopes where id = $1
+ `,
+ [row.envelopeId],
+ );
+ const stored = envelope.rows[0]!;
+
+ assert.equal(stored.status, "sent");
+ assert.equal(stored.title, people[index]![4]);
+ assert.equal(stored.reminder_interval_days, 3);
+ assert.equal(stored.expires_at - stored.sent_at, 14 * 24 * 60 * 60);
+
+ const prepared = await getPrepareEnvelopeDataForUser(
+ userId,
+ row.envelopeId!,
+ { database },
+ );
+
+ assert.ok(prepared);
+ assert.deepEqual(
+ prepared.signers.map((signer) => [signer.name, signer.email]),
+ [
+ [people[index]![0], people[index]![1]],
+ [people[index]![2], people[index]![3]],
+ ],
+ );
+
+ const [tenant] = prepared.signers;
+ const summary = prepared.fields
+ .map((placed) => ({
+ label: placed.label,
+ page: placed.page,
+ signer: placed.signerId === tenant?.id ? "tenant" : "landlord",
+ type: placed.type,
+ }))
+ .sort((left, right) =>
+ `${left.type}${left.label ?? ""}`.localeCompare(
+ `${right.type}${right.label ?? ""}`,
+ ),
+ );
+
+ assert.deepEqual(summary, [
+ {
+ label: undefined,
+ page: 1,
+ signer: "tenant",
+ type: "signature",
+ },
+ {
+ label: undefined,
+ page: 2,
+ signer: "landlord",
+ type: "signature",
+ },
+ {
+ label: "Unit number",
+ page: 1,
+ signer: "tenant",
+ type: "text",
+ },
+ ]);
+
+ const checks = await database.query<{
+ email: string;
+ require_email_code: boolean;
+ role: string;
+ }>(
+ `
+ select email, require_email_code, role from signers
+ where envelope_id = $1 order by sign_order
+ `,
+ [row.envelopeId],
+ );
+
+ assert.deepEqual(
+ checks.rows.map((signer) => [
+ signer.role,
+ signer.require_email_code,
+ signer.email,
+ ]),
+ [
+ ["signer", true, people[index]![1]],
+ ["signer", true, people[index]![3]],
+ ["cc", false, copyEmail],
+ ],
+ );
+
+ const detail = await getEnvelopeDetailDataForUser(
+ userId,
+ row.envelopeId!,
+ database,
+ );
+
+ assert.equal(detail?.copyRecipients[0]?.email, copyEmail);
+ assert.equal(
+ (
+ await database.query(
+ `select 1 from audit_events where envelope_id = $1 and event = 'sent'`,
+ [row.envelopeId],
+ )
+ ).rowCount,
+ 1,
+ );
+ }
+
+ const invitations = await capturedInvitations();
+ const firstSignerEmails = people.map((row) => row[1]);
+
+ assert.equal(
+ invitations.filter((email) =>
+ firstSignerEmails.some((address) => email.to.includes(address)),
+ ).length,
+ 3,
+ );
+});
+
+test("a bad row is skipped while the rest send", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const before = await countEnvelopes(userId);
+ const goodOne = `ann-${randomUUID()}@example.test`;
+ const goodTwo = `cara-${randomUUID()}@example.test`;
+ const result = await bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ ...confirmBody(
+ [
+ "name,email",
+ `Ann,${goodOne}`,
+ "Bob,not-an-email",
+ `Cara,${goodTwo}`,
+ ].join("\n"),
+ ),
+ },
+ { ...options(), sender: senderFor(userId) },
+ );
+
+ assert.deepEqual(
+ result.rows.map((row) => [row.status, row.reason, Boolean(row.envelopeId)]),
+ [
+ ["sent", null, true],
+ ["skipped", "Enter a valid email address.", false],
+ ["sent", null, true],
+ ],
+ );
+ assert.equal(result.summary.sent, 2);
+ assert.equal(result.summary.skipped, 1);
+ assert.equal(await countEnvelopes(userId), before + 2);
+ assert.equal(await countSent(userId), 2);
+});
+
+test("the cap is enforced without creating envelopes", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const before = await countEnvelopes(userId);
+ const csv = [
+ "name,email",
+ ...Array.from({ length: MAX_BULK_SEND_ROWS + 1 }, (_, index) => {
+ const n = String(index + 1);
+
+ return `Person ${n},person${n}-${userId.slice(0, 8)}@example.test`;
+ }),
+ ].join("\n");
+ const preview = await bulkSendFromTemplate(
+ userId,
+ template.id,
+ { csv },
+ options(),
+ );
+
+ assert.equal(preview.summary.ok, MAX_BULK_SEND_ROWS);
+ assert.equal(preview.summary.skipped, 1);
+ assert.equal(preview.rows[MAX_BULK_SEND_ROWS]?.status, "skipped");
+ assert.match(preview.rows[MAX_BULK_SEND_ROWS]?.reason ?? "", /200/);
+ assert.equal(await countEnvelopes(userId), before);
+});
+
+test("another user's template is refused", async () => {
+ const owner = await createUser();
+ const stranger = await createUser();
+ const template = await createOneRoleTemplate(owner);
+ const csv = "name,email\nAnn,[email protected]\n";
+
+ await assert.rejects(
+ bulkSendFromTemplate(
+ stranger,
+ template.id,
+ { ...confirmBody(csv) },
+ { ...options(), sender: senderFor(stranger) },
+ ),
+ (error: unknown) =>
+ error instanceof TemplateError && error.statusCode === 404,
+ );
+ assert.equal(await countEnvelopes(stranger), 0);
+
+ const preview = await bulkSendFromTemplate(
+ stranger,
+ template.id,
+ { csv },
+ options(),
+ ).then(
+ () => null,
+ (error: unknown) => error,
+ );
+
+ assert.ok(preview instanceof TemplateError);
+ assert.equal(preview.statusCode, 404);
+});
+
+test("Part 11 mode skips a row whose signer has no verified account", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const before = await countEnvelopes(userId);
+ const previous = await database.query<{ part11_mode: boolean }>(
+ `select part11_mode from app_settings where id`,
+ );
+
+ await database.query(
+ `
+ insert into app_settings (id, signup_mode, created_at, updated_at, part11_mode)
+ values (true, 'open', 1, 1, true)
+ on conflict (id) do update set part11_mode = true
+ `,
+ );
+
+ try {
+ const result = await bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ ...confirmBody(`name,email\nAda,ada-${randomUUID()}@example.test\n`, {
+ signatureMeaning: "approval",
+ }),
+ },
+ { ...options(), sender: senderFor(userId) },
+ );
+
+ assert.equal(result.summary.sent, 0);
+ assert.equal(result.summary.skipped, 1);
+ assert.match(result.rows[0]?.reason ?? "", /needs an account/);
+ assert.equal(await countEnvelopes(userId), before);
+ } finally {
+ if (previous.rowCount) {
+ await database.query(
+ `update app_settings set part11_mode = $1 where id`,
+ [previous.rows[0]!.part11_mode],
+ );
+ } else {
+ await database.query(`delete from app_settings where id`);
+ }
+ }
+});
+
+test("sending without the permitted-use confirmation is refused, and so is an empty CSV", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+
+ await assert.rejects(
+ bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ batchKey: randomUUID(),
+ confirm: true,
+ csv: "name,email\nAnn,[email protected]\n",
+ },
+ { ...options(), sender: senderFor(userId) },
+ ),
+ (error: unknown) =>
+ error instanceof BulkSendError && error.statusCode === 400,
+ );
+ await assert.rejects(
+ bulkSendFromTemplate(userId, template.id, { csv: "" }, options()),
+ ZodError,
+ );
+ await assert.rejects(
+ bulkSendFromTemplate(userId, template.id, { csv: "nope" }, options()),
+ (error: unknown) =>
+ error instanceof BulkSendError && error.statusCode === 400,
+ );
+ await assert.rejects(
+ bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ confirm: true,
+ csv: "name,email\nAnn,[email protected]\n",
+ permittedUseConfirmed: true,
+ },
+ { ...options(), sender: senderFor(userId) },
+ ),
+ (error: unknown) =>
+ error instanceof BulkSendError &&
+ error.message === missingBulkSendBatchKeyMessage,
+ );
+});
+
+async function createUnsignedTemplate(userId: string) {
+ const draft = await createDraftEnvelope(
+ userId,
+ {
+ sourcePdf: { body: sourcePdf, filename: "nda.pdf" },
+ title: "Unfinished NDA",
+ },
+ options(),
+ );
+ const saved = await replaceDraftEnvelopeSigners(
+ userId,
+ draft.envelope.id,
+ {
+ signers: [{ email: "[email protected]", name: "Riley Recipient" }],
+ },
+ database,
+ );
+
+ await replaceDraftEnvelopeFields(
+ userId,
+ draft.envelope.id,
+ {
+ fields: [field(saved.signers[0]!.id, "text", 0.1, { label: "Note" })],
+ },
+ database,
+ );
+
+ return saveEnvelopeAsTemplate(
+ userId,
+ draft.envelope.id,
+ { name: "Unfinished NDA", roleNames: ["Signer"] },
+ options(),
+ );
+}
+
+test("a template with no signature field is refused before any row is ready", async () => {
+ const userId = await createUser();
+ const template = await createUnsignedTemplate(userId);
+ const csv = "name,email\nAnn,[email protected]\n";
+
+ await assert.rejects(
+ bulkSendFromTemplate(userId, template.id, { csv }, options()),
+ (error: unknown) =>
+ error instanceof BulkSendError &&
+ error.statusCode === 400 &&
+ /Signature field/.test(error.message),
+ );
+ await assert.rejects(
+ bulkSendFromTemplate(userId, template.id, confirmBody(csv), {
+ ...options(),
+ sender: senderFor(userId),
+ }),
+ (error: unknown) =>
+ error instanceof BulkSendError && /Signature field/.test(error.message),
+ );
+ assert.equal(await countEnvelopes(userId), 1);
+});
+
+test("confirming the same batch key does not send the envelopes again", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const batchKey = randomUUID();
+ const csv = `name,email\nAnn,ann-${randomUUID()}@example.test\nCara,cara-${randomUUID()}@example.test\n`;
+ const body = {
+ batchKey,
+ confirm: true,
+ csv,
+ permittedUseConfirmed: true,
+ };
+ const first = await bulkSendFromTemplate(userId, template.id, body, {
+ ...options(),
+ sender: senderFor(userId),
+ });
+ const afterFirst = await countSent(userId);
+
+ assert.equal(first.summary.sent, 2);
+ assert.equal(afterFirst, 2);
+
+ const second = await bulkSendFromTemplate(userId, template.id, body, {
+ ...options(),
+ sender: senderFor(userId),
+ });
+
+ assert.equal(second.summary.sent, 2);
+ assert.deepEqual(
+ second.rows.map((row) => row.envelopeId),
+ first.rows.map((row) => row.envelopeId),
+ );
+ assert.equal(await countSent(userId), afterFirst);
+ assert.equal(await countEnvelopes(userId), afterFirst + 1);
+});
+
+test("a retry of a batch that already sent a row resumes without a duplicate", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const batchKey = randomUUID();
+ const csv = `name,email\nAnn,ann-${randomUUID()}@example.test\n`;
+ const body = {
+ batchKey,
+ confirm: true,
+ csv,
+ permittedUseConfirmed: true,
+ };
+ const first = await bulkSendFromTemplate(userId, template.id, body, {
+ ...options(),
+ sender: senderFor(userId),
+ });
+
+ assert.equal(first.rows[0]?.status, "sent");
+ assert.ok(first.rows[0]?.envelopeId);
+
+ await database.query(
+ `
+ update bulk_send_batch_rows
+ set status = 'processing'
+ where envelope_id = $1
+ `,
+ [first.rows[0].envelopeId],
+ );
+
+ const retry = await bulkSendFromTemplate(userId, template.id, body, {
+ ...options(),
+ sender: senderFor(userId),
+ });
+
+ assert.equal(retry.rows[0]?.status, "sent");
+ assert.equal(retry.rows[0]?.envelopeId, first.rows[0]?.envelopeId);
+ assert.equal(
+ retry.rows[0]?.signers[0]?.email,
+ first.rows[0]?.signers[0]?.email,
+ );
+ assert.equal(await countSent(userId), 1);
+ assert.equal(await countEnvelopes(userId), 2);
+});
+
+test("a retry does not report sent until the invitation is recorded", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const batchKey = randomUUID();
+ const csv = `name,email\nAnn,ann-${randomUUID()}@example.test\n`;
+ const body = {
+ batchKey,
+ confirm: true,
+ csv,
+ permittedUseConfirmed: true,
+ };
+ const first = await bulkSendFromTemplate(userId, template.id, body, {
+ ...options(),
+ sender: senderFor(userId),
+ });
+
+ assert.equal(first.rows[0]?.status, "sent");
+ assert.ok(first.rows[0]?.envelopeId);
+
+ await database.query(
+ `
+ update bulk_send_batch_rows
+ set status = 'processing', reason = null
+ where envelope_id = $1
+ `,
+ [first.rows[0].envelopeId],
+ );
+ await database.query(
+ `
+ delete from audit_events
+ where envelope_id = $1 and event = 'email_sent'
+ `,
+ [first.rows[0].envelopeId],
+ );
+
+ const retry = await bulkSendFromTemplate(userId, template.id, body, {
+ ...options(),
+ sender: senderFor(userId),
+ });
+
+ assert.equal(retry.rows[0]?.status, "failed");
+ assert.equal(retry.rows[0]?.reason, bulkSendInvitationUnconfirmedMessage);
+ assert.equal(retry.rows[0]?.envelopeId, first.rows[0]?.envelopeId);
+ assert.equal(await countSent(userId), 1);
+ assert.equal(await countEnvelopes(userId), 2);
+});
+
+test("a stored batch row does not keep signer names or emails", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const email = `ann-${randomUUID()}@example.test`;
+ const result = await bulkSendFromTemplate(
+ userId,
+ template.id,
+ confirmBody(`name,email\nAnn Example,${email}\n`),
+ { ...options(), sender: senderFor(userId) },
+ );
+
+ assert.equal(result.rows[0]?.status, "sent");
+
+ const stored = await database.query(
+ `
+ select batch_key, request_fingerprint, status, reason
+ from bulk_send_batches b
+ join bulk_send_batch_rows r on r.batch_id = b.id
+ where r.envelope_id = $1
+ `,
+ [result.rows[0]?.envelopeId],
+ );
+
+ assert.equal(stored.rowCount, 1);
+ assert.equal(JSON.stringify(stored.rows).includes(email), false);
+ assert.equal(JSON.stringify(stored.rows).includes("Ann Example"), false);
+});
+
+test("a different list with the same batch key is refused", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const batchKey = randomUUID();
+ const firstCsv = `name,email\nAnn,ann-${randomUUID()}@example.test\n`;
+
+ await bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ batchKey,
+ confirm: true,
+ csv: firstCsv,
+ permittedUseConfirmed: true,
+ },
+ { ...options(), sender: senderFor(userId) },
+ );
+
+ await assert.rejects(
+ bulkSendFromTemplate(
+ userId,
+ template.id,
+ {
+ batchKey,
+ confirm: true,
+ csv: `name,email\nCara,cara-${randomUUID()}@example.test\n`,
+ permittedUseConfirmed: true,
+ },
+ { ...options(), sender: senderFor(userId) },
+ ),
+ (error: unknown) =>
+ error instanceof BulkSendError &&
+ error.message === bulkSendBatchMismatchMessage,
+ );
+});
+
+test("an unexpected row failure is logged and kept for the sender", async () => {
+ const userId = await createUser();
+ const template = await createOneRoleTemplate(userId);
+ const errors: unknown[] = [];
+ const originalError = console.error;
+ const failingStorage: StorageService = {
+ deleteObject: (key) => storageService.deleteObject(key),
+ getObject: async () => {
+ throw new Error("disk full");
+ },
+ getObjectStream: (key) => storageService.getObjectStream(key),
+ headObject: (key) => storageService.headObject(key),
+ putObject: (input) => storageService.putObject(input),
+ };
+
+ console.error = (...args: unknown[]) => {
+ errors.push(args);
+ };
+
+ try {
+ const result = await bulkSendFromTemplate(
+ userId,
+ template.id,
+ confirmBody(`name,email\nAnn,ann-${randomUUID()}@example.test\n`),
+ {
+ database,
+ sender: senderFor(userId),
+ storageService: failingStorage,
+ },
+ );
+
+ assert.equal(result.rows[0]?.status, "failed");
+ assert.equal(result.rows[0]?.reason, "Unable to send this envelope.");
+ assert.equal(
+ errors.some((entry) =>
+ JSON.stringify(entry).includes("template_bulk_send_row_failure"),
+ ),
+ true,
+ );
+ assert.equal(
+ errors.some(
+ (entry) =>
+ Array.isArray(entry) &&
+ entry.some(
+ (value) => value instanceof Error && value.message === "disk full",
+ ),
+ ),
+ true,
+ );
+ } finally {
+ console.error = originalError;
+ }
+});
diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.ts
new file mode 100644
index 0000000..8e1e2db
--- /dev/null
+++ b/src/lib/bulk-send.ts
@@ -0,0 +1,749 @@
+import { createHash, randomUUID } from "node:crypto";
+
+import { ZodError } from "zod";
+
+import {
+ type BulkSendResult,
+ type BulkSendRowResult,
+ MAX_BULK_SEND_ROWS,
+ parseBulkSendCsv,
+ summarizeBulkSendRows,
+ validateBulkSendRows,
+} from "./bulk-send-csv.ts";
+import {
+ type DbExecutor,
+ type DbPool,
+ getDb,
+ queryMany,
+ queryOne,
+} from "./db/connection.ts";
+import {
+ EnvelopeMutationError,
+ getPrepareEnvelopeDataForUser,
+ replaceDraftEnvelopeSigners,
+ sendDraftEnvelope,
+} from "./envelopes.ts";
+import { describePart11SignerProblem, findSignerAccounts } from "./part11.ts";
+import {
+ bulkSendRequestSchema,
+ type BulkSendRequest,
+} from "./schemas/bulk-send.ts";
+import { logRouteError } from "./security/logging.ts";
+import { DocumentImportError } from "./services/document-import.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import { readStoredSettings } from "./settings.ts";
+import {
+ createDraftFromTemplate,
+ describeUnsendableTemplate,
+ getTemplateForBulkSend,
+ TemplateError,
+} from "./templates.ts";
+import { type SignatureMeaning } from "./types/domain.ts";
+
+// Send one template to many people: each CSV row becomes its own envelope,
+// created from the template and sent the same way a hand-sent draft is.
+// Rows are checked first. One row that fails does not take the others with it.
+// A confirmed batch is stored by key so a retry does not send the same
+// envelopes again.
+
+export const missingBulkSendBatchKeyMessage =
+ "This send is missing its batch key.";
+
+export const bulkSendBatchMismatchMessage =
+ "This batch key was used with a different list.";
+
+export const bulkSendInvitationUnconfirmedMessage =
+ "This envelope was marked sent but the invitation was not recorded. Check your documents before sending this row again.";
+
+export class BulkSendError extends Error {
+ readonly statusCode: number;
+
+ constructor(message: string, statusCode: number) {
+ super(message);
+ this.name = "BulkSendError";
+ this.statusCode = statusCode;
+ }
+}
+
+export type BulkSendSender = {
+ email: string;
+ ipAddress?: string | null;
+ name: string;
+ userAgent?: string | null;
+};
+
+type BulkSendOptions = {
+ database?: DbPool;
+ sender?: BulkSendSender;
+ storageService?: StorageService;
+};
+
+type StoredBatch = {
+ id: string;
+ requestFingerprint: string;
+ rows: Map<number, StoredBatchRow>;
+};
+
+type StoredBatchRow = {
+ envelopeId: string | null;
+ reason: string | null;
+ status: "failed" | "processing" | "sent" | "skipped";
+};
+
+type SendRowContext = {
+ batchId: string;
+ copyRecipients: NonNullable<BulkSendRequest["copyRecipients"]>;
+ database: DbPool;
+ expiresInDays: BulkSendRequest["expiresInDays"];
+ progress: { envelopeId: string | null };
+ reminderIntervalDays: BulkSendRequest["reminderIntervalDays"];
+ requireEmailCode: boolean;
+ sender: BulkSendSender;
+ signatureMeaning: SignatureMeaning | null;
+ storageService: StorageService;
+ templateId: string;
+ userId: string;
+};
+
+const TERMINAL_ROW_STATUSES = new Set(["failed", "sent", "skipped"]);
+
+function describeSendFailure(error: unknown): string {
+ if (error instanceof ZodError) {
+ return error.issues[0]?.message ?? "Invalid signer details.";
+ }
+
+ if (
+ error instanceof BulkSendError ||
+ error instanceof TemplateError ||
+ error instanceof EnvelopeMutationError ||
+ error instanceof DocumentImportError
+ ) {
+ return error.message;
+ }
+
+ return "Unable to send this envelope.";
+}
+
+function isExpectedSendFailure(error: unknown): boolean {
+ return (
+ error instanceof ZodError ||
+ error instanceof TemplateError ||
+ error instanceof EnvelopeMutationError ||
+ error instanceof DocumentImportError ||
+ error instanceof BulkSendError
+ );
+}
+
+function withReason(row: BulkSendRowResult, reason: string): BulkSendRowResult {
+ return {
+ ...row,
+ envelopeId: null,
+ envelopePath: null,
+ reason,
+ status: "skipped",
+ };
+}
+
+async function applyPart11Problems(
+ rows: readonly BulkSendRowResult[],
+ signatureMeaning: SignatureMeaning | null | undefined,
+ database: DbExecutor,
+): Promise<BulkSendRowResult[]> {
+ const emails = rows.flatMap((row) =>
+ row.status === "ok" ? row.signers.map((signer) => signer.email) : [],
+ );
+ const accounts = await findSignerAccounts(emails, database);
+
+ return rows.map((row) => {
+ if (row.status !== "ok") {
+ return row;
+ }
+
+ for (const signer of row.signers) {
+ const problem = describePart11SignerProblem(
+ {
+ email: signer.email,
+ name: signer.name,
+ signatureMeaning: signatureMeaning ?? null,
+ },
+ accounts.get(signer.email.toLowerCase()),
+ );
+
+ if (problem) {
+ return withReason(row, problem);
+ }
+ }
+
+ return row;
+ });
+}
+
+function envelopePath(envelopeId: string): string {
+ return `/envelopes/${envelopeId}`;
+}
+
+function fingerprintBulkSendRequest(
+ templateId: string,
+ input: BulkSendRequest,
+): string {
+ return createHash("sha256")
+ .update(
+ JSON.stringify({
+ copyRecipients: input.copyRecipients ?? [],
+ csv: input.csv,
+ expiresInDays: input.expiresInDays ?? null,
+ reminderIntervalDays: input.reminderIntervalDays ?? null,
+ requireEmailCode: input.requireEmailCode === true,
+ signatureMeaning: input.signatureMeaning ?? null,
+ templateId,
+ }),
+ )
+ .digest("hex");
+}
+
+function sentRow(
+ row: BulkSendRowResult,
+ envelopeId: string,
+): BulkSendRowResult {
+ return {
+ ...row,
+ envelopeId,
+ envelopePath: envelopePath(envelopeId),
+ reason: null,
+ status: "sent",
+ };
+}
+
+function failedRow(
+ row: BulkSendRowResult,
+ envelopeId: string | null,
+ error: unknown,
+): BulkSendRowResult {
+ return {
+ ...row,
+ envelopeId,
+ envelopePath: envelopeId ? envelopePath(envelopeId) : null,
+ reason: describeSendFailure(error),
+ status: "failed",
+ };
+}
+
+async function withBatchLock<T>(
+ pool: DbPool,
+ lockKey: string,
+ run: () => Promise<T>,
+): Promise<T> {
+ const client = await pool.connect();
+
+ try {
+ await client.query("SELECT pg_advisory_lock(hashtextextended($1, 19))", [
+ lockKey,
+ ]);
+
+ try {
+ return await run();
+ } finally {
+ await client.query(
+ "SELECT pg_advisory_unlock(hashtextextended($1, 19))",
+ [lockKey],
+ );
+ }
+ } finally {
+ client.release();
+ }
+}
+
+async function loadBatch(
+ userId: string,
+ batchKey: string,
+ database: DbExecutor,
+): Promise<StoredBatch | null> {
+ const batch = await queryOne<{
+ id: string;
+ requestFingerprint: string;
+ }>(
+ database,
+ `
+ SELECT id, request_fingerprint AS "requestFingerprint"
+ FROM bulk_send_batches
+ WHERE user_id = $1 AND batch_key = $2
+ `,
+ [userId, batchKey],
+ );
+
+ if (!batch) {
+ return null;
+ }
+
+ const rows = await queryMany<{
+ envelopeId: string | null;
+ reason: string | null;
+ rowNumber: number;
+ status: StoredBatchRow["status"];
+ }>(
+ database,
+ `
+ SELECT
+ row_number AS "rowNumber",
+ status,
+ envelope_id AS "envelopeId",
+ reason
+ FROM bulk_send_batch_rows
+ WHERE batch_id = $1
+ `,
+ [batch.id],
+ );
+
+ return {
+ id: batch.id,
+ requestFingerprint: batch.requestFingerprint,
+ rows: new Map(
+ rows.map((row) => [
+ row.rowNumber,
+ {
+ envelopeId: row.envelopeId,
+ reason: row.reason,
+ status: row.status,
+ },
+ ]),
+ ),
+ };
+}
+
+async function insertBatch(
+ userId: string,
+ templateId: string,
+ batchKey: string,
+ requestFingerprint: string,
+ database: DbExecutor,
+): Promise<StoredBatch> {
+ const id = randomUUID();
+
+ await database.query(
+ `
+ INSERT INTO bulk_send_batches (
+ id,
+ user_id,
+ template_id,
+ batch_key,
+ request_fingerprint
+ )
+ VALUES ($1, $2, $3, $4, $5)
+ `,
+ [id, userId, templateId, batchKey, requestFingerprint],
+ );
+
+ return { id, requestFingerprint, rows: new Map() };
+}
+
+async function ensureBatch(
+ userId: string,
+ templateId: string,
+ batchKey: string,
+ requestFingerprint: string,
+ database: DbExecutor,
+): Promise<StoredBatch> {
+ const existing = await loadBatch(userId, batchKey, database);
+
+ if (existing) {
+ if (existing.requestFingerprint !== requestFingerprint) {
+ throw new BulkSendError(bulkSendBatchMismatchMessage, 409);
+ }
+
+ return existing;
+ }
+
+ try {
+ return await insertBatch(
+ userId,
+ templateId,
+ batchKey,
+ requestFingerprint,
+ database,
+ );
+ } catch (error) {
+ if (
+ typeof error === "object" &&
+ error !== null &&
+ "code" in error &&
+ error.code === "23505"
+ ) {
+ const raced = await loadBatch(userId, batchKey, database);
+
+ if (raced) {
+ if (raced.requestFingerprint !== requestFingerprint) {
+ throw new BulkSendError(bulkSendBatchMismatchMessage, 409);
+ }
+
+ return raced;
+ }
+ }
+
+ throw error;
+ }
+}
+
+async function saveBatchRow(
+ batchId: string,
+ row: BulkSendRowResult,
+ status: StoredBatchRow["status"],
+ database: DbExecutor,
+): Promise<void> {
+ await database.query(
+ `
+ INSERT INTO bulk_send_batch_rows (
+ batch_id,
+ row_number,
+ status,
+ envelope_id,
+ reason
+ )
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (batch_id, row_number)
+ DO UPDATE SET
+ status = EXCLUDED.status,
+ envelope_id = EXCLUDED.envelope_id,
+ reason = EXCLUDED.reason
+ `,
+ [batchId, row.rowNumber, status, row.envelopeId, row.reason],
+ );
+}
+
+async function invitationWasRecorded(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<boolean> {
+ const row = await queryOne<{ ok: number }>(
+ database,
+ `
+ SELECT 1 AS ok
+ FROM audit_events
+ WHERE envelope_id = $1
+ AND event = 'email_sent'
+ AND metadata->>'template' = 'signing_invitation'
+ LIMIT 1
+ `,
+ [envelopeId],
+ );
+
+ return row !== null;
+}
+
+function restoreStoredRow(
+ row: BulkSendRowResult,
+ stored: StoredBatchRow,
+): BulkSendRowResult {
+ if (stored.status === "sent" && stored.envelopeId) {
+ return sentRow(row, stored.envelopeId);
+ }
+
+ if (stored.status === "skipped") {
+ return {
+ ...row,
+ envelopeId: null,
+ envelopePath: null,
+ reason: stored.reason,
+ status: "skipped",
+ };
+ }
+
+ return {
+ ...row,
+ envelopeId: stored.envelopeId,
+ envelopePath: stored.envelopeId ? envelopePath(stored.envelopeId) : null,
+ reason: stored.reason ?? "Unable to send this envelope.",
+ status: "failed",
+ };
+}
+
+async function sendOneRow(
+ row: BulkSendRowResult,
+ stored: StoredBatchRow | undefined,
+ context: SendRowContext,
+): Promise<BulkSendRowResult> {
+ const {
+ batchId,
+ copyRecipients,
+ database,
+ expiresInDays,
+ progress,
+ reminderIntervalDays,
+ requireEmailCode,
+ sender,
+ signatureMeaning,
+ storageService,
+ templateId,
+ userId,
+ } = context;
+ const needsSignerUpdate =
+ copyRecipients.length > 0 || requireEmailCode || signatureMeaning !== null;
+ let envelopeId = stored?.envelopeId ?? null;
+
+ progress.envelopeId = envelopeId;
+
+ if (envelopeId && (await invitationWasRecorded(envelopeId, database))) {
+ return sentRow(row, envelopeId);
+ }
+
+ if (envelopeId) {
+ const prepared = await getPrepareEnvelopeDataForUser(userId, envelopeId, {
+ database,
+ });
+
+ if (!prepared) {
+ envelopeId = null;
+ progress.envelopeId = null;
+ } else if (prepared.status !== "draft") {
+ throw new BulkSendError(bulkSendInvitationUnconfirmedMessage, 409);
+ }
+ }
+
+ if (!envelopeId) {
+ const draft = await createDraftFromTemplate(
+ userId,
+ templateId,
+ {
+ signers: row.signers.map((signer) => ({
+ email: signer.email,
+ name: signer.name,
+ })),
+ title: row.title,
+ },
+ { database, storageService },
+ );
+
+ envelopeId = draft.envelopeId;
+ progress.envelopeId = envelopeId;
+ }
+
+ const processing = {
+ ...row,
+ envelopeId,
+ envelopePath: envelopePath(envelopeId),
+ };
+
+ await saveBatchRow(batchId, processing, "processing", database);
+
+ if (needsSignerUpdate) {
+ const prepared = await getPrepareEnvelopeDataForUser(userId, envelopeId, {
+ database,
+ });
+
+ if (!prepared) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (prepared.status === "draft") {
+ await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ {
+ copyRecipients,
+ signers: [...prepared.signers]
+ .sort((left, right) => left.order - right.order)
+ .map((signer) => ({
+ email: signer.email,
+ id: signer.id,
+ name: signer.name,
+ requireEmailCode,
+ signatureMeaning,
+ })),
+ },
+ database,
+ );
+ }
+ }
+
+ try {
+ await sendDraftEnvelope(
+ userId,
+ envelopeId,
+ {
+ expiresInDays,
+ ipAddress: sender.ipAddress,
+ reminderIntervalDays,
+ senderEmail: sender.email,
+ senderName: sender.name,
+ signatureLevel: "simple",
+ userAgent: sender.userAgent,
+ },
+ { database },
+ );
+ } catch (error) {
+ if (
+ error instanceof EnvelopeMutationError &&
+ (error.message === "Only draft envelopes can be sent." ||
+ error.message === "This envelope has already been sent.") &&
+ (await invitationWasRecorded(envelopeId, database))
+ ) {
+ return sentRow(row, envelopeId);
+ }
+
+ throw error;
+ }
+
+ return sentRow(row, envelopeId);
+}
+
+/**
+ * Reads a CSV of people for a template the user owns. With confirm, each
+ * valid row is turned into an envelope and sent. Invalid rows are skipped
+ * and a failure on one row does not roll back the others. Confirming again
+ * with the same batch key returns the stored results.
+ */
+export async function bulkSendFromTemplate(
+ userId: string,
+ templateId: string,
+ input: unknown,
+ {
+ database = getDb(),
+ sender,
+ storageService = createStorageService(),
+ }: BulkSendOptions = {},
+): Promise<BulkSendResult> {
+ const parsedInput = bulkSendRequestSchema.parse(input);
+ const template = await getTemplateForBulkSend(userId, templateId, database);
+
+ if (!template) {
+ throw new TemplateError("Template not found.", 404);
+ }
+
+ const unsendable = describeUnsendableTemplate(
+ template.roles,
+ template.fields,
+ );
+
+ if (unsendable) {
+ throw new BulkSendError(unsendable, 400);
+ }
+
+ if (parsedInput.confirm && parsedInput.permittedUseConfirmed !== true) {
+ throw new BulkSendError(
+ "Confirm that these envelopes are ordinary business agreements before sending.",
+ 400,
+ );
+ }
+
+ if (parsedInput.confirm && !parsedInput.batchKey) {
+ throw new BulkSendError(missingBulkSendBatchKeyMessage, 400);
+ }
+
+ if (parsedInput.confirm && !sender) {
+ throw new BulkSendError("Unable to send this envelope.", 500);
+ }
+
+ const parsedCsv = parseBulkSendCsv(
+ parsedInput.csv,
+ template.roles,
+ template.name,
+ );
+
+ if (parsedCsv.error) {
+ throw new BulkSendError(parsedCsv.error, 400);
+ }
+
+ const copyRecipientEmails = (parsedInput.copyRecipients ?? []).map(
+ (recipient) => recipient.email,
+ );
+ let rows = validateBulkSendRows(parsedCsv.rows, copyRecipientEmails);
+ const part11 = (await readStoredSettings(database))?.part11Mode ?? false;
+
+ if (part11) {
+ rows = await applyPart11Problems(
+ rows,
+ parsedInput.signatureMeaning,
+ database,
+ );
+ }
+
+ const resultFor = (nextRows: BulkSendRowResult[]): BulkSendResult => ({
+ error: null,
+ maxRows: MAX_BULK_SEND_ROWS,
+ rows: nextRows,
+ summary: summarizeBulkSendRows(nextRows),
+ templateId: template.id,
+ templateName: template.name,
+ });
+
+ if (!parsedInput.confirm) {
+ return resultFor(rows);
+ }
+
+ const batchKey = parsedInput.batchKey!;
+ const copyRecipients = parsedInput.copyRecipients ?? [];
+ const requireEmailCode = parsedInput.requireEmailCode === true;
+ const signatureMeaning = parsedInput.signatureMeaning ?? null;
+ const fingerprint = fingerprintBulkSendRequest(template.id, parsedInput);
+
+ return withBatchLock(database, `${userId}:${batchKey}`, async () => {
+ const batch = await ensureBatch(
+ userId,
+ template.id,
+ batchKey,
+ fingerprint,
+ database,
+ );
+ const sent: BulkSendRowResult[] = [];
+
+ for (const row of rows) {
+ const stored = batch.rows.get(row.rowNumber);
+
+ if (stored && TERMINAL_ROW_STATUSES.has(stored.status)) {
+ sent.push(restoreStoredRow(row, stored));
+ continue;
+ }
+
+ if (row.status !== "ok") {
+ await saveBatchRow(batch.id, row, "skipped", database);
+ sent.push(row);
+ continue;
+ }
+
+ const progress = { envelopeId: stored?.envelopeId ?? null };
+
+ try {
+ const result = await sendOneRow(row, stored, {
+ batchId: batch.id,
+ copyRecipients,
+ database,
+ expiresInDays: parsedInput.expiresInDays,
+ progress,
+ reminderIntervalDays: parsedInput.reminderIntervalDays,
+ requireEmailCode,
+ sender: sender!,
+ signatureMeaning,
+ storageService,
+ templateId,
+ userId,
+ });
+
+ await saveBatchRow(batch.id, result, "sent", database);
+ sent.push(result);
+ } catch (error) {
+ if (!isExpectedSendFailure(error)) {
+ logRouteError(error, {
+ category: "template_bulk_send_row_failure",
+ message:
+ "Unexpected failure while sending one row of a template batch.",
+ metadata: {
+ envelopeId: progress.envelopeId,
+ rowNumber: row.rowNumber,
+ templateId: template.id,
+ },
+ userId,
+ });
+ }
+
+ const failed = failedRow(row, progress.envelopeId, error);
+
+ await saveBatchRow(batch.id, failed, "failed", database);
+ sent.push(failed);
+ }
+ }
+
+ return resultFor(sent);
+ });
+}
diff --git a/src/lib/schemas/bulk-send.ts b/src/lib/schemas/bulk-send.ts
new file mode 100644
index 0000000..46ad6ee
--- /dev/null
+++ b/src/lib/schemas/bulk-send.ts
@@ -0,0 +1,33 @@
+import { z } from "zod";
+
+import {
+ MAX_COPY_RECIPIENTS_PER_ENVELOPE,
+ signatureMeanings,
+} from "../types/domain.ts";
+import { emailSchema, nameSchema } from "./common.ts";
+import { deadlineDaysSchema, reminderIntervalDaysSchema } from "./envelope.ts";
+
+/** Enough for 200 rows with names, addresses and a title. */
+export const MAX_BULK_SEND_CSV_CHARS = 512 * 1024;
+
+/** Preview or send a template from a CSV of people. */
+export const bulkSendRequestSchema = z.object({
+ /**
+ * Stable id for one confirm. A retry with the same key returns or
+ * finishes the stored results instead of sending the list again.
+ */
+ batchKey: z.string().trim().min(1).max(64).optional(),
+ confirm: z.boolean().optional(),
+ copyRecipients: z
+ .array(z.object({ email: emailSchema, name: nameSchema }))
+ .max(MAX_COPY_RECIPIENTS_PER_ENVELOPE)
+ .optional(),
+ csv: z.string().min(1).max(MAX_BULK_SEND_CSV_CHARS),
+ expiresInDays: deadlineDaysSchema.optional(),
+ permittedUseConfirmed: z.boolean().optional(),
+ reminderIntervalDays: reminderIntervalDaysSchema.optional(),
+ requireEmailCode: z.boolean().optional(),
+ signatureMeaning: z.enum(signatureMeanings).nullable().optional(),
+});
+
+export type BulkSendRequest = z.infer<typeof bulkSendRequestSchema>;
diff --git a/src/lib/templates.test.ts b/src/lib/templates.test.ts
new file mode 100644
index 0000000..ab8aa53
--- /dev/null
+++ b/src/lib/templates.test.ts
@@ -0,0 +1,58 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { describeUnsendableTemplate } from "./templates.ts";
+
+const role = { id: "role-1", name: "Signer" };
+
+function signatureField(signerId = role.id) {
+ return {
+ height: 0.03,
+ page: 1,
+ required: true,
+ signerId,
+ type: "signature",
+ width: 0.2,
+ x: 0.1,
+ y: 0.1,
+ };
+}
+
+test("a template with no signature field cannot be sent", () => {
+ assert.match(
+ describeUnsendableTemplate([role], []) ?? "",
+ /Add signers and place fields/,
+ );
+ assert.match(
+ describeUnsendableTemplate(
+ [role],
+ [
+ {
+ ...signatureField(),
+ label: "Note",
+ type: "text",
+ },
+ ],
+ ) ?? "",
+ /Signature field/,
+ );
+ assert.equal(describeUnsendableTemplate([role], [signatureField()]), null);
+});
+
+test("a dropdown with fewer than two choices cannot be sent", () => {
+ assert.match(
+ describeUnsendableTemplate(
+ [role],
+ [
+ signatureField(),
+ {
+ ...signatureField(),
+ options: ["Only one"],
+ type: "dropdown",
+ y: 0.2,
+ },
+ ],
+ ) ?? "",
+ /dropdown/,
+ );
+});
diff --git a/src/lib/templates.ts b/src/lib/templates.ts
index 7c2d363..39a0684 100644
--- a/src/lib/templates.ts
+++ b/src/lib/templates.ts
@@ -17,7 +17,11 @@ import {
replaceDraftEnvelopeFields,
replaceDraftEnvelopeSigners,
} from "./envelopes.ts";
-import { countAnswerableFields } from "./field-choices.ts";
+import {
+ countAnswerableFields,
+ describeChoiceFieldProblem,
+ findChoiceFieldProblem,
+} from "./field-choices.ts";
import { fieldPlacementListSchema } from "./schemas/field.ts";
import {
saveTemplateSchema,
@@ -218,11 +222,68 @@ export async function listTemplatesForUser(
}));
}
-export async function getUseTemplateDataForUser(
+export type TemplateForBulkSend = UseTemplateData & {
+ fields: unknown;
+};
+
+/**
+ * Whether this template can be sent as it stands: every role needs a
+ * signature field, and choice fields must be finished. Saved from a draft
+ * that was still being prepared, it is kept, but it cannot go out.
+ */
+export function describeUnsendableTemplate(
+ roles: readonly TemplateRole[],
+ fields: unknown,
+): string | null {
+ if (roles.length === 0) {
+ return "Add signers and place fields before sending this envelope.";
+ }
+
+ const parsed = fieldPlacementListSchema.safeParse(fields);
+
+ if (!parsed.success) {
+ return UNUSABLE_TEMPLATE_MESSAGE;
+ }
+
+ if (parsed.data.length === 0) {
+ return "Add signers and place fields before sending this envelope.";
+ }
+
+ const roleIds = new Set(roles.map((role) => role.id));
+
+ if (parsed.data.some((field) => !roleIds.has(field.signerId))) {
+ return UNUSABLE_TEMPLATE_MESSAGE;
+ }
+
+ const missing = roles.find(
+ (role) =>
+ !parsed.data.some(
+ (field) => field.signerId === role.id && field.type === "signature",
+ ),
+ );
+
+ if (missing) {
+ return `Every signer must have at least one Signature field before sending. ${missing.name} is missing one.`;
+ }
+
+ const choiceProblem = findChoiceFieldProblem(parsed.data);
+
+ if (!choiceProblem) {
+ return null;
+ }
+
+ return describeChoiceFieldProblem(
+ choiceProblem,
+ roles.find((role) => role.id === choiceProblem.signerId)?.name ??
+ "a signer",
+ );
+}
+
+export async function getTemplateForBulkSend(
userId: string,
templateId: string,
database: DbExecutor = getDb(),
-): Promise<UseTemplateData | null> {
+): Promise<TemplateForBulkSend | null> {
const row = await getTemplateRow(userId, templateId, database);
if (!row) {
@@ -237,6 +298,7 @@ export async function getUseTemplateDataForUser(
return {
fieldCountLabel: countLabel(countFields(row.fields), "field"),
+ fields: row.fields,
id: row.id,
name: row.name,
pageCountLabel: countLabel(row.pageCount, "page"),
@@ -244,6 +306,26 @@ export async function getUseTemplateDataForUser(
};
}
+export async function getUseTemplateDataForUser(
+ userId: string,
+ templateId: string,
+ database: DbExecutor = getDb(),
+): Promise<UseTemplateData | null> {
+ const template = await getTemplateForBulkSend(userId, templateId, database);
+
+ if (!template) {
+ return null;
+ }
+
+ return {
+ fieldCountLabel: template.fieldCountLabel,
+ id: template.id,
+ name: template.name,
+ pageCountLabel: template.pageCountLabel,
+ roles: template.roles,
+ };
+}
+
/**
* Keeps an envelope's document, fields and signing order as a template.
* Any envelope of the user's will do, sent or not: only where the fields