Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add templates: send the same document again without setting it up again
Claude6673116a8568
diff --git a/db/migrations/20261114140000_templates.sql b/db/migrations/20261114140000_templates.sqlnew file mode 100644index 0000000..47dde52--- /dev/null+++ b/db/migrations/20261114140000_templates.sql@@ -0,0 +1,37 @@+-- Templates: a document, its fields and its signing order, kept so the same+-- thing can be sent again without setting it up again.+--+-- A template holds no one's name or address. Each place in the signing+-- order is a role with a label ("Client", "Landlord"), and the person who+-- fills it is named when the template is used.+--+-- Roles and fields are stored whole, as JSON, because they are only ever+-- read and written together. The application checks their contents with the+-- same rules it applies to the fields of an envelope.+-- roles: [{ "id": "...", "name": "Client" }, ...] in signing order+-- fields: placed fields, each with "signerId" naming one of the roles++create table if not exists public.templates (+ id text primary key,+ user_id text not null references public."user"(id) on delete cascade,+ name text not null check (length(btrim(name)) between 1 and 160),+ source_pdf_key text not null,+ source_pdf_filename text not null,+ source_pdf_size_bytes bigint not null check (source_pdf_size_bytes > 0),+ page_count integer not null check (page_count > 0),+ roles jsonb not null,+ fields jsonb not null,+ created_at bigint not null default (extract(epoch from now())::bigint),+ updated_at bigint not null default (extract(epoch from now())::bigint),+ constraint templates_roles_check check (+ case+ when jsonb_typeof(roles) = 'array'+ then jsonb_array_length(roles) between 1 and 10+ else false+ end+ ),+ constraint templates_fields_check check (jsonb_typeof(fields) = 'array')+);++create index if not exists idx_templates_user_created_at+ on public.templates(user_id, created_at desc, id);diff --git a/src/app/(app)/templates/[id]/use/page.tsx b/src/app/(app)/templates/[id]/use/page.tsxnew file mode 100644index 0000000..0d50301--- /dev/null+++ b/src/app/(app)/templates/[id]/use/page.tsx@@ -0,0 +1,44 @@+import { notFound } from "next/navigation";++import { UseTemplateShell } from "@/components/templates/use-template-shell";+import { getAuthSession } from "@/lib/auth/server";+import { getDb } from "@/lib/db/connection";+import { getUseTemplateDataForUser, TemplateError } from "@/lib/templates";++type UseTemplatePageProps = {+ params: Promise<{+ id: string;+ }>;+};++export default async function UseTemplatePage({+ params,+}: UseTemplatePageProps) {+ const { id } = await params;+ let template: Awaited<ReturnType<typeof getUseTemplateDataForUser>> = null;+ let errorMessage: string | undefined;+ let failed = false;++ try {+ const session = await getAuthSession();++ template = session+ ? await getUseTemplateDataForUser(session.user.id, id, getDb())+ : null;+ } catch (error) {+ failed = true;+ errorMessage = error instanceof TemplateError ? error.message : undefined;+ }++ if (!failed && !template) {+ notFound();+ }++ return (+ <UseTemplateShell+ errorMessage={errorMessage}+ key={id}+ template={template ?? undefined}+ />+ );+}diff --git a/src/app/(app)/templates/page.tsx b/src/app/(app)/templates/page.tsxnew file mode 100644index 0000000..2100f5c--- /dev/null+++ b/src/app/(app)/templates/page.tsx@@ -0,0 +1,21 @@+import { TemplatesShell } from "@/components/templates/templates-shell";+import { getAuthSession } from "@/lib/auth/server";+import { getDb } from "@/lib/db/connection";+import { listTemplatesForUser } from "@/lib/templates";++export default async function TemplatesPage() {+ let templates: Awaited<ReturnType<typeof listTemplatesForUser>> = [];+ let initialState: "error" | undefined;++ try {+ const session = await getAuthSession();++ templates = session+ ? await listTemplatesForUser(session.user.id, getDb())+ : [];+ } catch {+ initialState = "error";+ }++ return <TemplatesShell initialState={initialState} templates={templates} />;+}diff --git a/src/app/api/envelopes/[id]/template/route.ts b/src/app/api/envelopes/[id]/template/route.tsnew file mode 100644index 0000000..d74fdec--- /dev/null+++ b/src/app/api/envelopes/[id]/template/route.ts@@ -0,0 +1,86 @@+import { NextResponse } from "next/server";+import { ZodError } from "zod";++import { requireVerifiedSenderSession } from "@/lib/auth/route-session";+import { getDb } from "@/lib/db/connection";+import { logRouteError } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { saveEnvelopeAsTemplate, TemplateError } from "@/lib/templates";++type EnvelopeTemplateRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++// Keeps this envelope's document, fields and signing order as a template.++export async function POST(+ request: Request,+ context: EnvelopeTemplateRouteContext,+) {+ const sessionResult = await requireVerifiedSenderSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ const rateLimitResponse = await applyRateLimit({+ category: "template_save",+ key: buildRateLimitKey(["template-save", session.user.id]),+ limit: 20,+ request,+ userId: session.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const { id } = await context.params;+ const body = (await request.json().catch(() => null)) as unknown;++ try {+ const template = await saveEnvelopeAsTemplate(session.user.id, id, body, {+ database: getDb(),+ });++ return NextResponse.json(+ { name: template.name, templateId: template.id },+ { status: 201 },+ );+ } catch (error) {+ if (error instanceof ZodError) {+ return NextResponse.json(+ { error: error.issues[0]?.message ?? "Invalid template request." },+ { status: 400 },+ );+ }++ if (error instanceof TemplateError) {+ return NextResponse.json(+ { error: error.message },+ { status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "template_save_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while saving an envelope as a template.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "Unable to save this as a template." },+ { status: 500 },+ );+ }+}diff --git a/src/app/api/templates/[id]/route.ts b/src/app/api/templates/[id]/route.tsnew file mode 100644index 0000000..4983e76--- /dev/null+++ b/src/app/api/templates/[id]/route.ts@@ -0,0 +1,50 @@+import { NextResponse } from "next/server";++import { requireVerifiedSenderSession } from "@/lib/auth/route-session";+import { getDb } from "@/lib/db/connection";+import { logRouteError } from "@/lib/security/logging";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { deleteTemplate, TemplateError } from "@/lib/templates";++type TemplateRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++export async function DELETE(request: Request, context: TemplateRouteContext) {+ const sessionResult = await requireVerifiedSenderSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ const { id } = await context.params;++ try {+ await deleteTemplate(session.user.id, id, { database: getDb() });++ return NextResponse.json({ deletedTemplateId: id }, { status: 200 });+ } catch (error) {+ if (error instanceof TemplateError) {+ return NextResponse.json(+ { error: error.message },+ { status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "template_delete_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while deleting a template.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "Unable to delete this template." },+ { status: 500 },+ );+ }+}diff --git a/src/app/api/templates/[id]/use/route.ts b/src/app/api/templates/[id]/use/route.tsnew file mode 100644index 0000000..f978394--- /dev/null+++ b/src/app/api/templates/[id]/use/route.ts@@ -0,0 +1,90 @@+import { NextResponse } from "next/server";+import { ZodError } from "zod";++import { requireVerifiedSenderSession } from "@/lib/auth/route-session";+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 } from "@/lib/security/request";+import { DocumentImportError } from "@/lib/services/document-import";+import { createDraftFromTemplate, TemplateError } from "@/lib/templates";++type UseTemplateRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++// Starts a draft envelope from a template.++export async function POST(request: Request, context: UseTemplateRouteContext) {+ const sessionResult = await requireVerifiedSenderSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ // The same allowance as uploading a document: either way a draft is made.+ const rateLimitResponse = await applyRateLimit({+ category: "draft_envelope_create",+ key: buildRateLimitKey(["draft-create", session.user.id]),+ limit: 20,+ request,+ userId: session.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const { id } = await context.params;+ const body = (await request.json().catch(() => null)) as unknown;++ try {+ const draft = await createDraftFromTemplate(session.user.id, id, body, {+ database: getDb(),+ });++ return NextResponse.json(draft, { status: 201 });+ } catch (error) {+ if (error instanceof ZodError) {+ return NextResponse.json(+ { error: error.issues[0]?.message ?? "Invalid template request." },+ { status: 400 },+ );+ }++ if (+ 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_use_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while starting a draft from a template.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "Unable to start an envelope from this template." },+ { status: 500 },+ );+ }+}diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex 146a207..0092468 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -14,6 +14,7 @@ import { useState } from "react";import { DocumentThumbnail } from "@/components/shared/document-thumbnail";import { ShellButton } from "@/components/shared/form-shell";import { StatusPanel } from "@/components/shared/status-panel";+import { SaveTemplateDialog } from "@/components/templates/save-template-dialog";import {Dialog,DialogContent,@@ -70,6 +71,7 @@ type ModalState =| "change-deadline"| "change-reminders"| "delete-draft"+ | "save-template"| "void-envelope"| null;@@ -129,6 +131,9 @@ export function EnvelopeDetailShell({const [isDeletingDraft, setIsDeletingDraft] = useState(false);const [isSendingReminder, setIsSendingReminder] = useState(false);const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);+ const [savedTemplateName, setSavedTemplateName] = useState<string | null>(+ null,+ );function handleRetry() {window.location.reload();@@ -520,6 +525,44 @@ export function EnvelopeDetailShell({</div>) : null}+ {savedTemplateName ? (+ <div+ className={`notice notice-success flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between ${+ deadlineText || deadline ? "mt-3" : "mt-5"+ }`}+ role="status"+ >+ <p>Saved as the template “{savedTemplateName}”.</p>+ <Link+ className="shrink-0 underline underline-offset-4"+ href="/templates"+ >+ View templates+ </Link>+ </div>+ ) : activeRecord.signers.length > 0 ? (+ <div+ className={`well flex flex-col gap-3 px-5 py-3.5 sm:flex-row sm:items-center sm:justify-between ${+ deadlineText || deadline ? "mt-3" : "mt-5"+ }`}+ >+ <p className="text-sm leading-6 text-(--secondary)">+ Send this kind of document often? Keep its fields and signing+ order as a template.+ </p>+ <button+ className="btn-quiet shrink-0"+ onClick={() => {+ setActionError(null);+ setActiveModal("save-template");+ }}+ type="button"+ >+ Save as template+ </button>+ </div>+ ) : null}+{actionError ? (<div className="notice notice-danger mt-5" role="alert">{actionError}@@ -681,6 +724,21 @@ export function EnvelopeDetailShell({/>) : null}+ {activeModal === "save-template" ? (+ <SaveTemplateDialog+ envelopeId={envelopeId}+ initialName={activeRecord.title}+ onCancel={() => setActiveModal(null)}+ onSaved={(templateName) => {+ setActiveModal(null);+ setSavedTemplateName(templateName);+ }}+ signers={[...activeRecord.signers]+ .sort((left, right) => left.order - right.order)+ .map((signer) => ({ id: signer.id, name: signer.name }))}+ />+ ) : null}+{activeModal === "delete-draft" ? (<ConfirmationDialogconfirmLabel="Delete draft"diff --git a/src/components/envelopes/upload-shell.tsx b/src/components/envelopes/upload-shell.tsxindex bdf2a1b..0f726ee 100644--- a/src/components/envelopes/upload-shell.tsx+++ b/src/components/envelopes/upload-shell.tsx@@ -1,6 +1,7 @@"use client";import { FileTextIcon, UploadIcon } from "lucide-react";+import Link from "next/link";import { useRouter } from "next/navigation";import {startTransition,@@ -128,6 +129,11 @@ function UploadShellLayout({return (<div className="space-y-5"><PageHeader+ action={+ <Link className="btn-quiet min-h-11 px-4" href="/templates">+ Start from a template+ </Link>+ }description="Step 1 of 4 - Upload document"title="New envelope"/>diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsxindex 9433a9f..c836770 100644--- a/src/components/layout/app-shell.tsx+++ b/src/components/layout/app-shell.tsx@@ -30,7 +30,8 @@ type AppShellProps = {};};-type ShellSection = "documents" | "new-envelope" | "settings" | "workspace";+type ShellSection =+ "documents" | "new-envelope" | "settings" | "templates" | "workspace";export function AppShell({children,@@ -209,6 +210,10 @@ function resolveSection(pathname: string): ShellSection {return "documents";}+ if (pathname === "/templates" || pathname.startsWith("/templates/")) {+ return "templates";+ }+return "workspace";}diff --git a/src/components/layout/nav-items.tsx b/src/components/layout/nav-items.tsxindex 5e72a8d..a182910 100644--- a/src/components/layout/nav-items.tsx+++ b/src/components/layout/nav-items.tsx@@ -7,6 +7,7 @@ export type ShellNavItem = {export const primaryNavItems: ShellNavItem[] = [{ href: "/dashboard", label: "Documents" },+ { href: "/templates", label: "Templates" },{ href: "/envelopes/new", label: "New envelope" },{ href: "/settings", label: "Settings" },];diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsxindex 3f38a8e..adb556a 100644--- a/src/components/settings/settings-shell.tsx+++ b/src/components/settings/settings-shell.tsx@@ -727,8 +727,8 @@ function useClosureCopy(): string {const { hosted, productName } = useBranding();return hosted- ? `Before closing your account, download any documents you want to keep. After closure, ${productName} keeps a 30-day export window and then deletes your stored documents and envelope records. Signers keep the copies they were emailed.`- : `Before closing your account, download any documents you want to keep. After 30 days your drafts and unfinished envelopes are deleted. Finished documents and their audit trails stay with ${productName}: they move to an administrator, because they are the organization's records.`;+ ? `Before closing your account, download any documents you want to keep. After closure, ${productName} keeps a 30-day export window and then deletes your stored documents, templates and envelope records. Signers keep the copies they were emailed.`+ : `Before closing your account, download any documents you want to keep. After 30 days your drafts, unfinished envelopes and templates are deleted. Finished documents and their audit trails stay with ${productName}: they move to an administrator, because they are the organization's records.`;}function AccountClosureDialog({diff --git a/src/components/templates/save-template-dialog.tsx b/src/components/templates/save-template-dialog.tsxnew file mode 100644index 0000000..f38fd60--- /dev/null+++ b/src/components/templates/save-template-dialog.tsx@@ -0,0 +1,196 @@+"use client";++import { useId, useState, type FormEvent } from "react";++import { ShellButton } from "@/components/shared/form-shell";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { MAX_TEMPLATE_ROLE_NAME_LENGTH } from "@/lib/schemas/template";++type SaveTemplateDialogProps = {+ envelopeId: string;+ /** What the template is called unless the sender changes it. */+ initialName: string;+ onCancel: () => void;+ onSaved: (templateName: string) => void;+ /** In signing order. The names only say whose place is being named. */+ signers: readonly { id: string; name: string }[];+};++const genericError = "Something went wrong. Please try again.";++/**+ * Asks what to call the template and each place in its signing order, then+ * saves the envelope as a template.+ */+export function SaveTemplateDialog({+ envelopeId,+ initialName,+ onCancel,+ onSaved,+ signers,+}: SaveTemplateDialogProps) {+ const formId = useId();+ const [name, setName] = useState(initialName);+ const [roleNames, setRoleNames] = useState(() =>+ signers.map((_, index) => `Signer ${String(index + 1)}`),+ );+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [isSaving, setIsSaving] = useState(false);++ const trimmedRoleNames = roleNames.map((roleName) => roleName.trim());+ const hasRepeatedRoleName =+ new Set(trimmedRoleNames.map((roleName) => roleName.toLowerCase())).size !==+ trimmedRoleNames.length;+ const canSave =+ name.trim().length > 0 &&+ trimmedRoleNames.every((roleName) => roleName.length > 0) &&+ !hasRepeatedRoleName;++ async function handleSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();++ if (!canSave || isSaving) {+ return;+ }++ setErrorMessage(null);+ setIsSaving(true);++ try {+ const response = await fetch(`/api/envelopes/${envelopeId}/template`, {+ body: JSON.stringify({ name, roleNames: trimmedRoleNames }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const payload = (await response.json().catch(() => null)) as {+ error?: string;+ name?: string;+ } | null;++ if (!response.ok) {+ setErrorMessage(payload?.error ?? genericError);+ return;+ }++ onSaved(payload?.name ?? name.trim());+ } catch {+ setErrorMessage(genericError);+ } finally {+ setIsSaving(false);+ }+ }++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !isSaving) {+ onCancel();+ }+ }}+ >+ <DialogContent className="max-w-lg sm:p-8" showCloseButton={false}>+ <form className="space-y-5" onSubmit={handleSubmit}>+ <DialogHeader className="space-y-3">+ <DialogTitle>Save as a template</DialogTitle>+ <DialogDescription asChild>+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">+ <p>+ A template keeps this document, where its fields are and the+ order people sign in. It does not keep anyone's name or+ email address, or anything that was filled in.+ </p>+ </div>+ </DialogDescription>+ </DialogHeader>++ <label className="grid gap-1.5" htmlFor={`${formId}-name`}>+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Template name+ </span>+ <input+ autoFocus+ className="field-input"+ disabled={isSaving}+ id={`${formId}-name`}+ maxLength={160}+ onChange={(event) => {+ setErrorMessage(null);+ setName(event.target.value);+ }}+ type="text"+ value={name}+ />+ </label>++ <fieldset className="grid gap-3">+ <legend className="text-[0.9375rem] font-extrabold text-(--fg)">+ Who signs+ </legend>+ <p className="text-[0.8125rem] leading-5 text-(--secondary)">+ Name each place in the signing order, such as Client or Landlord.+ You say who that is each time you use the template.+ </p>+ {signers.map((signer, index) => (+ <label+ className="well grid gap-1.5 px-4 py-3"+ htmlFor={`${formId}-role-${String(index)}`}+ key={signer.id}+ >+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Signer {index + 1}, here {signer.name}+ </span>+ <input+ className="field-input"+ disabled={isSaving}+ id={`${formId}-role-${String(index)}`}+ maxLength={MAX_TEMPLATE_ROLE_NAME_LENGTH}+ onChange={(event) => {+ setErrorMessage(null);+ setRoleNames((current) =>+ current.map((roleName, roleIndex) =>+ roleIndex === index ? event.target.value : roleName,+ ),+ );+ }}+ type="text"+ value={roleNames[index] ?? ""}+ />+ </label>+ ))}+ {hasRepeatedRoleName ? (+ <p className="text-xs font-semibold text-(--danger)" role="alert">+ Give each signer a different name.+ </p>+ ) : null}+ </fieldset>++ {errorMessage ? (+ <div className="notice notice-danger" role="alert">+ <p>{errorMessage}</p>+ </div>+ ) : null}++ <div className="flex flex-col-reverse gap-3 pt-1 sm:flex-row sm:justify-end">+ <ShellButton+ disabled={isSaving}+ onClick={onCancel}+ variant="secondary"+ >+ Cancel+ </ShellButton>+ <ShellButton disabled={!canSave} loading={isSaving} type="submit">+ {isSaving ? "Saving..." : "Save template"}+ </ShellButton>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/templates/templates-shell.tsx b/src/components/templates/templates-shell.tsxnew file mode 100644index 0000000..e5064d3--- /dev/null+++ b/src/components/templates/templates-shell.tsx@@ -0,0 +1,221 @@+"use client";++import { useRouter } from "next/navigation";+import { useState } from "react";++import { DocumentThumbnail } from "@/components/shared/document-thumbnail";+import { ShellButton } from "@/components/shared/form-shell";+import { PageHeader } from "@/components/shared/page-header";+import { StatusPanel } from "@/components/shared/status-panel";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import type { TemplateListItem } from "@/lib/templates";++type TemplatesShellProps = {+ initialState?: "error";+ templates?: readonly TemplateListItem[];+};++const pageDescription =+ "Documents you send often, with their fields and signing order already in place.";++export function TemplatesShell({+ initialState,+ templates = [],+}: TemplatesShellProps) {+ const router = useRouter();+ const [pendingDelete, setPendingDelete] = useState<TemplateListItem | null>(+ null,+ );+ const [deleteError, setDeleteError] = useState<string | null>(null);+ const [isDeleting, setIsDeleting] = useState(false);++ async function handleConfirmDelete() {+ if (!pendingDelete || isDeleting) {+ return;+ }++ setDeleteError(null);+ setIsDeleting(true);++ try {+ const response = await fetch(`/api/templates/${pendingDelete.id}`, {+ method: "DELETE",+ });++ // Already gone is as good as deleted.+ if (!response.ok && response.status !== 404) {+ const payload = (await response.json().catch(() => null)) as {+ error?: string;+ } | null;++ setDeleteError(payload?.error ?? "Unable to delete this template.");+ return;+ }++ setPendingDelete(null);+ router.refresh();+ } catch {+ setDeleteError("Unable to delete this template.");+ } finally {+ setIsDeleting(false);+ }+ }++ if (initialState === "error") {+ return (+ <div className="space-y-5">+ <PageHeader description={pageDescription} title="Templates" />+ <StatusPanel+ action={{ href: "/templates", label: "Retry" }}+ description="We couldn't load your templates. Try again in a moment."+ title="Couldn't load templates"+ tone="error"+ />+ </div>+ );+ }++ return (+ <div className="space-y-5">+ <PageHeader description={pageDescription} title="Templates" />++ {templates.length === 0 ? (+ <section+ className="panel px-6 py-14 sm:py-16"+ data-animate="enter"+ data-animate-delay="1"+ >+ <div className="mx-auto flex max-w-lg flex-col items-center gap-5 text-center">+ <span className="flex h-28 items-center justify-center">+ <DocumentThumbnail title="" />+ </span>+ <div className="space-y-2">+ <h2 className="text-2xl font-extrabold tracking-[-0.03em] text-(--fg)">+ No templates yet+ </h2>+ <p className="text-[0.9375rem] leading-6 text-(--secondary)">+ Open any document you have prepared or sent and choose Save as+ template. Next time, you only name the people who sign.+ </p>+ </div>+ <ShellButton href="/dashboard">Go to documents</ShellButton>+ </div>+ </section>+ ) : (+ <section+ className="panel p-5 sm:p-7"+ data-animate="enter"+ data-animate-delay="1"+ >+ <ul className="space-y-3">+ {templates.map((template) => (+ <li+ className="well flex flex-col gap-4 p-4 sm:flex-row sm:items-center sm:justify-between sm:p-5"+ key={template.id}+ >+ <div className="min-w-0 space-y-2">+ <h2 className="truncate text-[1.0625rem] font-extrabold text-(--fg)">+ {template.name}+ </h2>+ <p className="text-sm leading-6 text-(--secondary)">+ {template.pageCountLabel} · {template.fieldCountLabel} ·+ Saved {template.createdAtLabel}+ </p>+ <ul+ aria-label={`Signers in ${template.name}`}+ className="flex flex-wrap gap-2"+ >+ {template.roleNames.map((roleName, index) => (+ <li+ className="pill pill-neutral"+ key={`${String(index)}-${roleName}`}+ >+ {index + 1}. {roleName}+ </li>+ ))}+ </ul>+ </div>+ <div className="flex shrink-0 flex-wrap items-center gap-2">+ <button+ aria-label={`Delete the template ${template.name}`}+ className="btn-quiet btn-quiet-danger min-h-11 px-4"+ onClick={() => {+ setDeleteError(null);+ setPendingDelete(template);+ }}+ type="button"+ >+ Delete+ </button>+ <ShellButton+ className="min-h-11"+ href={`/templates/${template.id}/use`}+ >+ Use template+ </ShellButton>+ </div>+ </li>+ ))}+ </ul>+ </section>+ )}++ {pendingDelete ? (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !isDeleting) {+ setPendingDelete(null);+ }+ }}+ >+ <DialogContent className="max-w-md sm:p-8" showCloseButton={false}>+ <div className="space-y-4">+ <DialogHeader className="space-y-3">+ <DialogTitle>Delete this template?</DialogTitle>+ <DialogDescription asChild>+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">+ <p>+ “{pendingDelete.name}” will be removed for+ good.+ </p>+ <p>Documents you already made from it are not affected.</p>+ </div>+ </DialogDescription>+ </DialogHeader>++ {deleteError ? (+ <div className="notice notice-danger" role="alert">+ <p>{deleteError}</p>+ </div>+ ) : null}++ <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-end">+ <ShellButton+ disabled={isDeleting}+ onClick={() => setPendingDelete(null)}+ variant="secondary"+ >+ Cancel+ </ShellButton>+ <ShellButton+ loading={isDeleting}+ onClick={handleConfirmDelete}+ variant="danger"+ >+ {isDeleting ? "Deleting..." : "Delete template"}+ </ShellButton>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ ) : null}+ </div>+ );+}diff --git a/src/components/templates/use-template-shell.tsx b/src/components/templates/use-template-shell.tsxnew file mode 100644index 0000000..f40617a--- /dev/null+++ b/src/components/templates/use-template-shell.tsx@@ -0,0 +1,304 @@+"use client";++import { useState, type FormEvent } from "react";++import { getSignerPalette } from "@/components/envelopes/signer-palette";+import { ShellButton } from "@/components/shared/form-shell";+import { PageHeader } from "@/components/shared/page-header";+import { StatusPanel } from "@/components/shared/status-panel";+import { duplicateSignerEmailMessage } from "@/lib/schemas/signer";+import type { UseTemplateData } from "@/lib/templates";++type UseTemplateShellProps = {+ /** Shown in place of the form when the template cannot be used. */+ errorMessage?: string;+ template?: UseTemplateData;+};++type Person = {+ email: string;+ name: string;+};++type PersonErrors = {+ email?: string;+ name?: string;+};++const validEmailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+const genericError = "Something went wrong. Please try again.";++function findErrors(people: readonly Person[]): PersonErrors[] {+ const emailCounts = new Map<string, number>();++ for (const person of people) {+ const email = person.email.trim().toLowerCase();++ if (email) {+ emailCounts.set(email, (emailCounts.get(email) ?? 0) + 1);+ }+ }++ return people.map((person) => {+ const errors: PersonErrors = {};+ const email = person.email.trim().toLowerCase();++ if (person.name.trim().length === 0) {+ errors.name = "Name is required";+ }++ if (!validEmailPattern.test(email)) {+ errors.email = "Enter a valid email address";+ } else if ((emailCounts.get(email) ?? 0) > 1) {+ errors.email = duplicateSignerEmailMessage;+ }++ return errors;+ });+}++/** Names a person for each role of a template and starts a draft from it. */+export function UseTemplateShell({+ errorMessage,+ template,+}: UseTemplateShellProps) {+ const [title, setTitle] = useState(template?.name ?? "");+ const [people, setPeople] = useState<Person[]>(() =>+ (template?.roles ?? []).map(() => ({ email: "", name: "" })),+ );+ const [showErrors, setShowErrors] = useState(false);+ const [submitError, setSubmitError] = useState<string | null>(null);+ const [isSubmitting, setIsSubmitting] = useState(false);++ if (!template) {+ return (+ <div className="space-y-5">+ <PageHeader title="Use a template" />+ <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 errors = findErrors(people);+ const titleError =+ title.trim().length === 0 ? "Give the envelope a title" : undefined;+ const canSubmit =+ !titleError && errors.every((error) => !error.name && !error.email);++ function updatePerson(index: number, patch: Partial<Person>) {+ setSubmitError(null);+ setPeople((current) =>+ current.map((person, personIndex) =>+ personIndex === index ? { ...person, ...patch } : person,+ ),+ );+ }++ async function handleSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();+ setShowErrors(true);++ if (!template || !canSubmit || isSubmitting) {+ return;+ }++ setSubmitError(null);+ setIsSubmitting(true);++ try {+ const response = await fetch(`/api/templates/${template.id}/use`, {+ body: JSON.stringify({ signers: people, title }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const payload = (await response.json().catch(() => null)) as {+ error?: string;+ redirectPath?: string;+ } | null;++ if (!response.ok || !payload?.redirectPath) {+ setSubmitError(payload?.error ?? genericError);+ setIsSubmitting(false);+ return;+ }++ // The button stays busy until the next page takes over.+ window.location.assign(payload.redirectPath);+ } catch {+ setSubmitError(genericError);+ setIsSubmitting(false);+ }+ }++ return (+ <div className="space-y-5">+ <PageHeader+ description={`${template.name} · ${template.pageCountLabel} · ${template.fieldCountLabel}`}+ title="Use a template"+ />++ <form+ className="panel space-y-6 p-5 sm:p-8"+ data-animate="enter"+ data-animate-delay="1"+ noValidate+ onSubmit={handleSubmit}+ >+ <label className="grid max-w-xl gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Envelope title+ </span>+ <input+ aria-invalid={showErrors && titleError ? true : undefined}+ className="field-input"+ disabled={isSubmitting}+ maxLength={160}+ onChange={(event) => {+ setSubmitError(null);+ setTitle(event.target.value);+ }}+ type="text"+ value={title}+ />+ {showErrors && titleError ? (+ <span+ className="text-xs font-semibold text-(--danger)"+ role="alert"+ >+ {titleError}+ </span>+ ) : null}+ </label>++ <div className="space-y-3">+ <div className="space-y-1">+ <h2 className="text-lg font-extrabold text-(--fg)">+ Who is signing this time?+ </h2>+ <p className="text-sm leading-6 text-(--secondary)">+ They receive the document in this order. The fields are already+ placed for each of them.+ </p>+ </div>++ <ol className="space-y-3">+ {template.roles.map((role, index) => {+ const palette = getSignerPalette(index);+ const person = people[index] ?? { email: "", name: "" };+ const nameError = showErrors ? errors[index]?.name : undefined;+ const emailError = showErrors ? errors[index]?.email : undefined;++ return (+ <li className="well p-4 sm:p-5" key={role.id}>+ <span+ className="pill"+ style={{+ backgroundColor: palette.tint,+ color: palette.color,+ }}+ >+ <span+ aria-hidden="true"+ className="size-2 rounded-full"+ style={{ backgroundColor: palette.color }}+ />+ {index + 1}. {role.name}+ </span>++ <div className="mt-3 grid gap-x-4 gap-y-3 md:grid-cols-2">+ <label className="grid auto-rows-min gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Name+ </span>+ <input+ aria-invalid={nameError ? true : undefined}+ aria-label={`${role.name} name`}+ className="field-input"+ disabled={isSubmitting}+ maxLength={120}+ onChange={(event) =>+ updatePerson(index, { name: event.target.value })+ }+ placeholder="Jane Smith"+ type="text"+ value={person.name}+ />+ {nameError ? (+ <span+ className="text-xs font-semibold text-(--danger)"+ role="alert"+ >+ {nameError}+ </span>+ ) : null}+ </label>++ <label className="grid auto-rows-min gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ </span>+ <input+ aria-invalid={emailError ? true : undefined}+ aria-label={`${role.name} email`}+ className="field-input"+ disabled={isSubmitting}+ maxLength={320}+ onChange={(event) =>+ updatePerson(index, { email: event.target.value })+ }+ placeholder="[email protected]"+ type="email"+ value={person.email}+ />+ {emailError ? (+ <span+ className="text-xs font-semibold text-(--danger)"+ role="alert"+ >+ {emailError}+ </span>+ ) : null}+ </label>+ </div>+ </li>+ );+ })}+ </ol>+ </div>++ <p className="text-sm leading-6 text-(--secondary)">+ Nothing is sent yet. You will see the review step next, where you can+ still change the fields, add people who get a copy, or add an extra+ check before signing.+ </p>++ {submitError ? (+ <div className="notice notice-danger" role="alert">+ <p>{submitError}</p>+ </div>+ ) : null}++ <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">+ <ShellButton+ disabled={isSubmitting}+ href="/templates"+ variant="secondary"+ >+ Cancel+ </ShellButton>+ <ShellButton loading={isSubmitting} type="submit">+ {isSubmitting ? "Creating..." : "Create draft"}+ </ShellButton>+ </div>+ </form>+ </div>+ );+}diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex fed9a8f..6e02bd1 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -97,6 +97,7 @@ import { escapeHtml } from "./utils/html.ts";type CreateDraftEnvelopeOptions = {database?: DbPool;+ storageService?: StorageService;};type CreateDraftEnvelopeInput = {@@ -472,7 +473,10 @@ const timelineDateFormatter = new Intl.DateTimeFormat("en-US", {export async function createDraftEnvelope(userId: string,input: CreateDraftEnvelopeInput,- { database = getDb() }: CreateDraftEnvelopeOptions = {},+ {+ database = getDb(),+ storageService = createStorageService(),+ }: CreateDraftEnvelopeOptions = {},): Promise<DraftEnvelopeResult> {const importedPdf = await importPdfDocument({body: input.sourcePdf.body,@@ -485,7 +489,6 @@ export async function createDraftEnvelope(envelopeId,userId,});- const storageService = createStorageService();await storageService.putObject({body: input.sourcePdf.body,@@ -1505,8 +1508,10 @@ export async function getDraftEnvelopeDocumentForUser(envelopeId: string,{database = getDb(),+ storageService = createStorageService(),}: {database?: DbExecutor;+ storageService?: StorageService;} = {},): Promise<DraftEnvelopeDocument> {const envelope = await getEnvelopeByIdForUser(userId, envelopeId, database);@@ -1515,8 +1520,6 @@ export async function getDraftEnvelopeDocumentForUser(throw new EnvelopeDocumentAccessError("Envelope not found.", 404);}- const storageService = createStorageService();-try {const object = await storageService.getObject(envelope.sourcePdfKey);diff --git a/src/lib/field-choices.ts b/src/lib/field-choices.tsindex 5001bf4..9553be7 100644--- a/src/lib/field-choices.ts+++ b/src/lib/field-choices.ts@@ -113,10 +113,9 @@ export function describeChoiceFieldProblem(* How many things a signer is asked to do, counting a group of radio* buttons as one.*/-export function countAnswerableFields<Field extends ChoiceField>(- fields: readonly Field[],- counts: (field: Field) => boolean,-): number {+export function countAnswerableFields<+ Field extends Pick<ChoiceField, "groupId" | "type">,+>(fields: readonly Field[], counts: (field: Field) => boolean): number {const seenGroups = new Set<string>();let total = 0;diff --git a/src/lib/retention.ts b/src/lib/retention.tsindex 2967bcd..92cc268 100644--- a/src/lib/retention.ts+++ b/src/lib/retention.ts@@ -438,6 +438,18 @@ async function purgeQueuedAccount(}}+ // Templates go with the account: their rows with the user's row below,+ // their documents here.+ const templates = await queryMany<{ sourcePdfKey: string }>(+ database,+ `SELECT source_pdf_key AS "sourcePdfKey" FROM templates WHERE user_id = $1`,+ [userId],+ );++ for (const template of templates) {+ storageKeys.add(template.sourcePdfKey);+ }+const deleteResult = await database.query(`DELETE FROM "user"diff --git a/src/lib/schemas/template.test.ts b/src/lib/schemas/template.test.tsnew file mode 100644index 0000000..41f6b8c--- /dev/null+++ b/src/lib/schemas/template.test.ts@@ -0,0 +1,84 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ duplicateRoleNameMessage,+ saveTemplateSchema,+ templateRolesSchema,+ useTemplateSchema,+} from "./template.ts";++test("a template needs a name, and its signers need different names", () => {+ assert.deepEqual(saveTemplateSchema.parse({ name: " Lease " }), {+ name: "Lease",+ });+ assert.equal(saveTemplateSchema.safeParse({ name: " " }).success, false);+ assert.equal(+ saveTemplateSchema.safeParse({ name: "Lease", roleNames: [] }).success,+ false,+ );+ assert.equal(+ saveTemplateSchema.safeParse({ name: "Lease", roleNames: ["x".repeat(61)] })+ .success,+ false,+ );++ const repeated = templateRolesSchema.safeParse([+ { id: "a", name: "Client" },+ { id: "b", name: "client" },+ ]);++ assert.equal(repeated.success, false);+ assert.equal(repeated.error?.issues[0]?.message, duplicateRoleNameMessage);+ assert.equal(+ templateRolesSchema.safeParse([+ { id: "a", name: "Client" },+ { id: "a", name: "Landlord" },+ ]).success,+ false,+ );+ assert.equal(templateRolesSchema.safeParse([]).success, false);+ assert.equal(+ templateRolesSchema.safeParse(+ Array.from({ length: 11 }, (_, index) => ({+ id: String(index),+ name: `Signer ${String(index)}`,+ })),+ ).success,+ false,+ );+});++test("using a template takes a title and one person for each signer", () => {+ const parsed = useTemplateSchema.parse({+ // Anything else about a signer is set on the draft afterwards.+ signers: [{ accessCode: "1234", email: " [email protected] ", name: " Ann " }],+ title: " Lease ",+ });++ assert.deepEqual(parsed, {+ signers: [{ email: "[email protected]", name: "Ann" }],+ title: "Lease",+ });+ assert.equal(+ useTemplateSchema.safeParse({+ signers: [+ { email: "[email protected]", name: "Ann" },+ { email: "[email protected]", name: "Bob" },+ ],+ title: "Lease",+ }).success,+ false,+ );+ assert.equal(+ useTemplateSchema.safeParse({ signers: [], title: "Lease" }).success,+ false,+ );+ assert.equal(+ useTemplateSchema.safeParse({+ signers: [{ email: "not an address", name: "Ann" }],+ title: "Lease",+ }).success,+ false,+ );+});diff --git a/src/lib/schemas/template.ts b/src/lib/schemas/template.tsnew file mode 100644index 0000000..8198d91--- /dev/null+++ b/src/lib/schemas/template.ts@@ -0,0 +1,101 @@+import { z } from "zod";++import { MAX_SIGNERS_PER_ENVELOPE } from "../types/domain.ts";+import {+ emailSchema,+ envelopeTitleSchema,+ idSchema,+ nameSchema,+ nonEmptyStringSchema,+} from "./common.ts";+import { duplicateSignerEmailMessage } from "./signer.ts";++export const MAX_TEMPLATE_ROLE_NAME_LENGTH = 60;++export const templateNameSchema = envelopeTitleSchema;+export const templateRoleNameSchema = nonEmptyStringSchema.max(+ MAX_TEMPLATE_ROLE_NAME_LENGTH,+);+export const duplicateRoleNameMessage =+ "Give each signer in the template a different name.";++/** One place in a template's signing order, such as "Client". */+export const templateRoleSchema = z.object({+ id: idSchema,+ name: templateRoleNameSchema,+});++/** A template's roles, in the order their people will sign. */+export const templateRolesSchema = z+ .array(templateRoleSchema)+ .min(1)+ .max(MAX_SIGNERS_PER_ENVELOPE)+ .superRefine((roles, ctx) => {+ const ids = new Set<string>();+ const names = new Set<string>();++ for (const [index, role] of roles.entries()) {+ const name = role.name.toLowerCase();++ if (names.has(name)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: duplicateRoleNameMessage,+ path: [index, "name"],+ });+ }++ if (ids.has(role.id)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Each signer in the template must be unique.",+ path: [index, "id"],+ });+ }++ ids.add(role.id);+ names.add(name);+ }+ });++/** Saving an envelope as a template. */+export const saveTemplateSchema = z.object({+ name: templateNameSchema,+ // What to call each signer, in signing order. Left out, they are called+ // "Signer 1", "Signer 2" and so on.+ roleNames: z+ .array(templateRoleNameSchema)+ .min(1)+ .max(MAX_SIGNERS_PER_ENVELOPE)+ .optional(),+});++/** Starting an envelope from a template: who fills each role, in order. */+export const useTemplateSchema = z.object({+ signers: z+ .array(z.object({ email: emailSchema, name: nameSchema }))+ .min(1)+ .max(MAX_SIGNERS_PER_ENVELOPE)+ .superRefine((signers, ctx) => {+ const emails = new Set<string>();++ for (const [index, signer] of signers.entries()) {+ const email = signer.email.toLowerCase();++ if (emails.has(email)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: duplicateSignerEmailMessage,+ path: [index, "email"],+ });+ }++ emails.add(email);+ }+ }),+ title: envelopeTitleSchema,+});++export type TemplateRole = z.infer<typeof templateRoleSchema>;+export type SaveTemplateInput = z.infer<typeof saveTemplateSchema>;+export type UseTemplateInput = z.infer<typeof useTemplateSchema>;diff --git a/src/lib/services/storage-keys.test.ts b/src/lib/services/storage-keys.test.tsindex 53aebc4..c37f730 100644--- a/src/lib/services/storage-keys.test.ts+++ b/src/lib/services/storage-keys.test.ts@@ -4,6 +4,7 @@ import { test } from "node:test";import {buildEnvelopeOriginalPdfKey,buildEnvelopeThumbnailKey,+ buildTemplatePdfKey,} from "./storage-keys.ts";const envelopeId = "0b7f6f0e-2f6a-4d0c-9a53-3f0e7c1f9a11";@@ -50,3 +51,19 @@ test("an original in a shared folder does not share its picture", () => {`users/sender/envelopes/${envelopeId}/thumbnail.jpg`,);});++test("a template's document is kept apart from every envelope's", () => {+ const templateKey = buildTemplatePdfKey({+ templateId: envelopeId,+ userId: "sender",+ });++ assert.equal(+ templateKey,+ `users/sender/templates/${envelopeId}/original.pdf`,+ );+ assert.notEqual(+ templateKey,+ buildEnvelopeOriginalPdfKey({ envelopeId, userId: "sender" }),+ );+});diff --git a/src/lib/services/storage-keys.ts b/src/lib/services/storage-keys.tsindex cae244d..04bc610 100644--- a/src/lib/services/storage-keys.ts+++ b/src/lib/services/storage-keys.ts@@ -2,6 +2,7 @@ import path from "node:path";const STORAGE_ROOT_SEGMENT = "users";const ENVELOPE_ROOT_SEGMENT = "envelopes";+const TEMPLATE_ROOT_SEGMENT = "templates";const CERTIFICATE_ROOT_SEGMENT = "certificates";const INTERNAL_CERTIFICATE_FILE_NAME = "internal.pdf";const RECIPIENT_CERTIFICATE_FILE_NAME = "recipient.pdf";@@ -83,6 +84,24 @@ export function buildEnvelopeThumbnailKey(return path.posix.join(folder, "thumbnail.jpg");}+/**+ * A template's own copy of its document. It is a copy, not the file of the+ * envelope it was made from, so neither can take the other's file with it+ * when it is deleted.+ */+export function buildTemplatePdfKey(input: {+ templateId: string;+ userId: string;+}): string {+ return path.posix.join(+ STORAGE_ROOT_SEGMENT,+ input.userId,+ TEMPLATE_ROOT_SEGMENT,+ input.templateId,+ "original.pdf",+ );+}+export function buildEnvelopeSignedPdfKey(input: EnvelopeStorageIdentity,): string {diff --git a/src/lib/templates.dbtest.ts b/src/lib/templates.dbtest.tsnew file mode 100644index 0000000..4e35737--- /dev/null+++ b/src/lib/templates.dbtest.ts@@ -0,0 +1,574 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, 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 { openTestDatabase } from "./db/test-database.ts";+import {+ createDraftEnvelope,+ EnvelopeMutationError,+ getDraftEnvelopeDocumentForUser,+ getPrepareEnvelopeDataForUser,+ getReviewEnvelopeDataForUser,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+} from "./envelopes.ts";+import { runRetentionSweep } from "./retention.ts";+import { buildTemplatePdfKey } from "./services/storage-keys.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import {+ createDraftFromTemplate,+ deleteTemplate,+ getUseTemplateDataForUser,+ listTemplatesForUser,+ saveEnvelopeAsTemplate,+ TemplateError,+} from "./templates.ts";++// Templates against a real Postgres and real files: what a template keeps+// of an envelope, what a draft made from it gets, and that neither leaves+// files behind. Run with `npm run test:db`.++let database: pg.Pool;+let storageDir: string;+let storageService: StorageService;+let sourcePdf: Uint8Array;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-templates-"));+ storageService = createStorageService({+ env: { STORAGE_DRIVER: "local", 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();+ await rm(storageDir, { 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,+ };+}++/** A two-page draft with two signers and one field of each awkward kind. */+async function createPreparedDraft(userId: string) {+ const draft = await createDraftEnvelope(+ userId,+ {+ sourcePdf: { body: sourcePdf, filename: "lease.pdf" },+ title: "Lease for 12 Harbour Road",+ },+ { database, storageService },+ );+ 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);+ const groupId = randomUUID();++ 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 }),+ field(riley!, "dropdown", 0.25, { options: ["Monthly", "Yearly"] }),+ field(casey!, "radio", 0.3, { groupId, label: "Furnished" }),+ field(casey!, "radio", 0.35, { groupId, label: "Unfurnished" }),+ ],+ },+ database,+ );++ return { envelopeId };+}++async function fileExists(key: string): Promise<boolean> {+ return (await storageService.headObject(key)).exists;+}++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;+}++function assertTemplateError(statusCode: number) {+ return (error: unknown): true => {+ assert.ok(error instanceof TemplateError, String(error));+ assert.equal(error.statusCode, statusCode);++ return true;+ };+}++test("a template keeps the document, the fields and the order, and no one's name", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);+ const template = await saveEnvelopeAsTemplate(+ userId,+ envelopeId,+ { name: " Residential lease ", roleNames: ["Tenant", "Landlord"] },+ { database, storageService },+ );++ assert.equal(template.name, "Residential lease");+ assert.equal(+ await fileExists(buildTemplatePdfKey({ templateId: template.id, userId })),+ true,+ );++ const stored = await database.query<{ everything: string }>(+ `select row_to_json(t)::text as everything from templates t where id = $1`,+ [template.id],+ );++ for (const personal of ["Riley", "Casey", "riley@", "casey@"]) {+ assert.ok(!stored.rows[0]!.everything.includes(personal), personal);+ }++ assert.deepEqual(await listTemplatesForUser(userId, database), [+ {+ createdAtLabel: (await listTemplatesForUser(userId, database))[0]!+ .createdAtLabel,+ // The two radio buttons are one question.+ fieldCountLabel: "5 fields",+ id: template.id,+ name: "Residential lease",+ pageCountLabel: "2 pages",+ roleNames: ["Tenant", "Landlord"],+ },+ ]);++ const form = await getUseTemplateDataForUser(userId, template.id, database);++ assert.deepEqual(+ form?.roles.map((role) => role.name),+ ["Tenant", "Landlord"],+ );+});++test("a draft made from a template has the fields on the people named for it", async () => {+ const userId = await createUser();+ const { envelopeId: originalId } = await createPreparedDraft(userId);+ const template = await saveEnvelopeAsTemplate(+ userId,+ originalId,+ { name: "Lease" },+ { database, storageService },+ );+ const made = await createDraftFromTemplate(+ userId,+ template.id,+ {+ signers: [+ { email: "[email protected]", name: "Tess Tenant" },+ { email: "[email protected]", name: "Lou Landlord" },+ ],+ title: "Lease for 4 Mill Lane",+ },+ { database, storageService },+ );++ assert.notEqual(made.envelopeId, originalId);+ assert.equal(made.redirectPath, `/envelopes/${made.envelopeId}/review`);++ const draft = await getPrepareEnvelopeDataForUser(userId, made.envelopeId, {+ database,+ });++ assert.ok(draft);+ assert.equal(draft.status, "draft");+ assert.equal(draft.title, "Lease for 4 Mill Lane");+ assert.equal(draft.pageCount, 2);+ assert.deepEqual(+ draft.signers.map((signer) => [signer.order, signer.name, signer.email]),+ [+ [1, "Tess Tenant", "[email protected]"],+ [2, "Lou Landlord", "[email protected]"],+ ],+ );++ const [tess, lou] = draft.signers.map((signer) => signer.id);+ const summary = draft.fields+ .map((placed) => ({+ label: placed.label,+ options: placed.options,+ page: placed.page,+ required: placed.required,+ signer: placed.signerId === tess ? "tess" : "lou",+ type: placed.type,+ }))+ .sort((left, right) =>+ `${left.type}${left.label ?? ""}`.localeCompare(+ `${right.type}${right.label ?? ""}`,+ ),+ );++ assert.deepEqual(summary, [+ {+ label: undefined,+ options: ["Monthly", "Yearly"],+ page: 1,+ required: true,+ signer: "tess",+ type: "dropdown",+ },+ {+ label: "Furnished",+ options: undefined,+ page: 1,+ required: true,+ signer: "lou",+ type: "radio",+ },+ {+ label: "Unfurnished",+ options: undefined,+ page: 1,+ required: true,+ signer: "lou",+ type: "radio",+ },+ {+ label: undefined,+ options: undefined,+ page: 1,+ required: true,+ signer: "tess",+ type: "signature",+ },+ {+ label: undefined,+ options: undefined,+ page: 2,+ required: true,+ signer: "lou",+ type: "signature",+ },+ {+ label: "Unit number",+ options: undefined,+ page: 1,+ required: false,+ signer: "tess",+ type: "text",+ },+ ]);+ assert.ok(lou);++ const radios = draft.fields.filter((placed) => placed.type === "radio");++ assert.equal(radios[0]!.groupId, radios[1]!.groupId);+ // Nothing anyone entered came along, and it is ready to send.+ assert.ok(draft.fields.every((placed) => !placed.value));+ assert.equal(+ (await getReviewEnvelopeDataForUser(userId, made.envelopeId, database))+ ?.canSend,+ true,+ );++ // The draft has its own copy of the document: deleting the template+ // takes the template's copy and nothing else.+ await deleteTemplate(userId, template.id, { database, storageService });++ assert.equal(+ await fileExists(buildTemplatePdfKey({ templateId: template.id, userId })),+ false,+ );+ assert.deepEqual(await listTemplatesForUser(userId, database), []);++ for (const envelopeId of [made.envelopeId, originalId]) {+ const document = await getDraftEnvelopeDocumentForUser(userId, envelopeId, {+ database,+ storageService,+ });++ assert.equal(document.body.length, sourcePdf.length);+ }+});++test("a template belongs to the person who saved it", async () => {+ const owner = await createUser();+ const stranger = await createUser();+ const { envelopeId } = await createPreparedDraft(owner);+ const options = { database, storageService };+ const people = {+ signers: [+ { email: "[email protected]", name: "A" },+ { email: "[email protected]", name: "B" },+ ],+ title: "Lease",+ };++ await assert.rejects(+ saveEnvelopeAsTemplate(stranger, envelopeId, { name: "Mine now" }, options),+ assertTemplateError(404),+ );++ const template = await saveEnvelopeAsTemplate(+ owner,+ envelopeId,+ { name: "Lease" },+ options,+ );++ assert.deepEqual(await listTemplatesForUser(stranger, database), []);+ assert.equal(+ await getUseTemplateDataForUser(stranger, template.id, database),+ null,+ );+ await assert.rejects(+ createDraftFromTemplate(stranger, template.id, people, options),+ assertTemplateError(404),+ );+ await assert.rejects(+ deleteTemplate(stranger, template.id, options),+ assertTemplateError(404),+ );+ assert.equal(await countEnvelopes(stranger), 0);+ assert.equal((await listTemplatesForUser(owner, database)).length, 1);+});++test("what a template is given is checked", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);+ const options = { database, storageService };+ const save = (input: unknown) =>+ saveEnvelopeAsTemplate(userId, envelopeId, input, options);++ await assert.rejects(save({ name: " " }), ZodError);+ await assert.rejects(+ save({ name: "Lease", roleNames: ["Tenant", "tenant"] }),+ ZodError,+ );+ // One name for two signers: the envelope is not what the form showed.+ await assert.rejects(+ save({ name: "Lease", roleNames: ["Tenant"] }),+ assertTemplateError(409),+ );+ assert.deepEqual(await listTemplatesForUser(userId, database), []);++ // An envelope nobody signs has no order to keep.+ const bare = await createDraftEnvelope(+ userId,+ { sourcePdf: { body: sourcePdf, filename: "bare.pdf" }, title: "Bare" },+ options,+ );++ await assert.rejects(+ saveEnvelopeAsTemplate(userId, bare.envelope.id, { name: "Bare" }, options),+ assertTemplateError(400),+ );++ const template = await save({ name: "Lease" });+ const use = (input: unknown) =>+ createDraftFromTemplate(userId, template.id, input, options);+ const before = await countEnvelopes(userId);++ await assert.rejects(+ use({ signers: [{ email: "[email protected]", name: "A" }], title: "Lease" }),+ assertTemplateError(400),+ );+ await assert.rejects(+ use({+ signers: [+ { email: "[email protected]", name: "A" },+ { email: "[email protected]", name: "B" },+ ],+ title: "Lease",+ }),+ ZodError,+ );+ await assert.rejects(+ use({+ signers: [+ { email: "[email protected]", name: "A" },+ { email: "[email protected]", name: "B" },+ ],+ title: "",+ }),+ ZodError,+ );+ assert.equal(await countEnvelopes(userId), before);+});++test("a draft that cannot be finished is not left half made", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);+ const options = { database, storageService };+ const template = await saveEnvelopeAsTemplate(+ userId,+ envelopeId,+ { name: "Lease" },+ options,+ );+ const people = {+ signers: [+ { email: "[email protected]", name: "A" },+ { email: "[email protected]", name: "B" },+ ],+ title: "Lease",+ };+ const before = await countEnvelopes(userId);++ // A field on a page the document does not have: well formed, so it is+ // only found out once the draft exists.+ await database.query(+ `+ update templates+ set fields = jsonb_set(fields, '{0,page}', '9')+ where id = $1+ `,+ [template.id],+ );+ await assert.rejects(+ createDraftFromTemplate(userId, template.id, people, options),+ EnvelopeMutationError,+ );+ assert.equal(await countEnvelopes(userId), before);++ // Contents the application would never have written.+ await database.query(+ `update templates set fields = '[{"type":"stamp"}]'::jsonb where id = $1`,+ [template.id],+ );+ await assert.rejects(+ createDraftFromTemplate(userId, template.id, people, options),+ assertTemplateError(409),+ );+ // The list still opens, so the template can be deleted.+ assert.equal((await listTemplatesForUser(userId, database)).length, 1);++ // The document itself has gone missing.+ const second = await saveEnvelopeAsTemplate(+ userId,+ envelopeId,+ { name: "Lease again" },+ options,+ );++ await storageService.deleteObject(+ buildTemplatePdfKey({ templateId: second.id, userId }),+ );+ await assert.rejects(+ createDraftFromTemplate(userId, second.id, people, options),+ assertTemplateError(409),+ );+ assert.equal(await countEnvelopes(userId), before);+});++test("the database refuses a template without signers", async () => {+ const userId = await createUser();+ const insert = (roles: string) =>+ database.query(+ `+ insert into templates (+ id, user_id, name, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, roles, fields+ ) values ($1, $2, 'T', 'k', 'f.pdf', 1, 1, $3::jsonb, '[]'::jsonb)+ `,+ [randomUUID(), userId, roles],+ );++ await assert.rejects(insert("[]"), /templates_roles_check/);+ await assert.rejects(insert('{"name":"x"}'), /templates_roles_check/);+ await insert('[{"id":"r1","name":"Client"}]');+});++test("closing the account removes its templates and their documents", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);+ const template = await saveEnvelopeAsTemplate(+ userId,+ envelopeId,+ { name: "Lease" },+ { database, storageService },+ );+ const key = buildTemplatePdfKey({ templateId: template.id, userId });++ assert.equal(await fileExists(key), true);++ await database.query(+ `+ insert into account_closure_requests+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)+ values ($1, 1, 1, 1, 1)+ `,+ [userId],+ );++ const summary = await runRetentionSweep({ database, storageService });++ assert.ok(!summary.accountPurgeFailures.includes(userId));+ assert.equal(await fileExists(key), false);+ assert.equal(+ (+ await database.query(`select 1 from templates where user_id = $1`, [+ userId,+ ])+ ).rowCount,+ 0,+ );+});diff --git a/src/lib/templates.ts b/src/lib/templates.tsnew file mode 100644index 0000000..dc932cc--- /dev/null+++ b/src/lib/templates.ts@@ -0,0 +1,526 @@+import { randomUUID } from "node:crypto";++import {+ type DbExecutor,+ type DbPool,+ getDb,+ queryMany,+ queryOne,+} from "./db/connection.ts";+import {+ createDraftEnvelope,+ deleteDraftEnvelope,+ EnvelopeDocumentAccessError,+ getDraftEnvelopeDocumentForUser,+ getPrepareEnvelopeDataForUser,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+} from "./envelopes.ts";+import { countAnswerableFields } from "./field-choices.ts";+import { fieldPlacementListSchema } from "./schemas/field.ts";+import {+ saveTemplateSchema,+ templateRolesSchema,+ useTemplateSchema,+ type TemplateRole,+} from "./schemas/template.ts";+import { buildTemplatePdfKey } from "./services/storage-keys.ts";+import {+ createStorageService,+ StorageObjectNotFoundError,+ type StorageService,+} from "./services/storage.ts";++// A template is a document, the fields placed on it and its signing order,+// kept so the same thing can be sent again. It names no one: each place in+// the signing order is a role ("Client"), filled in when the template is+// used. It is made from an envelope and turned back into a draft envelope,+// so everything a draft can hold, a template can hold.++/** A guard on storage, not a product limit anyone should run into. */+export const MAX_TEMPLATES_PER_USER = 100;++const UNUSABLE_TEMPLATE_MESSAGE =+ "This template can no longer be used. Delete it, then save the document as a template again.";++export class TemplateError extends Error {+ readonly statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.name = "TemplateError";+ this.statusCode = statusCode;+ }+}++type TemplateOptions = {+ database?: DbPool;+ storageService?: StorageService;+};++type TemplateRow = {+ createdAt: number;+ fields: unknown;+ id: string;+ name: string;+ pageCount: number;+ roles: unknown;+ sourcePdfFilename: string;+ sourcePdfKey: string;+};++export type TemplateListItem = {+ createdAtLabel: string;+ fieldCountLabel: string;+ id: string;+ name: string;+ pageCountLabel: string;+ /** In signing order. */+ roleNames: string[];+};++/** What the "use this template" form needs. */+export type UseTemplateData = {+ fieldCountLabel: string;+ id: string;+ name: string;+ pageCountLabel: string;+ roles: TemplateRole[];+};++export type SavedTemplate = {+ id: string;+ name: string;+};++export type DraftFromTemplate = {+ envelopeId: string;+ redirectPath: string;+};++const TEMPLATE_COLUMNS = `+ id,+ name,+ page_count AS "pageCount",+ roles,+ fields,+ source_pdf_key AS "sourcePdfKey",+ source_pdf_filename AS "sourcePdfFilename",+ created_at AS "createdAt"+`;++const dateFormatter = new Intl.DateTimeFormat("en-US", {+ day: "numeric",+ month: "short",+ timeZone: "UTC",+ year: "numeric",+});++function countLabel(count: number, singular: string): string {+ return `${String(count)} ${count === 1 ? singular : `${singular}s`}`;+}++// A list must still open when one template's stored contents cannot be+// read, so the names and the count are taken leniently here. Using a+// template checks them properly.+function readRoleNames(roles: unknown): string[] {+ if (!Array.isArray(roles)) {+ return [];+ }++ return roles.flatMap((role: unknown) =>+ typeof role === "object" &&+ role !== null &&+ "name" in role &&+ typeof role.name === "string"+ ? [role.name]+ : [],+ );+}++function countFields(fields: unknown): number {+ if (!Array.isArray(fields)) {+ return 0;+ }++ return countAnswerableFields(+ fields.flatMap((field: unknown) =>+ typeof field === "object" && field !== null+ ? [+ {+ groupId:+ "groupId" in field && typeof field.groupId === "string"+ ? field.groupId+ : undefined,+ type: "type" in field ? String(field.type) : "",+ },+ ]+ : [],+ ),+ () => true,+ );+}++async function getTemplateRow(+ userId: string,+ templateId: string,+ database: DbExecutor,+): Promise<TemplateRow | null> {+ return queryOne<TemplateRow>(+ database,+ `SELECT ${TEMPLATE_COLUMNS} FROM templates WHERE id = $1 AND user_id = $2`,+ [templateId, userId],+ );+}++export async function listTemplatesForUser(+ userId: string,+ database: DbExecutor = getDb(),+): Promise<TemplateListItem[]> {+ const rows = await queryMany<TemplateRow>(+ database,+ `+ SELECT ${TEMPLATE_COLUMNS}+ FROM templates+ WHERE user_id = $1+ ORDER BY created_at DESC, id ASC+ `,+ [userId],+ );++ return rows.map((row) => ({+ createdAtLabel: dateFormatter.format(new Date(row.createdAt * 1000)),+ fieldCountLabel: countLabel(countFields(row.fields), "field"),+ id: row.id,+ name: row.name,+ pageCountLabel: countLabel(row.pageCount, "page"),+ roleNames: readRoleNames(row.roles),+ }));+}++export async function getUseTemplateDataForUser(+ userId: string,+ templateId: string,+ database: DbExecutor = getDb(),+): Promise<UseTemplateData | null> {+ const row = await getTemplateRow(userId, templateId, database);++ if (!row) {+ return null;+ }++ const roles = templateRolesSchema.safeParse(row.roles);++ if (!roles.success) {+ throw new TemplateError(UNUSABLE_TEMPLATE_MESSAGE, 409);+ }++ return {+ fieldCountLabel: countLabel(countFields(row.fields), "field"),+ id: row.id,+ name: row.name,+ pageCountLabel: countLabel(row.pageCount, "page"),+ roles: roles.data,+ };+}++/**+ * 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+ * are is copied, never what was entered in them, and the signers' names+ * and addresses are left behind.+ */+export async function saveEnvelopeAsTemplate(+ userId: string,+ envelopeId: string,+ input: unknown,+ {+ database = getDb(),+ storageService = createStorageService(),+ }: TemplateOptions = {},+): Promise<SavedTemplate> {+ const parsedInput = saveTemplateSchema.parse(input);+ const envelope = await getPrepareEnvelopeDataForUser(userId, envelopeId, {+ database,+ });++ if (!envelope) {+ throw new TemplateError("Envelope not found.", 404);+ }++ const signers = [...envelope.signers].sort(+ (left, right) => left.order - right.order,+ );++ if (signers.length === 0) {+ throw new TemplateError(+ "Add at least one signer before saving this as a template.",+ 400,+ );+ }++ const roleNames =+ parsedInput.roleNames ??+ signers.map((_, index) => `Signer ${String(index + 1)}`);++ if (roleNames.length !== signers.length) {+ throw new TemplateError(+ "The signers of this envelope have changed. Reload the page and try again.",+ 409,+ );+ }++ const roles = templateRolesSchema.parse(+ roleNames.map((name) => ({ id: randomUUID(), name })),+ );+ const roleIdBySignerId = new Map(+ signers.map((signer, index) => [signer.id, roles[index]!.id] as const),+ );+ // Where each field is and what kind it is. Anything a signer entered+ // stays with the envelope.+ const fields = fieldPlacementListSchema.parse(+ envelope.fields.flatMap((field) => {+ const roleId = roleIdBySignerId.get(field.signerId);++ return roleId+ ? [+ {+ groupId: field.groupId,+ height: field.height,+ label: field.label,+ options: field.options,+ page: field.page,+ required: field.required,+ signerId: roleId,+ type: field.type,+ width: field.width,+ x: field.x,+ y: field.y,+ },+ ]+ : [];+ }),+ );+ const existing = await queryOne<{ total: number }>(+ database,+ `SELECT count(*)::int AS total FROM templates WHERE user_id = $1`,+ [userId],+ );++ if ((existing?.total ?? 0) >= MAX_TEMPLATES_PER_USER) {+ throw new TemplateError(+ `You have ${String(MAX_TEMPLATES_PER_USER)} templates, which is the most an account can keep. Delete one to save another.`,+ 409,+ );+ }++ let document: Awaited<ReturnType<typeof getDraftEnvelopeDocumentForUser>>;++ try {+ document = await getDraftEnvelopeDocumentForUser(userId, envelopeId, {+ database,+ storageService,+ });+ } catch (error) {+ if (error instanceof EnvelopeDocumentAccessError) {+ throw new TemplateError(+ "This envelope's document is no longer available, so it cannot be saved as a template.",+ error.statusCode,+ );+ }++ throw error;+ }++ const templateId = randomUUID();+ const sourcePdfKey = buildTemplatePdfKey({ templateId, userId });+ const now = Math.floor(Date.now() / 1000);++ await storageService.putObject({+ body: document.body,+ contentType: "application/pdf",+ key: sourcePdfKey,+ });++ try {+ await database.query(+ `+ INSERT INTO templates (+ id,+ user_id,+ name,+ source_pdf_key,+ source_pdf_filename,+ source_pdf_size_bytes,+ page_count,+ roles,+ fields,+ created_at,+ updated_at+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $10)+ `,+ [+ templateId,+ userId,+ parsedInput.name,+ sourcePdfKey,+ document.fileName,+ document.body.length,+ envelope.pageCount,+ JSON.stringify(roles),+ JSON.stringify(fields),+ now,+ ],+ );+ } catch (error) {+ // Nothing points at the copy, so nothing would ever remove it.+ await storageService.deleteObject(sourcePdfKey).catch(() => undefined);+ throw error;+ }++ return { id: templateId, name: parsedInput.name };+}++/**+ * Starts a draft envelope from a template: the template's document and+ * fields, with a person named for each role. The draft is an ordinary one+ * from then on, and changing it does not change the template.+ */+export async function createDraftFromTemplate(+ userId: string,+ templateId: string,+ input: unknown,+ {+ database = getDb(),+ storageService = createStorageService(),+ }: TemplateOptions = {},+): Promise<DraftFromTemplate> {+ const parsedInput = useTemplateSchema.parse(input);+ const template = await getTemplateRow(userId, templateId, database);++ if (!template) {+ throw new TemplateError("Template not found.", 404);+ }++ const roles = templateRolesSchema.safeParse(template.roles);+ const fields = fieldPlacementListSchema.safeParse(template.fields);++ if (!roles.success || !fields.success) {+ throw new TemplateError(UNUSABLE_TEMPLATE_MESSAGE, 409);+ }++ const roleIds = new Set(roles.data.map((role) => role.id));++ if (fields.data.some((field) => !roleIds.has(field.signerId))) {+ throw new TemplateError(UNUSABLE_TEMPLATE_MESSAGE, 409);+ }++ if (parsedInput.signers.length !== roles.data.length) {+ throw new TemplateError(+ "Name one person for each signer in this template.",+ 400,+ );+ }++ let sourcePdf: Uint8Array;++ try {+ sourcePdf = (await storageService.getObject(template.sourcePdfKey)).body;+ } catch (error) {+ if (error instanceof StorageObjectNotFoundError) {+ throw new TemplateError(UNUSABLE_TEMPLATE_MESSAGE, 409);+ }++ throw error;+ }++ const draft = await createDraftEnvelope(+ userId,+ {+ sourcePdf: {+ body: sourcePdf,+ contentType: "application/pdf",+ filename: template.sourcePdfFilename,+ },+ title: parsedInput.title,+ },+ { database, storageService },+ );+ const envelopeId = draft.envelope.id;++ try {+ const saved = await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ { signers: parsedInput.signers },+ database,+ );+ const signerIdByOrder = new Map(+ saved.signers.map((signer) => [signer.signOrder, signer.id] as const),+ );+ const signerIdByRoleId = new Map(+ roles.data.map(+ (role, index) => [role.id, signerIdByOrder.get(index + 1)] as const,+ ),+ );++ await replaceDraftEnvelopeFields(+ userId,+ envelopeId,+ {+ fields: fields.data.map((field) => ({+ ...field,+ signerId: signerIdByRoleId.get(field.signerId),+ })),+ },+ database,+ );+ } catch (error) {+ // Half a draft is worse than none: the sender would find a document+ // with no fields on it and no sign of why.+ await deleteDraftEnvelope(userId, envelopeId, {+ database,+ storageService,+ }).catch(() => undefined);++ throw error;+ }++ return {+ envelopeId,+ // Everything is already in place, so the sender lands where they can+ // check it and send. The earlier steps are one click back.+ redirectPath: `/envelopes/${envelopeId}/review`,+ };+}++export async function deleteTemplate(+ userId: string,+ templateId: string,+ {+ database = getDb(),+ storageService = createStorageService(),+ }: TemplateOptions = {},+): Promise<void> {+ const deleted = await queryOne<{ sourcePdfKey: string }>(+ database,+ `+ DELETE FROM templates+ WHERE id = $1 AND user_id = $2+ RETURNING source_pdf_key AS "sourcePdfKey"+ `,+ [templateId, userId],+ );++ if (!deleted) {+ throw new TemplateError("Template not found.", 404);+ }++ // Envelopes made from the template have their own copies of the document.+ await storageService.deleteObject(deleted.sourcePdfKey).catch((error) => {+ console.error(+ `Failed to delete the document of template ${templateId}:`,+ error,+ );+ });+}