Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Copy a finished envelope into a new draft
Matt Van Horn719e05e2fb09
diff --git a/db/migrations/20261115100000_copied_audit_event.sql b/db/migrations/20261115100000_copied_audit_event.sqlnew file mode 100644index 0000000..17682ab--- /dev/null+++ b/db/migrations/20261115100000_copied_audit_event.sql@@ -0,0 +1,27 @@+-- A draft made by copying an earlier envelope records that it was copied,+-- so its timeline is not the same as a document that was just uploaded.++alter table public.audit_events+ drop constraint if exists audit_events_event_check;++alter table public.audit_events+ add constraint audit_events_event_check+ check (event in (+ 'created',+ 'sent',+ 'viewed',+ 'consented',+ 'verified',+ 'verification_failed',+ 'signed',+ 'declined',+ 'reminded_manual',+ 'email_sent',+ 'completed',+ 'voided',+ 'deadline_changed',+ 'expired',+ 'reminded_auto',+ 'reauthentication_failed',+ 'copied'+ ));diff --git a/src/app/api/envelopes/[id]/copy/route.ts b/src/app/api/envelopes/[id]/copy/route.tsnew file mode 100644index 0000000..b0f81a8--- /dev/null+++ b/src/app/api/envelopes/[id]/copy/route.ts@@ -0,0 +1,87 @@+import { NextResponse } from "next/server";+import { ZodError } from "zod";++import { requireVerifiedSenderSession } from "@/lib/auth/route-session";+import { getDb } from "@/lib/db/connection";+import { copyEnvelopeToDraft, 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";++type EnvelopeCopyRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++const noStore = { "cache-control": "private, no-store" };++// Starts a new draft from an envelope that has already gone out. Nothing+// is emailed, and the original is left as it is.++export async function POST(+ request: Request,+ context: EnvelopeCopyRouteContext,+) {+ const sessionResult = await requireVerifiedSenderSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ const { id } = await context.params;+ const ipAddress = getClientIpAddress(request.headers);+ const rateLimitResponse = await applyRateLimit({+ category: "envelope_copy",+ key: buildRateLimitKey(["envelope-copy", session.user.id, id]),+ limit: 20,+ request,+ userId: session.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ rateLimitResponse.headers.set("cache-control", "private, no-store");+ return rateLimitResponse;+ }++ try {+ const result = await copyEnvelopeToDraft(session.user.id, id, {+ actorEmail: session.user.email,+ database: getDb(),+ });++ return NextResponse.json(result, { headers: noStore, status: 201 });+ } catch (error) {+ if (error instanceof ZodError) {+ return NextResponse.json(+ { error: error.issues[0]?.message ?? "Invalid copy request." },+ { headers: noStore, status: 400 },+ );+ }++ if (error instanceof EnvelopeMutationError) {+ return NextResponse.json(+ { error: error.message },+ { headers: noStore, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "envelope_copy_failure",+ ipAddress,+ message: "Unexpected failure while copying an envelope to a draft.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "Unable to copy this envelope." },+ { headers: noStore, status: 500 },+ );+ }+}diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex fd0be9a..f51ad81 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -71,6 +71,7 @@ type EnvelopeDetailRecord = {type ModalState =| "change-deadline"| "change-reminders"+ | "copy-draft"| "delete-draft"| "save-template"| "void-envelope"@@ -129,6 +130,7 @@ export function EnvelopeDetailShell({const [actionError, setActionError] = useState<string | null>(null);const [isChangingDeadline, setIsChangingDeadline] = useState(false);const [isChangingReminders, setIsChangingReminders] = useState(false);+ const [isCopyingDraft, setIsCopyingDraft] = useState(false);const [isDeletingDraft, setIsDeletingDraft] = useState(false);const [isSendingReminder, setIsSendingReminder] = useState(false);const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);@@ -312,6 +314,39 @@ export function EnvelopeDetailShell({}}+ async function handleConfirmCopyDraft() {+ setActionError(null);+ setIsCopyingDraft(true);++ try {+ const response = await fetch(`/api/envelopes/${envelopeId}/copy`, {+ method: "POST",+ });+ const payload = (await response.json().catch(() => null)) as {+ error?: string;+ id?: string;+ } | null;++ if (response.ok && typeof payload?.id === "string") {+ // A full page load so the new draft is fetched from the server.+ // eslint-disable-next-line @next/next/no-location-assign-relative-destination+ window.location.assign(`/envelopes/${encodeURIComponent(payload.id)}`);+ return;+ }++ if (response.status === 404) {+ window.location.reload();+ return;+ }++ setActionError(payload?.error ?? "Unable to copy this envelope.");+ } catch {+ setActionError("Unable to copy this envelope.");+ } finally {+ setIsCopyingDraft(false);+ }+ }+async function handleConfirmDeleteDraft() {setActionError(null);setIsDeletingDraft(true);@@ -483,18 +518,29 @@ export function EnvelopeDetailShell({) : null}{activeRecord.status !== "draft" ? (- <ShellButton- onClick={() =>- // A file download from an API route, not a page navigation.- // eslint-disable-next-line @next/next/no-location-assign-relative-destination- window.location.assign(- `/api/envelopes/${encodeURIComponent(envelopeId)}/audit`,- )- }- variant="secondary"- >- Export audit trail- </ShellButton>+ <>+ <ShellButton+ onClick={() => {+ setActionError(null);+ setActiveModal("copy-draft");+ }}+ variant="secondary"+ >+ Copy to new draft+ </ShellButton>+ <ShellButton+ onClick={() =>+ // A file download from an API route, not a page navigation.+ // eslint-disable-next-line @next/next/no-location-assign-relative-destination+ window.location.assign(+ `/api/envelopes/${encodeURIComponent(envelopeId)}/audit`,+ )+ }+ variant="secondary"+ >+ Export audit trail+ </ShellButton>+ </>) : null}</div></div>@@ -748,6 +794,15 @@ export function EnvelopeDetailShell({/>) : null}+ {activeModal === "copy-draft" ? (+ <CopyDraftDialog+ errorMessage={actionError}+ onCancel={() => setActiveModal(null)}+ onConfirm={handleConfirmCopyDraft}+ processing={isCopyingDraft}+ />+ ) : null}+{activeModal === "save-template" ? (<SaveTemplateDialogenvelopeId={envelopeId}@@ -814,6 +869,72 @@ export function EnvelopeDetailShell({);}+type CopyDraftDialogProps = {+ errorMessage?: string | null;+ onCancel: () => void;+ onConfirm: () => void | Promise<void>;+ processing?: boolean;+};++function CopyDraftDialog({+ errorMessage,+ onCancel,+ onConfirm,+ processing = false,+}: CopyDraftDialogProps) {+ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !processing) {+ onCancel();+ }+ }}+ >+ <DialogContent className="max-w-md sm:p-8" showCloseButton={false}>+ <div className="space-y-4">+ <DialogHeader className="space-y-3">+ <DialogTitle>Copy to a new draft</DialogTitle>+ <DialogDescription asChild>+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">+ <p>+ This starts a new draft with the same document, the same+ people and the same fields. Nothing that was filled in is+ copied.+ </p>+ <p>+ Access codes are not copied: they are stored hashed, so they+ cannot be brought across. You can set new ones before sending.+ </p>+ <p>Nobody is emailed, and this envelope is left as it is.</p>+ </div>+ </DialogDescription>+ </DialogHeader>++ {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={processing}+ onClick={onCancel}+ variant="secondary"+ >+ Cancel+ </ShellButton>+ <ShellButton loading={processing} onClick={onConfirm}>+ {processing ? "Copying..." : "Copy to new draft"}+ </ShellButton>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}+type DeadlineDialogProps = {errorMessage?: string | null;expired: boolean;diff --git a/src/lib/envelope-copy.dbtest.ts b/src/lib/envelope-copy.dbtest.tsnew file mode 100644index 0000000..9dc5b60--- /dev/null+++ b/src/lib/envelope-copy.dbtest.ts@@ -0,0 +1,755 @@+import assert from "node:assert/strict";+import { createHash, 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 {+ copyEnvelopeToDraft,+ createDraftEnvelope,+ deleteDraftEnvelope,+ EnvelopeMutationError,+ getDraftEnvelopeDocumentForUser,+ getDraftSignerStepDataForUser,+ getEnvelopeDetailDataForUser,+ getPrepareEnvelopeDataForUser,+ listCopyRecipientsForEnvelopeId,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+ saveEnvelopeThumbnailForUser,+} from "./envelopes.ts";+import { deleteEnvelopesAndFiles } from "./retention.ts";+import {+ listAuditEventsForEnvelope,+ verifyAuditChain,+} from "./services/audit.ts";+import {+ buildEnvelopeOriginalPdfKey,+ buildEnvelopeThumbnailKey,+} from "./services/storage-keys.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";++// Copying a finished envelope into a new draft, against a real Postgres+// and real files. Run with `npm run test:db`.++let database: pg.Pool;+let storageDir: string;+let storageService: StorageService;+let sourcePdf: Uint8Array;+const createdUsers: string[] = [];++const THUMBNAIL = Uint8Array.from([+ 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x02, 0x6d, 0x01, 0xe0, 0x03, 0x01,+ 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xd9,+]);++before(async () => {+ database = await openTestDatabase();+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-envelope-copy-"));+ 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 });+});++function sha256(bytes: Uint8Array): string {+ return createHash("sha256").update(bytes).digest("hex");+}++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,+ };+}++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,+ {+ copyRecipients: [{ email: "[email protected]", name: "Zofia Copy" }],+ signers: [+ {+ accessCode: "secret12",+ email: "[email protected]",+ name: "Riley Recipient",+ requireEmailCode: true,+ },+ {+ email: "[email protected]",+ name: "Casey Second",+ requireEmailCode: false,+ },+ ],+ },+ 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 { casey: casey!, envelopeId, groupId, riley: riley! };+}++async function markNotDraft(+ envelopeId: string,+ status: "completed" | "declined" | "sent" | "voided",+ extra: {+ expiresAt?: number | null;+ part11?: boolean;+ reminderIntervalDays?: number | null;+ } = {},+) {+ const now = Math.floor(Date.now() / 1000);++ await database.query(+ `+ update envelopes+ set+ status = $2,+ sent_at = $3,+ completed_at = $4,+ declined_at = $5,+ voided_at = $6,+ expires_at = $7,+ reminder_interval_days = $8,+ part11 = $9+ where id = $1+ `,+ [+ envelopeId,+ status,+ now - 3600,+ status === "completed" ? now : null,+ status === "declined" ? now : null,+ status === "voided" ? now : null,+ extra.expiresAt === undefined ? now + 7 * 24 * 60 * 60 : extra.expiresAt,+ extra.reminderIntervalDays === undefined ? 3 : extra.reminderIntervalDays,+ extra.part11 ?? true,+ ],+ );+ const signerStatus =+ status === "completed"+ ? "signed"+ : status === "declined"+ ? "declined"+ : "notified";++ await database.query(+ `+ update signers+ set+ status = 'pending',+ signing_token_hash = encode(sha256(id::bytea), 'hex'),+ signing_token_expires_at = $2+ where envelope_id = $1 and role = 'signer'+ `,+ [envelopeId, now + 86_400],+ );+ await database.query(+ `+ update signers+ set+ status = $2,+ signed_at = $3,+ declined_at = $4+ where envelope_id = $1 and role = 'signer' and sign_order = 1+ `,+ [+ envelopeId,+ signerStatus,+ status === "completed" ? now : null,+ status === "declined" ? now : null,+ ],+ );++ if (status === "completed") {+ await database.query(+ `+ update signers+ set status = 'signed', signed_at = $2+ where envelope_id = $1 and role = 'signer' and sign_order > 1+ `,+ [envelopeId, now],+ );+ }+ await database.query(+ `+ update fields+ set+ value = case+ when type in ('signature', 'initials', 'text', 'number', 'dropdown', 'date')+ then 'filled'+ else value+ end,+ checked = case+ when type in ('checkbox', 'radio') then true+ else checked+ end,+ input_method = case+ when type in ('signature', 'initials') then 'typed'+ else input_method+ end,+ submitted_at = $2+ where envelope_id = $1+ `,+ [envelopeId, now],+ );+}++async function dumpEnvelope(envelopeId: string) {+ const envelope = await database.query<{ row: string }>(+ `select row_to_json(e)::text as row from envelopes e where id = $1`,+ [envelopeId],+ );+ const signers = await database.query<{ row: string }>(+ `select row_to_json(s)::text as row from signers s where envelope_id = $1 order by sign_order, id`,+ [envelopeId],+ );+ const fields = await database.query<{ row: string }>(+ `select row_to_json(f)::text as row from fields f where envelope_id = $1 order by page, created_at, id`,+ [envelopeId],+ );+ const pages = await database.query<{ row: string }>(+ `select row_to_json(p)::text as row from envelope_pages p where envelope_id = $1 order by page_number, id`,+ [envelopeId],+ );+ const audit = await database.query<{ row: string }>(+ `select row_to_json(a)::text as row from audit_events a where envelope_id = $1 order by created_at, id`,+ [envelopeId],+ );++ return {+ audit: audit.rows.map((row) => row.row),+ envelope: envelope.rows[0]!.row,+ fields: fields.rows.map((row) => row.row),+ pages: pages.rows.map((row) => row.row),+ signers: signers.rows.map((row) => row.row),+ };+}++async function signerChecks(envelopeId: string) {+ const result = await database.query<{+ access_code_hash: string | null;+ email: string;+ require_email_code: boolean;+ signature_meaning: string | null;+ signing_token_hash: string | null;+ status: string;+ }>(+ `+ select+ email,+ status,+ access_code_hash,+ require_email_code,+ signature_meaning,+ signing_token_hash+ from signers+ where envelope_id = $1 and role = 'signer'+ order by sign_order+ `,+ [envelopeId],+ );++ return result.rows;+}++async function envelopeColumns(envelopeId: string) {+ const result = await database.query<{+ expires_at: number | null;+ part11: boolean;+ reminder_interval_days: number | null;+ source_pdf_hash: string;+ source_pdf_key: string;+ status: string;+ title: string;+ }>(+ `+ select+ status,+ title,+ source_pdf_key,+ source_pdf_hash,+ expires_at,+ reminder_interval_days,+ part11+ from envelopes+ where id = $1+ `,+ [envelopeId],+ );++ return result.rows[0]!;+}++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 assertMutationError(statusCode: number) {+ return (error: unknown): true => {+ assert.ok(error instanceof EnvelopeMutationError, String(error));+ assert.equal(error.statusCode, statusCode);++ return true;+ };+}++function fieldShape(+ placed: {+ groupId?: string;+ height: number;+ label?: string;+ options?: string[];+ page: number;+ required: boolean;+ signerId: string;+ type: string;+ width: number;+ x: number;+ y: number;+ },+ signerOrderById: Map<string, number>,+) {+ return {+ assignment: signerOrderById.get(placed.signerId),+ groupId: placed.groupId ?? null,+ height: placed.height,+ label: placed.label ?? null,+ options: placed.options ?? null,+ page: placed.page,+ required: placed.required,+ type: placed.type,+ width: placed.width,+ x: placed.x,+ y: placed.y,+ };+}++test("a completed envelope is copied into a new draft with people, fields and a separate document", async () => {+ const userId = await createUser();+ const { envelopeId: originalId, groupId } = await createPreparedDraft(userId);++ await markNotDraft(originalId, "completed");+ await saveEnvelopeThumbnailForUser(userId, originalId, THUMBNAIL, {+ database,+ storageService,+ });++ const originalBefore = await dumpEnvelope(originalId);+ const originalDocument = await getDraftEnvelopeDocumentForUser(+ userId,+ originalId,+ { database, storageService },+ );+ const originalPrepared = await getPrepareEnvelopeDataForUser(+ userId,+ originalId,+ { database },+ );+ const originalCopyRecipients = await listCopyRecipientsForEnvelopeId(+ originalId,+ database,+ );+ const originalKey = (await envelopeColumns(originalId)).source_pdf_key;+ const originalThumbnailKey = buildEnvelopeThumbnailKey({+ envelopeId: originalId,+ sourcePdfKey: originalKey,+ userId,+ });++ assert.equal(await fileExists(originalThumbnailKey), true);++ const copied = await copyEnvelopeToDraft(userId, originalId, {+ actorEmail: "[email protected]",+ database,+ storageService,+ });++ assert.notEqual(copied.id, originalId);+ assert.deepEqual(await dumpEnvelope(originalId), originalBefore);++ const originalAfter = await envelopeColumns(originalId);+ const draft = await envelopeColumns(copied.id);++ assert.equal(originalAfter.status, "completed");+ assert.equal(draft.status, "draft");+ assert.equal(draft.title, originalAfter.title);+ assert.equal(draft.title, "Lease for 12 Harbour Road");+ assert.notEqual(draft.source_pdf_key, originalAfter.source_pdf_key);+ assert.equal(draft.source_pdf_hash, originalAfter.source_pdf_hash);+ assert.equal(draft.expires_at, null);+ assert.equal(draft.reminder_interval_days, null);+ assert.equal(draft.part11, false);+ assert.equal(originalAfter.expires_at !== null, true);+ assert.equal(originalAfter.reminder_interval_days, 3);+ assert.equal(originalAfter.part11, true);++ const copiedDocument = await getDraftEnvelopeDocumentForUser(+ userId,+ copied.id,+ { database, storageService },+ );++ assert.equal(sha256(copiedDocument.body), sha256(originalDocument.body));+ assert.equal(copiedDocument.body.length, sourcePdf.length);+ assert.equal(+ draft.source_pdf_key,+ buildEnvelopeOriginalPdfKey({ envelopeId: copied.id, userId }),+ );++ const copiedThumbnailKey = buildEnvelopeThumbnailKey({+ envelopeId: copied.id,+ sourcePdfKey: draft.source_pdf_key,+ userId,+ });++ assert.equal(await fileExists(copiedThumbnailKey), false);++ const prepared = await getPrepareEnvelopeDataForUser(userId, copied.id, {+ database,+ });+ const step = await getDraftSignerStepDataForUser(userId, copied.id, database);+ const detail = await getEnvelopeDetailDataForUser(+ userId,+ copied.id,+ database,+ );+ const checks = await signerChecks(copied.id);+ const copyRecipients = await listCopyRecipientsForEnvelopeId(+ copied.id,+ database,+ );++ assert.ok(prepared);+ assert.ok(step);+ assert.ok(detail);+ assert.equal(prepared.status, "draft");+ assert.deepEqual(+ prepared.signers.map((signer) => [signer.order, signer.name, signer.email]),+ [+ [1, "Riley Recipient", "[email protected]"],+ [2, "Casey Second", "[email protected]"],+ ],+ );+ assert.equal(+ originalPrepared!.signers.filter((signer) =>+ prepared.signers.some((copiedSigner) => copiedSigner.id === signer.id),+ ).length,+ 0,+ );+ assert.deepEqual(+ checks.map((row) => [+ row.email,+ row.status,+ row.access_code_hash,+ row.require_email_code,+ row.signature_meaning,+ row.signing_token_hash,+ ]),+ [+ ["[email protected]", "pending", null, true, null, null],+ ["[email protected]", "pending", null, false, null, null],+ ],+ );+ assert.deepEqual(+ step.signers.map((signer) => [+ signer.hasAccessCode,+ signer.requireEmailCode,+ ]),+ [+ [false, true],+ [false, false],+ ],+ );+ assert.deepEqual(+ copyRecipients.map((recipient) => [recipient.name, recipient.email]),+ originalCopyRecipients.map((recipient) => [+ recipient.name,+ recipient.email,+ ]),+ );+ assert.notEqual(copyRecipients[0]?.id, originalCopyRecipients[0]?.id);++ const originalOrder = new Map(+ originalPrepared!.signers.map((signer) => [signer.id, signer.order]),+ );+ const copiedOrder = new Map(+ prepared.signers.map((signer) => [signer.id, signer.order]),+ );++ assert.deepEqual(+ prepared.fields.map((placed) => fieldShape(placed, copiedOrder)),+ originalPrepared!.fields.map((placed) => fieldShape(placed, originalOrder)),+ );+ assert.ok(+ prepared.fields.every(+ (placed) =>+ (placed.value ?? null) === null &&+ (placed.checked ?? null) === null &&+ (placed.imageKey ?? null) === null &&+ (placed.inputMethod ?? null) === null &&+ (placed.submittedAt ?? null) === null,+ ),+ );+ assert.ok(+ originalPrepared!.fields.some(+ (placed) => placed.value === "filled" || placed.checked === true,+ ),+ );++ const radios = prepared.fields.filter((placed) => placed.type === "radio");++ assert.equal(radios[0]!.groupId, groupId);+ assert.equal(radios[1]!.groupId, groupId);+ assert.deepEqual(+ prepared.pages.map((page) => [+ page.pageNumber,+ page.widthPt,+ page.heightPt,+ ]),+ originalPrepared!.pages.map((page) => [+ page.pageNumber,+ page.widthPt,+ page.heightPt,+ ]),+ );+ assert.notDeepEqual(+ prepared.pages.map((page) => page.id),+ originalPrepared!.pages.map((page) => page.id),+ );++ assert.deepEqual(+ detail.timeline.map((event) => event.description),+ ["Copied from an earlier envelope"],+ );+ assert.deepEqual(await verifyAuditChain(copied.id, database), {+ chainedEvents: 1,+ ok: true,+ });+ assert.deepEqual(await verifyAuditChain(originalId, database), {+ chainedEvents: 1,+ ok: true,+ });+ assert.deepEqual(+ (await listAuditEventsForEnvelope(copied.id, database)).map(+ (event) => event.event,+ ),+ ["copied"],+ );+ assert.deepEqual(+ (await listAuditEventsForEnvelope(originalId, database)).map(+ (event) => event.event,+ ),+ ["created"],+ );++ await deleteDraftEnvelope(userId, copied.id, { database, storageService });++ assert.equal(await fileExists(originalKey), true);+ assert.equal(await fileExists(draft.source_pdf_key), false);++ const second = await copyEnvelopeToDraft(userId, originalId, {+ database,+ storageService,+ });+ const secondKey = (await envelopeColumns(second.id)).source_pdf_key;++ await deleteEnvelopesAndFiles([originalId], database, storageService);++ assert.equal(await fileExists(originalKey), false);+ assert.equal(await fileExists(secondKey), true);+ assert.equal(+ sha256(+ (+ await getDraftEnvelopeDocumentForUser(userId, second.id, {+ database,+ storageService,+ })+ ).body,+ ),+ sha256(originalDocument.body),+ );+});++test("a declined or voided envelope can be copied, and so can one still out or past its deadline", async () => {+ const userId = await createUser();+ const now = Math.floor(Date.now() / 1000);+ const cases: Array<{+ extra?: Parameters<typeof markNotDraft>[2];+ status: "declined" | "sent" | "voided";+ }> = [+ { status: "declined" },+ { status: "voided" },+ { status: "sent" },+ { extra: { expiresAt: now - 60 }, status: "sent" },+ ];++ for (const { extra, status } of cases) {+ const { envelopeId } = await createPreparedDraft(userId);++ await markNotDraft(envelopeId, status, extra);++ const copied = await copyEnvelopeToDraft(userId, envelopeId, {+ database,+ storageService,+ });+ const draft = await envelopeColumns(copied.id);+ const prepared = await getPrepareEnvelopeDataForUser(userId, copied.id, {+ database,+ });++ assert.equal(draft.status, "draft", status);+ assert.equal(draft.title, "Lease for 12 Harbour Road", status);+ assert.equal(prepared?.signers.length, 2, status);+ assert.equal(prepared?.fields.length, 6, status);+ assert.ok(+ prepared?.fields.every((placed) => (placed.value ?? null) === null),+ status,+ );+ }+});++test("a draft cannot be copied", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);+ const before = await countEnvelopes(userId);++ await assert.rejects(+ copyEnvelopeToDraft(userId, envelopeId, { database, storageService }),+ assertMutationError(409),+ );+ assert.equal(await countEnvelopes(userId), before);+});++test("someone else's envelope cannot be copied", async () => {+ const owner = await createUser();+ const stranger = await createUser();+ const { envelopeId } = await createPreparedDraft(owner);++ await markNotDraft(envelopeId, "completed");++ await assert.rejects(+ copyEnvelopeToDraft(stranger, envelopeId, { database, storageService }),+ assertMutationError(404),+ );+ assert.equal(await countEnvelopes(stranger), 0);+ assert.equal((await envelopeColumns(envelopeId)).status, "completed");+});++test("a missing document is refused and leaves no draft", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);++ await markNotDraft(envelopeId, "completed");++ const key = (await envelopeColumns(envelopeId)).source_pdf_key;++ await storageService.deleteObject(key);++ const before = await dumpEnvelope(envelopeId);+ const envelopeCount = await countEnvelopes(userId);++ await assert.rejects(+ copyEnvelopeToDraft(userId, envelopeId, { database, storageService }),+ (error: unknown) => {+ assert.ok(error instanceof EnvelopeMutationError, String(error));+ assert.equal(error.statusCode, 409);+ assert.match(error.message, /no longer available/);++ return true;+ },+ );+ assert.equal(await countEnvelopes(userId), envelopeCount);+ assert.deepEqual(await dumpEnvelope(envelopeId), before);+});++test("what is copied is checked", async () => {+ const userId = await createUser();++ await assert.rejects(+ copyEnvelopeToDraft(userId, " ", { database, storageService }),+ ZodError,+ );+});diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 6295201..d6b9ce9 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -19,13 +19,16 @@ import {describeChoiceFieldProblem,findChoiceFieldProblem,} from "./field-choices.ts";+import { idSchema } from "./schemas/common.ts";import {changeDeadlineResponseSchema,changeRemindersResponseSchema,+ copyEnvelopeResponseSchema,envelopeListFiltersSchema,type AuditEventRecord,type ChangeDeadlineResponse,type ChangeRemindersResponse,+ type CopyEnvelopeResponse,envelopeCreateResponseSchema,envelopePageSchema,envelopeRecordSchema,@@ -442,6 +445,7 @@ export type ReplaceDraftSignersResult = ReplaceSignersResponse;export type ReplaceDraftFieldsResult = ReplaceFieldsResponse;export type SendDraftEnvelopeResult = SendEnvelopeResponse;export type VoidEnvelopeResult = VoidEnvelopeResponse;+export type CopyEnvelopeToDraftResult = CopyEnvelopeResponse;const FIELD_TYPE_SUMMARY_LABELS: Record<FieldRecord["type"],@@ -474,6 +478,7 @@ const TIMELINE_TONE_MAP: Record<> = {completed: "success",consented: "neutral",+ copied: "accent",created: "accent",deadline_changed: "neutral",declined: "danger",@@ -658,6 +663,328 @@ export async function createDraftEnvelope(}}+type CopyEnvelopeToDraftOptions = {+ actorEmail?: string | null;+ database?: DbPool;+ storageService?: StorageService;+};++/**+ * Starts a new draft from an envelope that has already gone out: the+ * unsigned document, the people who were asked to sign, anyone who was+ * to receive a copy, and where the fields are. Nothing that was filled+ * in comes along. Access codes are hashed, so they cannot be copied.+ * The original envelope is left as it is, and nobody is emailed.+ */+export async function copyEnvelopeToDraft(+ userId: string,+ envelopeId: string,+ {+ actorEmail = null,+ database = getDb(),+ storageService = createStorageService(),+ }: CopyEnvelopeToDraftOptions = {},+): Promise<CopyEnvelopeToDraftResult> {+ const sourceEnvelopeId = idSchema.parse(envelopeId);+ const envelope = await getEnvelopeByIdForUser(+ userId,+ sourceEnvelopeId,+ database,+ );++ if (!envelope) {+ throw new EnvelopeMutationError("Envelope not found.", 404);+ }++ if (envelope.status === "draft") {+ throw new EnvelopeMutationError("Draft envelopes cannot be copied.", 409);+ }++ let sourcePdf: Uint8Array;++ try {+ sourcePdf = (await storageService.getObject(envelope.sourcePdfKey)).body;+ } catch (error) {+ if (error instanceof StorageObjectNotFoundError) {+ throw new EnvelopeMutationError(+ "This envelope's document is no longer available, so it cannot be copied.",+ 409,+ );+ }++ throw error;+ }++ const newEnvelopeId = randomUUID();+ const now = Math.floor(Date.now() / 1000);+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({+ envelopeId: newEnvelopeId,+ userId,+ });++ await storageService.putObject({+ body: sourcePdf,+ contentType: "application/pdf",+ key: sourcePdfKey,+ });++ try {+ await withTransaction(async (tx) => {+ const source = await getEnvelopeByIdForUser(userId, sourceEnvelopeId, tx);++ if (!source) {+ throw new EnvelopeMutationError("Envelope not found.", 404);+ }++ if (source.status === "draft") {+ throw new EnvelopeMutationError(+ "Draft envelopes cannot be copied.",+ 409,+ );+ }++ const pages = await listEnvelopePagesForEnvelopeId(sourceEnvelopeId, tx);+ const signers = await listSignersForEnvelopeId(sourceEnvelopeId, tx);+ const copyRecipients = await listCopyRecipientsForEnvelopeId(+ sourceEnvelopeId,+ tx,+ );+ const fieldsByEnvelope = await listFieldsForEnvelopeIds(+ [sourceEnvelopeId],+ tx,+ );+ const checks = await listSignerCheckSettings(sourceEnvelopeId, tx);+ const fields = fieldsByEnvelope.get(sourceEnvelopeId) ?? [];+ const signerIdBySourceId = new Map(+ signers.map((signer) => [signer.id, randomUUID()] as const),+ );++ for (const field of fields) {+ if (!signerIdBySourceId.has(field.signerId)) {+ throw new EnvelopeMutationError(+ "This envelope cannot be copied.",+ 409,+ );+ }+ }++ const copied = envelopeRecordSchema.parse({+ completedAt: null,+ createdAt: now,+ declinedAt: null,+ evidenceKey: null,+ id: newEnvelopeId,+ pageCount: source.pageCount,+ sentAt: null,+ signedPdfKey: null,+ sourcePdfFilename: source.sourcePdfFilename,+ sourcePdfHash: source.sourcePdfHash,+ sourcePdfKey,+ sourcePdfSizeBytes: sourcePdf.length,+ status: "draft",+ title: source.title,+ updatedAt: now,+ userId,+ voidedAt: null,+ });++ await tx.query(+ `+ INSERT INTO envelopes (+ id,+ user_id,+ title,+ status,+ source_pdf_key,+ source_pdf_filename,+ source_pdf_size_bytes,+ page_count,+ signed_pdf_key,+ evidence_key,+ source_pdf_hash,+ sent_at,+ completed_at,+ declined_at,+ voided_at,+ created_at,+ updated_at+ ) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17+ )+ `,+ [+ copied.id,+ copied.userId,+ copied.title,+ copied.status,+ copied.sourcePdfKey,+ copied.sourcePdfFilename,+ copied.sourcePdfSizeBytes,+ copied.pageCount,+ copied.signedPdfKey,+ copied.evidenceKey,+ copied.sourcePdfHash,+ copied.sentAt,+ copied.completedAt,+ copied.declinedAt,+ copied.voidedAt,+ copied.createdAt,+ copied.updatedAt,+ ],+ );++ for (const page of pages) {+ await tx.query(+ `+ INSERT INTO envelope_pages (+ id,+ envelope_id,+ page_number,+ width_pt,+ height_pt+ ) VALUES ($1, $2, $3, $4, $5)+ `,+ [+ randomUUID(),+ newEnvelopeId,+ page.pageNumber,+ page.widthPt,+ page.heightPt,+ ],+ );+ }++ for (const signer of signers) {+ await tx.query(+ `+ INSERT INTO signers (+ id,+ envelope_id,+ name,+ email,+ sign_order,+ status,+ signing_token_hash,+ signing_token_expires_at,+ turn_started_at,+ last_notified_at,+ last_nudged_at,+ signed_at,+ declined_at,+ decline_reason,+ created_at,+ updated_at,+ access_code_hash,+ require_email_code,+ signature_meaning+ ) VALUES (+ $1, $2, $3, $4, $5, 'pending', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $6, $7, $8, $9, $10+ )+ `,+ [+ signerIdBySourceId.get(signer.id),+ newEnvelopeId,+ signer.name,+ signer.email,+ signer.signOrder,+ now,+ now,+ null,+ checks.get(signer.id)?.requireEmailCode ?? false,+ null,+ ],+ );+ }++ for (const [index, recipient] of copyRecipients.entries()) {+ await tx.query(+ `+ INSERT INTO signers (+ id, envelope_id, name, email, sign_order, status, role,+ created_at, updated_at+ ) VALUES ($1, $2, $3, $4, $5, 'pending', 'cc', $6, $6)+ `,+ [+ randomUUID(),+ newEnvelopeId,+ recipient.name,+ recipient.email,+ COPY_RECIPIENT_SIGN_ORDER_BASE + index + 1,+ now,+ ],+ );+ }++ for (const [index, field] of fields.entries()) {+ await tx.query(+ `+ INSERT INTO fields (+ id,+ envelope_id,+ signer_id,+ type,+ page,+ x,+ y,+ width,+ height,+ required,+ label,+ input_method,+ value,+ image_key,+ checked,+ submitted_at,+ created_at,+ updated_at,+ options,+ group_id+ ) VALUES (+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NULL, NULL, NULL, NULL, NULL, $12, $13, $14::jsonb, $15+ )+ `,+ [+ randomUUID(),+ newEnvelopeId,+ signerIdBySourceId.get(field.signerId),+ field.type,+ field.page,+ field.x,+ field.y,+ field.width,+ field.height,+ field.required,+ field.label ?? null,+ now + index,+ now,+ field.type === "dropdown" && field.options !== undefined+ ? JSON.stringify(field.options)+ : null,+ field.groupId ?? null,+ ],+ );+ }++ await recordAuditEvent(+ {+ actorEmail,+ actorType: "sender",+ createdAt: now,+ envelopeId: newEnvelopeId,+ event: "copied",+ metadata: { sourceEnvelopeId },+ },+ tx,+ );+ }, database);+ } catch (error) {+ await storageService.deleteObject(sourcePdfKey).catch(() => undefined);+ throw error;+ }++ return copyEnvelopeResponseSchema.parse({ id: newEnvelopeId });+}+export function buildCreateEnvelopeResponse(result: DraftEnvelopeResult,): CreateEnvelopeResponse {@@ -1268,6 +1595,8 @@ function buildTimelineDescription(event: AuditEventRecord): string {const targetLabel = signerName ?? event.actorEmail ?? signerEmail ?? "signer";switch (event.event) {+ case "copied":+ return "Copied from an earlier envelope";case "created":return "Envelope created";case "sent":diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.tsindex ec766ef..54ee67d 100644--- a/src/lib/schemas/envelope.ts+++ b/src/lib/schemas/envelope.ts@@ -87,6 +87,10 @@ export const voidEnvelopeResponseSchema = z.object({voidedAt: unixTimestampSchema,});+export const copyEnvelopeResponseSchema = z.object({+ id: idSchema,+});+export const manualNudgeResponseSchema = z.object({envelopeId: idSchema,nextAvailableAt: unixTimestampSchema,@@ -182,6 +186,7 @@ export type ChangeRemindersResponse = z.infer<typeof changeRemindersResponseSchema>;export type VoidEnvelopeResponse = z.infer<typeof voidEnvelopeResponseSchema>;+export type CopyEnvelopeResponse = z.infer<typeof copyEnvelopeResponseSchema>;export type ManualNudgeResponse = z.infer<typeof manualNudgeResponseSchema>;export type EnvelopeListFilters = z.infer<typeof envelopeListFiltersSchema>;export type DownloadRequest = z.infer<typeof downloadRequestSchema>;diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.tsindex b801d81..11ad57c 100644--- a/src/lib/types/domain.ts+++ b/src/lib/types/domain.ts@@ -64,6 +64,7 @@ export const auditEventTypes = ["expired","reminded_auto","reauthentication_failed",+ "copied",] as const;/**