Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(embedded): prevent and hide automatic reminder schedules for embedded envelopes (#246)
Kevin Rosee08ee3b2c384
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex 855cd75..ee8cbda 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -29,7 +29,11 @@ import type {EnvelopeDetailData,EnvelopeDetailTimelineItem,} from "@/lib/envelopes";-import { describeCopyRecipientDelivery } from "@/lib/envelope-detail-copy";+import {+ canEditAutomaticReminders,+ describeAutomaticReminders,+ describeCopyRecipientDelivery,+} from "@/lib/envelope-detail-copy";import { formatReminderInterval } from "@/lib/services/reminders";import {DEFAULT_ENVELOPE_DEADLINE_DAYS,@@ -251,11 +255,18 @@ export function EnvelopeDetailShell({: deadline.expiresAtLabel? `Expires ${deadline.expiresAtLabel}.`: "No deadline. Each signing link lasts seven days.";- const reminderIntervalDays = record.reminderIntervalDays ?? null;- const remindersText =- reminderIntervalDays === null- ? "Automatic reminders are off."- : `Automatic reminders: ${formatReminderInterval(reminderIntervalDays).toLowerCase()}.`;+ const isEmbedded = record.delivery === "embedded";+ const reminderIntervalDays = isEmbedded+ ? null+ : (record.reminderIntervalDays ?? null);+ const canChangeReminders = canEditAutomaticReminders({+ delivery: record.delivery,+ isOwnEnvelope,+ });+ const remindersText = describeAutomaticReminders({+ delivery: record.delivery,+ reminderIntervalDays,+ });// The document as it was sent, before anyone signed: while it is out for// signature, and once it was declined or voided. A completed envelope// has its signed PDF instead.@@ -823,7 +834,7 @@ export function EnvelopeDetailShell({<p className="text-sm leading-6 text-(--secondary)">{remindersText}</p>- {isOwnEnvelope ? (+ {canChangeReminders ? (<buttonclassName="btn-quiet shrink-0"onClick={() => {@@ -1053,7 +1064,7 @@ export function EnvelopeDetailShell({/>) : null}- {activeModal === "change-reminders" ? (+ {activeModal === "change-reminders" && canChangeReminders ? (<RemindersDialogerrorMessage={actionError}initialIntervalDays={reminderIntervalDays}diff --git a/src/lib/automatic-reminders.dbtest.ts b/src/lib/automatic-reminders.dbtest.tsindex c1a4455..94dc7db 100644--- a/src/lib/automatic-reminders.dbtest.ts+++ b/src/lib/automatic-reminders.dbtest.ts@@ -52,10 +52,12 @@ after(async () => {/** An envelope sent at SENT_AT and waiting on its one signer. */async function createSentEnvelope({+ delivery = "email",expiresAt = SENT_AT + 30 * DAY,reminderIntervalDays,signerStatus = "notified",}: {+ delivery?: "email" | "embedded";expiresAt?: number | null;reminderIntervalDays: number | null;signerStatus?: "notified" | "signed";@@ -76,14 +78,15 @@ async function createSentEnvelope({await database.query(`insert into envelopes (- id, user_id, title, status, source_pdf_key, source_pdf_filename,+ id, user_id, title, status, delivery, source_pdf_key, source_pdf_filename,source_pdf_size_bytes, page_count, source_pdf_hash, sent_at,expires_at, reminder_interval_days- ) values ($1, $2, 'Lease', 'sent', $3, 'lease.pdf', 10, 1, $4, $5, $6, $7)+ ) values ($1, $2, 'Lease', 'sent', $3, $4, 'lease.pdf', 10, 1, $5, $6, $7, $8)`,[envelopeId,userId,+ delivery,`test/${envelopeId}.pdf`,"a".repeat(64),SENT_AT,@@ -381,3 +384,32 @@ test("only the owner changes reminders, and only while the envelope is out", asyerror instanceof EnvelopeMutationError && error.statusCode === 409,);});++test("embedded envelopes refuse reminder schedule changes and are skipped by the daily job (issue #246)", async () => {+ const embedded = await createSentEnvelope({+ delivery: "embedded",+ reminderIntervalDays: null,+ });++ await assert.rejects(+ changeEnvelopeReminders(embedded.userId, embedded.envelopeId, 1, {+ database,+ }),+ (error: unknown) =>+ error instanceof EnvelopeMutationError && error.statusCode === 409,+ );++ // Even a pre-existing row with an interval saved is skipped by the daily job.+ await database.query(+ `update envelopes set reminder_interval_days = 1 where id = $1`,+ [embedded.envelopeId],+ );++ const { sent, service } = recordingEmailService();++ await run(SENT_AT + 2 * DAY, service);+ assert.equal(+ sent.some((message) => message.to.startsWith(embedded.signerId)),+ false,+ );+});diff --git a/src/lib/embedded-reminders.test.ts b/src/lib/embedded-reminders.test.tsnew file mode 100644index 0000000..6f33687--- /dev/null+++ b/src/lib/embedded-reminders.test.ts@@ -0,0 +1,538 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { registerHooks } from "node:module";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";++import { PDFDocument } from "pdf-lib";+import type { Pool, PoolClient, QueryResult } from "pg";++import {+ changeEnvelopeReminders,+ EnvelopeMutationError,+ getEnvelopeDetailDataForUser,+ sendDraftEnvelope,+} from "./envelopes.ts";+import { sendAutomaticEnvelopeReminder } from "./reminders.ts";+import type { EmailService } from "./services/email.ts";+import { createStorageService } from "./services/storage.ts";+import { setWebhookDrainScheduler } from "./webhooks/outbox.ts";++// Resolve next/server when running plain node --test, matching route.dbtest.ts.+registerHooks({+ resolve(specifier, context, nextResolve) {+ if (/^next\/[a-z-]+$/.test(specifier)) {+ return nextResolve(`${specifier}.js`, context);+ }++ return nextResolve(specifier, context);+ },+});++const ENV_KEYS = [+ "APP_URL",+ "EMAIL_CAPTURE_DIR",+ "EMAIL_DRIVER",+ "STORAGE_DRIVER",+ "STORAGE_LOCAL_DIR",+] as const;++let workDir: string;+let sourcePdfBytes: Uint8Array;+const previousEnv = new Map<string, string | undefined>();++before(async () => {+ workDir = await mkdtemp(path.join(tmpdir(), "signudoc-embedded-reminders-"));++ for (const key of ENV_KEYS) {+ previousEnv.set(key, process.env[key]);+ }++ process.env.APP_URL = "https://sign.example.test";+ process.env.EMAIL_CAPTURE_DIR = path.join(workDir, "outbox");+ process.env.EMAIL_DRIVER = "capture";+ process.env.STORAGE_DRIVER = "local";+ process.env.STORAGE_LOCAL_DIR = path.join(workDir, "storage");+ setWebhookDrainScheduler(() => undefined);++ const doc = await PDFDocument.create();++ doc.addPage([612, 792]);+ sourcePdfBytes = await doc.save();+});++after(async () => {+ setWebhookDrainScheduler(null);++ for (const [key, value] of previousEnv) {+ if (value === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = value;+ }+ }++ await rm(workDir, { force: true, recursive: true });+});++type StoredEnvelope = {+ completedAt: number | null;+ createdAt: number;+ declinedAt: number | null;+ delivery: "email" | "embedded";+ evidenceKey: string | null;+ expiresAt: number | null;+ id: string;+ pageCount: number;+ part11: boolean;+ reminderIntervalDays: number | null;+ sentAt: number | null;+ signatureLevel: "advanced" | "qualified" | "simple";+ signatureProvider: string | null;+ signedPdfKey: string | null;+ sourcePdfFilename: string;+ sourcePdfHash: string;+ sourcePdfKey: string;+ sourcePdfSizeBytes: number;+ status: "draft" | "sent" | "completed" | "declined" | "voided";+ title: string;+ updatedAt: number;+ userId: string;+ voidedAt: number | null;+};++function queryResult<T>(rows: T[], rowCount = rows.length): QueryResult {+ return {+ command: "",+ fields: [],+ oid: 0,+ rowCount,+ rows,+ } as unknown as QueryResult;+}++async function createFakeDb(initial: {+ delivery: "email" | "embedded";+ reminderIntervalDays: number | null;+ status: "draft" | "sent";+}) {+ const now = 1_800_000_000;+ const userId = randomUUID();+ const envelopeId = randomUUID();+ const signerId = randomUUID();+ const sourcePdfKey = `envelopes/${userId}/${envelopeId}/source.pdf`;++ if (initial.status === "draft") {+ await createStorageService().putObject({+ body: sourcePdfBytes,+ contentType: "application/pdf",+ key: sourcePdfKey,+ });+ }++ const envelope: StoredEnvelope = {+ completedAt: null,+ createdAt: now,+ declinedAt: null,+ delivery: initial.delivery,+ evidenceKey: null,+ expiresAt: initial.status === "sent" ? now + 86_400 * 30 : null,+ id: envelopeId,+ pageCount: 1,+ part11: false,+ reminderIntervalDays: initial.reminderIntervalDays,+ sentAt: initial.status === "sent" ? now : null,+ signatureLevel: "simple",+ signatureProvider: null,+ signedPdfKey: null,+ sourcePdfFilename: "agreement.pdf",+ sourcePdfHash: "a".repeat(64),+ sourcePdfKey,+ sourcePdfSizeBytes: sourcePdfBytes.byteLength,+ status: initial.status,+ title: "Service agreement",+ updatedAt: now,+ userId,+ voidedAt: null,+ };+ const signer = {+ createdAt: now,+ declineReason: null,+ declinedAt: null,+ email: "[email protected]",+ envelopeId,+ id: signerId,+ lastNotifiedAt: initial.status === "sent" ? now : null,+ lastNudgedAt: null,+ name: "Casey Client",+ role: "signer" as const,+ signatureMeaning: null,+ signedAt: null,+ signOrder: 1,+ signingStep: 1,+ signingTokenExpiresAt: initial.status === "sent" ? now + 86_400 * 30 : null,+ signingTokenHash: initial.status === "sent" ? "b".repeat(64) : null,+ status:+ initial.status === "sent" ? ("notified" as const) : ("pending" as const),+ turnStartedAt: initial.status === "sent" ? now : null,+ updatedAt: now,+ };+ const field = {+ checked: null,+ createdAt: now,+ envelopeId,+ groupId: null,+ height: 0.05,+ id: randomUUID(),+ imageKey: null,+ inputMethod: null,+ label: null,+ options: null,+ page: 1,+ required: true,+ signerId,+ submittedAt: null,+ type: "signature" as const,+ updatedAt: now,+ value: null,+ width: 0.3,+ x: 0.1,+ y: 0.7,+ };+ const auditEvents: Array<{ event: string; metadata: unknown }> = [];++ async function execute(+ text: string,+ values: unknown[] = [],+ ): Promise<QueryResult> {+ const sql = text.replace(/\s+/g, " ").trim();++ if (sql === "BEGIN" || sql === "COMMIT" || sql === "ROLLBACK") {+ return queryResult([], 0);+ }++ if (sql.startsWith("SELECT pg_advisory_xact_lock")) {+ return queryResult([{ pg_advisory_xact_lock: "" }], 1);+ }++ if (sql.toLowerCase().includes("app_settings")) {+ return queryResult([+ {+ allowed_email_domains: [],+ brand_color: null,+ consent_disclosure: null,+ email_ready_at: null,+ logo_hash: null,+ organization_name: "Acme Test",+ part11_mode: false,+ privacy_url: null,+ require_two_factor: false,+ retention_days: null,+ sender_address: null,+ session_idle_minutes: null,+ session_max_hours: null,+ setup_completed_at: 1_700_000_000,+ signup_mode: "open",+ support_address: null,+ terms_url: null,+ },+ ]);+ }++ if (sql.includes("FROM embed_allowed_origins")) {+ return queryResult([{ any: true }]);+ }++ if (sql.startsWith("SELECT delivery FROM envelopes")) {+ if (+ values[0] === envelope.id &&+ (values[1] === null || values[1] === envelope.userId)+ ) {+ return queryResult([{ delivery: envelope.delivery }]);+ }++ return queryResult([]);+ }++ if (sql.includes("FROM envelopes WHERE id = $1 AND user_id = $2")) {+ if (values[0] === envelope.id && values[1] === envelope.userId) {+ return queryResult([{ ...envelope }]);+ }++ return queryResult([]);+ }++ if (sql.includes("FROM signers") && sql.includes("role = 'cc'")) {+ return queryResult([]);+ }++ if (+ sql.includes("access_code_hash IS NOT NULL") &&+ sql.includes("FROM signers")+ ) {+ return queryResult([+ {+ hasAccessCode: false,+ id: signer.id,+ requireEmailCode: false,+ signatureMeaning: null,+ },+ ]);+ }++ if (sql.includes("FROM signers WHERE envelope_id IN")) {+ return queryResult(values.includes(envelopeId) ? [{ ...signer }] : []);+ }++ if (sql.includes("FROM fields WHERE envelope_id IN")) {+ return queryResult(values.includes(envelopeId) ? [{ ...field }] : []);+ }++ if (sql.includes("FROM envelope_pages WHERE envelope_id = $1")) {+ return queryResult([+ {+ envelopeId,+ heightPt: 792,+ id: "page-1",+ pageNumber: 1,+ widthPt: 612,+ },+ ]);+ }++ if (sql.includes("FROM audit_events")) {+ return queryResult([]);+ }++ if (sql.startsWith("INSERT INTO audit_events")) {+ auditEvents.push({+ event: String(values[2]),+ metadata: values[7],+ });+ return queryResult([], 1);+ }++ if (sql.startsWith("UPDATE envelopes SET status = 'sent'")) {+ if (+ values[2] === envelope.id &&+ values[3] === envelope.userId &&+ envelope.status === "draft"+ ) {+ envelope.status = "sent";+ envelope.sentAt = Number(values[0]);+ envelope.updatedAt = Number(values[1]);+ envelope.expiresAt = Number(values[4]);+ envelope.reminderIntervalDays = (values[5] as number | null) ?? null;+ return queryResult([], 1);+ }++ return queryResult([], 0);+ }++ if (sql.startsWith("UPDATE envelopes SET delivery = 'embedded'")) {+ envelope.delivery = "embedded";+ return queryResult([], 1);+ }++ if (sql.startsWith("UPDATE envelopes SET reminder_interval_days = $1")) {+ if (+ values[2] === envelope.id &&+ values[3] === envelope.userId &&+ envelope.status === "sent" &&+ envelope.delivery === "email"+ ) {+ envelope.reminderIntervalDays = (values[0] as number | null) ?? null;+ envelope.updatedAt = Number(values[1]);+ return queryResult([], 1);+ }++ return queryResult([], 0);+ }++ if (sql.startsWith("UPDATE signers SET status = 'pending'")) {+ return queryResult([], 1);+ }++ if (sql.startsWith("UPDATE signers SET status = 'notified'")) {+ signer.status = "notified";+ signer.lastNotifiedAt = Number(values[3]);+ return queryResult([], 1);+ }++ if (+ sql.startsWith("INSERT INTO webhook_deliveries") ||+ sql.startsWith("UPDATE webhook_deliveries")+ ) {+ return queryResult([], 0);+ }++ throw new Error(`Unexpected SQL in embedded-reminders.test.ts: ${sql}`);+ }++ const client = {+ query: (text: string, values?: unknown[]) => execute(text, values),+ release: () => undefined,+ } as unknown as PoolClient;+ const pool = {+ connect: async () => client,+ query: (text: string, values?: unknown[]) => execute(text, values),+ totalCount: 1,+ } as unknown as Pool;++ return { auditEvents, envelope, envelopeId, pool, userId };+}++const unusedEmail: EmailService = {+ async send() {+ throw new Error("embedded envelopes must not send reminder emails");+ },+ async sendBatch() {+ throw new Error("not used");+ },+};++test("sending an embedded envelope refuses a non-null reminderIntervalDays with HTTP 400 (issue #246)", async () => {+ const db = await createFakeDb({+ delivery: "email",+ reminderIntervalDays: null,+ status: "draft",+ });+ let caught: unknown;++ try {+ await sendDraftEnvelope(+ db.userId,+ db.envelopeId,+ {+ delivery: "embedded",+ reminderIntervalDays: 5,+ senderEmail: "[email protected]",+ senderName: "Alex Sender",+ },+ { database: db.pool },+ );+ } catch (error) {+ caught = error;+ }++ assert.ok(caught instanceof EnvelopeMutationError);+ assert.equal(caught.statusCode, 400);+ assert.match(caught.message, /Embedded envelopes do not send/);+ assert.equal(db.envelope.status, "draft");+ assert.equal(db.envelope.reminderIntervalDays, null);++ const { apiErrorFor } = await import("./api/route.ts");+ const apiResponse = apiErrorFor(caught);++ assert.ok(apiResponse);+ assert.equal(apiResponse.status, 400);+ assert.deepEqual(await apiResponse.json(), {+ error: {+ code: "invalid_request",+ message: caught.message,+ },+ });+});++test("sending an embedded envelope with reminderIntervalDays null or omitted succeeds with null schedule (issue #246)", async () => {+ for (const reminderIntervalDays of [undefined, null] as const) {+ const db = await createFakeDb({+ delivery: "email",+ reminderIntervalDays: null,+ status: "draft",+ });++ const sent = await sendDraftEnvelope(+ db.userId,+ db.envelopeId,+ {+ delivery: "embedded",+ reminderIntervalDays,+ senderEmail: "[email protected]",+ senderName: "Alex Sender",+ },+ { database: db.pool },+ );++ assert.equal(sent.envelopeId, db.envelopeId);+ assert.equal(db.envelope.status, "sent");+ assert.equal(db.envelope.delivery, "embedded");+ assert.equal(db.envelope.reminderIntervalDays, null);+ }+});++test("changeEnvelopeReminders refuses embedded envelopes with 409 while emailed envelopes still save (issue #246)", async () => {+ const embedded = await createFakeDb({+ delivery: "embedded",+ reminderIntervalDays: null,+ status: "sent",+ });++ await assert.rejects(+ changeEnvelopeReminders(embedded.userId, embedded.envelopeId, 1, {+ database: embedded.pool,+ }),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 409 &&+ /does not send automatic reminders/.test(error.message),+ );+ assert.equal(embedded.envelope.reminderIntervalDays, null);++ const emailed = await createFakeDb({+ delivery: "email",+ reminderIntervalDays: 5,+ status: "sent",+ });+ const saved = await changeEnvelopeReminders(+ emailed.userId,+ emailed.envelopeId,+ 1,+ { database: emailed.pool },+ );++ assert.deepEqual(saved, {+ envelopeId: emailed.envelopeId,+ reminderIntervalDays: 1,+ });+ assert.equal(emailed.envelope.reminderIntervalDays, 1);+});++test("envelope detail hides any legacy reminder schedule on embedded envelopes and automatic reminders skip them (issue #246)", async () => {+ const legacyEmbedded = await createFakeDb({+ delivery: "embedded",+ reminderIntervalDays: 5,+ status: "sent",+ });+ const detail = await getEnvelopeDetailDataForUser(+ legacyEmbedded.userId,+ legacyEmbedded.envelopeId,+ legacyEmbedded.pool,+ );++ assert.equal(detail?.delivery, "embedded");+ assert.equal(detail?.reminderIntervalDays, null);++ const sent = await sendAutomaticEnvelopeReminder(legacyEmbedded.envelopeId, {+ database: legacyEmbedded.pool,+ emailService: unusedEmail,+ });++ assert.equal(sent, false);++ const emailed = await createFakeDb({+ delivery: "email",+ reminderIntervalDays: 5,+ status: "sent",+ });+ const emailedDetail = await getEnvelopeDetailDataForUser(+ emailed.userId,+ emailed.envelopeId,+ emailed.pool,+ );++ assert.equal(emailedDetail?.delivery, "email");+ assert.equal(emailedDetail?.reminderIntervalDays, 5);+});diff --git a/src/lib/embedding.dbtest.ts b/src/lib/embedding.dbtest.tsindex b0568b5..6a49791 100644--- a/src/lib/embedding.dbtest.ts+++ b/src/lib/embedding.dbtest.ts@@ -27,6 +27,7 @@ import {} from "./embedding.ts";import {changeEnvelopeDeadline,+ changeEnvelopeReminders,correctSentEnvelopeSigner,EnvelopeMutationError,} from "./envelopes.ts";@@ -141,7 +142,13 @@ async function createAdmin(): Promise<ApiActor> {};}-function request(options: { accessCode?: string; delivery?: string } = {}) {+function request(+ options: {+ accessCode?: string;+ delivery?: string;+ reminderIntervalDays?: number | null;+ } = {},+) {const tag = randomUUID().slice(0, 8);return apiCreateEnvelopeSchema.parse({@@ -168,6 +175,9 @@ function request(options: { accessCode?: string; delivery?: string } = {}) {send: {delivery: options.delivery ?? "embedded",permittedUseConfirmed: true,+ ...(options.reminderIntervalDays !== undefined+ ? { reminderIntervalDays: options.reminderIntervalDays }+ : {}),},signers: [{@@ -276,6 +286,13 @@ test("an embedded send is refused while no site is allowed, or with signer checkerror instanceof EnvelopeMutationError &&/access codes/.test(error.message),);+ await assert.rejects(+ create(admin, { reminderIntervalDays: 5 }),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 400 &&+ /automatic reminders/.test(error.message),+ );});test("an embedded envelope emails no invitation, and the app gets a link for the signer whose turn it is", async () => {@@ -568,6 +585,11 @@ test("an emailed envelope gets no embed links, and an embedded one no reminders(error: unknown) =>error instanceof ReminderMutationError && error.statusCode === 409,);+ await assert.rejects(+ changeEnvelopeReminders(admin.userId, embedded.id, 1, { database }),+ (error: unknown) =>+ error instanceof EnvelopeMutationError && error.statusCode === 409,+ );await assert.rejects(correctSentEnvelopeSigner(admin.userId,diff --git a/src/lib/envelope-detail-copy.test.ts b/src/lib/envelope-detail-copy.test.tsindex f69ca30..bf77baf 100644--- a/src/lib/envelope-detail-copy.test.ts+++ b/src/lib/envelope-detail-copy.test.ts@@ -1,7 +1,11 @@import assert from "node:assert/strict";import { test } from "node:test";-import { describeCopyRecipientDelivery } from "./envelope-detail-copy.ts";+import {+ canEditAutomaticReminders,+ describeAutomaticReminders,+ describeCopyRecipientDelivery,+} from "./envelope-detail-copy.ts";test("copy recipient status copy distinguishes terminal outcomes from pending delivery (issue #238)", () => {assert.equal(@@ -25,3 +29,63 @@ test("copy recipient status copy distinguishes terminal outcomes from pending de"No copy was sent because this envelope was declined.",);});++test("automatic reminder copy and editability reflect embedded vs email delivery (issue #246)", () => {+ assert.equal(+ describeAutomaticReminders({+ delivery: "embedded",+ reminderIntervalDays: null,+ }),+ "SignuDoc does not send automatic reminders for embedded envelopes.",+ );+ // Even if a pre-existing DB row had a saved interval, embedded delivery+ // never shows an active schedule.+ assert.equal(+ describeAutomaticReminders({+ delivery: "embedded",+ reminderIntervalDays: 5,+ }),+ "SignuDoc does not send automatic reminders for embedded envelopes.",+ );+ assert.equal(+ describeAutomaticReminders({+ delivery: "email",+ reminderIntervalDays: null,+ }),+ "Automatic reminders are off.",+ );+ assert.equal(+ describeAutomaticReminders({+ delivery: "email",+ reminderIntervalDays: 1,+ }),+ "Automatic reminders: every day.",+ );+ assert.equal(+ describeAutomaticReminders({+ delivery: "email",+ reminderIntervalDays: 5,+ }),+ "Automatic reminders: every 5 days.",+ );+ assert.equal(+ describeAutomaticReminders({+ reminderIntervalDays: 7,+ }),+ "Automatic reminders: every week.",+ );++ assert.equal(+ canEditAutomaticReminders({ delivery: "embedded", isOwnEnvelope: true }),+ false,+ );+ assert.equal(+ canEditAutomaticReminders({ delivery: "email", isOwnEnvelope: true }),+ true,+ );+ assert.equal(+ canEditAutomaticReminders({ delivery: "email", isOwnEnvelope: false }),+ false,+ );+ assert.equal(canEditAutomaticReminders({ isOwnEnvelope: true }), true);+});diff --git a/src/lib/envelope-detail-copy.ts b/src/lib/envelope-detail-copy.tsindex e4dc865..c4aa017 100644--- a/src/lib/envelope-detail-copy.ts+++ b/src/lib/envelope-detail-copy.ts@@ -1,3 +1,5 @@+import type { EnvelopeDelivery } from "./schemas/envelope.ts";+import { formatReminderInterval } from "./services/reminders.ts";import type { EnvelopeStatus } from "./types/domain.ts";/**@@ -18,3 +20,28 @@ export function describeCopyRecipientDelivery(status: EnvelopeStatus): string {return "Gets the finished document once everyone has signed.";}}++/**+ * Automatic reminder status line on the sender's envelope detail page.+ * Embedded envelopes never receive reminders from SignuDoc.+ */+export function describeAutomaticReminders(input: {+ delivery?: EnvelopeDelivery;+ reminderIntervalDays: number | null;+}): string {+ if (input.delivery === "embedded") {+ return "SignuDoc does not send automatic reminders for embedded envelopes.";+ }++ return input.reminderIntervalDays === null+ ? "Automatic reminders are off."+ : `Automatic reminders: ${formatReminderInterval(input.reminderIntervalDays).toLowerCase()}.`;+}++/** Whether the sender can open and save an automatic reminder schedule. */+export function canEditAutomaticReminders(input: {+ delivery?: EnvelopeDelivery;+ isOwnEnvelope: boolean;+}): boolean {+ return input.isOwnEnvelope && input.delivery !== "embedded";+}diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 8fd26ee..dcf68bc 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -233,6 +233,7 @@ type EnvelopeRow = {completedAt: number | null;createdAt: number;declinedAt: number | null;+ delivery?: "email" | "embedded";evidenceKey: string | null;expiresAt: number | null;id: string;@@ -483,6 +484,8 @@ export type EnvelopeDetailData = {createdAtLabel: string;/** Set while the envelope is out for signature. */deadline: EnvelopeDetailDeadline | null;+ /** "email", or "embedded" when signers sign inside another app. */+ delivery?: "email" | "embedded";/** Days between automatic reminders while it is out. Null when off. */reminderIntervalDays: number | null;envelopeId: string;@@ -1226,6 +1229,7 @@ async function getEnvelopeByIdForUser(user_id AS "userId",title,status,+ delivery,source_pdf_key AS "sourcePdfKey",source_pdf_filename AS "sourcePdfFilename",source_pdf_size_bytes AS "sourcePdfSizeBytes",@@ -2126,6 +2130,7 @@ async function listEnvelopes(user_id AS "userId",title,status,+ delivery,source_pdf_key AS "sourcePdfKey",source_pdf_filename AS "sourcePdfFilename",source_pdf_size_bytes AS "sourcePdfSizeBytes",@@ -2354,9 +2359,10 @@ export async function getEnvelopeDetailDataForUser(: null,}: null,+ delivery: envelope.delivery ?? "email",envelopeId,reminderIntervalDays:- envelope.status === "sent"+ envelope.status === "sent" && envelope.delivery !== "embedded"? (envelope.reminderIntervalDays ?? null): null,manualReminder,@@ -2936,6 +2942,13 @@ export async function sendDraftEnvelope();}+ if (input.reminderIntervalDays != null) {+ throw new EnvelopeMutationError(+ "Embedded envelopes do not send automatic reminders, so leave out reminderIntervalDays or set it to null.",+ 400,+ );+ }+if (!(await hasEmbedOrigins(database))) {throw new EnvelopeMutationError("Embedded signing is off: no site is allowed to show signing pages. An administrator can add one under Settings, Organization, Embedded signing.",@@ -3026,6 +3039,8 @@ export async function sendDraftEnvelope(const sentAt = Math.floor(Date.now() / 1000);const expiresAt = deadlineFromDays(sentAt, input.expiresInDays);+ const reminderIntervalDays =+ delivery === "embedded" ? null : (input.reminderIntervalDays ?? null);const issuedLinks = new Map<string, IssuedSigningLink>();for (const signer of firstSigners) {@@ -3054,14 +3069,7 @@ export async function sendDraftEnvelope(AND user_id = $4AND status = 'draft'`,- [- sentAt,- sentAt,- envelopeId,- userId,- expiresAt,- input.reminderIntervalDays ?? null,- ],+ [sentAt, sentAt, envelopeId, userId, expiresAt, reminderIntervalDays],);if (updatedEnvelope.rowCount !== 1) {@@ -3223,7 +3231,7 @@ export async function sendDraftEnvelope(...(delivery === "embedded" ? { delivery } : {}),// The send route refuses a send without this confirmation.expiresAt,- reminderIntervalDays: input.reminderIntervalDays ?? null,+ reminderIntervalDays,permittedUseConfirmed: true,permittedUseVersion: PERMITTED_USE_VERSION,...(part11 ? { part11: true } : {}),@@ -3944,7 +3952,7 @@ export async function changeEnvelopeReminders(`UPDATE envelopesSET reminder_interval_days = $1, updated_at = $2- WHERE id = $3 AND user_id = $4 AND status = 'sent'+ WHERE id = $3 AND user_id = $4 AND status = 'sent' AND delivery = 'email'`,[reminderIntervalDays, nowUnixTimestamp, envelopeId, userId],);@@ -3952,12 +3960,21 @@ export async function changeEnvelopeReminders(if (updated.rowCount !== 1) {const envelope = await getEnvelopeByIdForUser(userId, envelopeId, database);- throw envelope- ? new EnvelopeMutationError(- "Reminders can only be changed while an envelope is out for signature.",- 409,- )- : new EnvelopeMutationError("Envelope not found.", 404);+ if (!envelope) {+ throw new EnvelopeMutationError("Envelope not found.", 404);+ }++ if (envelope.status === "sent" && envelope.delivery === "embedded") {+ throw new EnvelopeMutationError(+ "This envelope is signed in another app, so SignuDoc does not send automatic reminders for it.",+ 409,+ );+ }++ throw new EnvelopeMutationError(+ "Reminders can only be changed while an envelope is out for signature.",+ 409,+ );}return changeRemindersResponseSchema.parse({diff --git a/src/lib/reminders.ts b/src/lib/reminders.tsindex 7b7f34f..9230773 100644--- a/src/lib/reminders.ts+++ b/src/lib/reminders.ts@@ -309,6 +309,10 @@ function getAutomaticReminderObstacle(signer: ReminderSignerRow,now: number,): string | null {+ if (envelope.delivery === "embedded") {+ return "This envelope is signed in another app, so SignuDoc does not send automatic reminders for it.";+ }+if (envelope.reminderIntervalDays === null) {return "Automatic reminders are off for this envelope.";}diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.tsindex 54ee67d..d3b8552 100644--- a/src/lib/schemas/envelope.ts+++ b/src/lib/schemas/envelope.ts@@ -136,11 +136,17 @@ export const signatureLevelSchema = z.enum(["simple", "advanced", "qualified"]);export type EnvelopeSignatureLevel = z.infer<typeof signatureLevelSchema>;+/** How signers receive signing links. See embedding.ts. */+export const envelopeDeliverySchema = z.enum(["email", "embedded"]);++export type EnvelopeDelivery = z.infer<typeof envelopeDeliverySchema>;+export const envelopeRecordSchema = z.object({id: idSchema,userId: idSchema,title: envelopeTitleSchema,status: envelopeStatusSchema,+ delivery: envelopeDeliverySchema.optional(),sourcePdfKey: z.string().trim().min(1),sourcePdfFilename: z.string().trim().min(1).max(255),sourcePdfSizeBytes: z.number().int().positive(),