Skip to content

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

TypeScript

Send automatic reminders from the daily job

Claude517d98f45a39
diff --git a/db/migrations/20261114100000_automatic_reminders.sql b/db/migrations/20261114100000_automatic_reminders.sql
new file mode 100644
index 0000000..4c7c944
--- /dev/null
+++ b/db/migrations/20261114100000_automatic_reminders.sql
@@ -0,0 +1,43 @@
+-- Automatic reminders, chosen by the sender for each envelope.
+--
+-- * envelopes.reminder_interval_days: how many days the daily job waits
+-- after the last invitation or reminder before it reminds the signer whose
+-- turn it is. Null means no automatic reminders.
+-- * audit_events: a new kind for a reminder the job sent.
+
+alter table public.envelopes
+ add column if not exists reminder_interval_days smallint;
+
+alter table public.envelopes
+ drop constraint if exists envelopes_reminder_interval_days_check;
+
+alter table public.envelopes
+ add constraint envelopes_reminder_interval_days_check
+ check (reminder_interval_days is null or reminder_interval_days between 1 and 30);
+
+create index if not exists idx_envelopes_reminders_on
+ on public.envelopes(id)
+ where status = 'sent' and reminder_interval_days is not null;
+
+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'
+ ));
diff --git a/src/app/api/envelopes/[id]/reminders/route.ts b/src/app/api/envelopes/[id]/reminders/route.ts
new file mode 100644
index 0000000..7806050
--- /dev/null
+++ b/src/app/api/envelopes/[id]/reminders/route.ts
@@ -0,0 +1,98 @@
+import { NextResponse } from "next/server";
+
+import { requireVerifiedSenderSession } from "@/lib/auth/route-session";
+import { getDb } from "@/lib/db/connection";
+import {
+ changeEnvelopeReminders,
+ EnvelopeMutationError,
+} from "@/lib/envelopes";
+import { changeRemindersSchema } from "@/lib/schemas/envelope";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+
+type EnvelopeRemindersRouteContext = {
+ params: Promise<{
+ id: string;
+ }>;
+};
+
+const noStore = { "cache-control": "private, no-store" };
+
+// Turns automatic reminders on, off, or to another interval for an envelope
+// that is out for signature. The daily job sends them.
+export async function POST(
+ request: Request,
+ context: EnvelopeRemindersRouteContext,
+) {
+ 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_reminders",
+ key: buildRateLimitKey(["envelope-reminders", session.user.id, id]),
+ limit: 20,
+ request,
+ userId: session.user.id,
+ windowMs: 60 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ rateLimitResponse.headers.set("cache-control", "private, no-store");
+ return rateLimitResponse;
+ }
+
+ const parsed = changeRemindersSchema.safeParse(
+ await request.json().catch(() => null),
+ );
+
+ if (!parsed.success) {
+ return NextResponse.json(
+ {
+ error:
+ "Choose reminders between 1 and 30 days apart, or turn them off.",
+ },
+ { headers: noStore, status: 400 },
+ );
+ }
+
+ try {
+ const result = await changeEnvelopeReminders(
+ session.user.id,
+ id,
+ parsed.data.reminderIntervalDays,
+ { database: getDb() },
+ );
+
+ return NextResponse.json(result, { headers: noStore, status: 200 });
+ } catch (error) {
+ if (error instanceof EnvelopeMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: noStore, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "envelope_reminders_failure",
+ ipAddress,
+ message: "Unexpected failure while changing an envelope's reminders.",
+ path: getRequestPathname(request),
+ userId: session.user.id,
+ });
+
+ return NextResponse.json(
+ { error: "Unable to change the reminders." },
+ { headers: noStore, status: 500 },
+ );
+ }
+}
diff --git a/src/app/api/envelopes/[id]/send/route.ts b/src/app/api/envelopes/[id]/send/route.ts
index 61beced..7aee114 100644
--- a/src/app/api/envelopes/[id]/send/route.ts
+++ b/src/app/api/envelopes/[id]/send/route.ts
@@ -23,6 +23,7 @@ type EnvelopeSendRouteContext = {
type SendEnvelopeRequest = {
expiresInDays?: unknown;
+ reminderIntervalDays?: unknown;
permittedUseConfirmed?: boolean;
};
@@ -69,11 +70,15 @@ export async function POST(
const options = sendEnvelopeOptionsSchema.safeParse({
expiresInDays: body.expiresInDays ?? undefined,
+ reminderIntervalDays: body.reminderIntervalDays ?? undefined,
});
if (!options.success) {
return NextResponse.json(
- { error: "Choose a deadline between 1 and 365 days from now." },
+ {
+ error:
+ "Choose a deadline between 1 and 365 days from now, and reminders between 1 and 30 days apart.",
+ },
{ status: 400 },
);
}
@@ -84,6 +89,7 @@ export async function POST(
id,
{
expiresInDays: options.data.expiresInDays,
+ reminderIntervalDays: options.data.reminderIntervalDays,
ipAddress,
senderEmail: session.user.email,
senderName:
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index 913a295..605d345 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -25,9 +25,11 @@ import type {
EnvelopeDetailData,
EnvelopeDetailTimelineItem,
} from "@/lib/envelopes";
+import { formatReminderInterval } from "@/lib/services/reminders";
import {
DEFAULT_ENVELOPE_DEADLINE_DAYS,
ENVELOPE_DEADLINE_DAY_OPTIONS,
+ ENVELOPE_REMINDER_DAY_OPTIONS,
} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
@@ -64,7 +66,12 @@ type EnvelopeDetailRecord = {
title: string;
};
-type ModalState = "change-deadline" | "delete-draft" | "void-envelope" | null;
+type ModalState =
+ | "change-deadline"
+ | "change-reminders"
+ | "delete-draft"
+ | "void-envelope"
+ | null;
const statusPillClasses: Record<EnvelopeStatus, string> = {
completed: "pill-success",
@@ -118,6 +125,7 @@ export function EnvelopeDetailShell({
const [activeModal, setActiveModal] = useState<ModalState>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [isChangingDeadline, setIsChangingDeadline] = useState(false);
+ const [isChangingReminders, setIsChangingReminders] = useState(false);
const [isDeletingDraft, setIsDeletingDraft] = useState(false);
const [isSendingReminder, setIsSendingReminder] = useState(false);
const [isVoidingEnvelope, setIsVoidingEnvelope] = useState(false);
@@ -193,6 +201,11 @@ 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 activeSigner =
activeRecord.status === "sent"
? activeRecord.signers.find((signer) => signer.status === "waiting")
@@ -265,6 +278,33 @@ export function EnvelopeDetailShell({
}
}
+ async function handleConfirmChangeReminders(intervalDays: number | null) {
+ setActionError(null);
+ setIsChangingReminders(true);
+
+ try {
+ const response = await fetch(`/api/envelopes/${envelopeId}/reminders`, {
+ body: JSON.stringify({ reminderIntervalDays: intervalDays }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+
+ if (response.ok || response.status === 404 || response.status === 409) {
+ window.location.reload();
+ return;
+ }
+
+ setActionError(payload?.error ?? "Unable to change the reminders.");
+ } catch {
+ setActionError("Unable to change the reminders.");
+ } finally {
+ setIsChangingReminders(false);
+ }
+ }
+
async function handleConfirmDeleteDraft() {
setActionError(null);
setIsDeletingDraft(true);
@@ -462,6 +502,24 @@ export function EnvelopeDetailShell({
</div>
) : null}
+ {deadline ? (
+ <div className="well mt-3 flex flex-col gap-3 px-5 py-3.5 sm:flex-row sm:items-center sm:justify-between">
+ <p className="text-sm leading-6 text-(--secondary)">
+ {remindersText}
+ </p>
+ <button
+ className="btn-quiet shrink-0"
+ onClick={() => {
+ setActionError(null);
+ setActiveModal("change-reminders");
+ }}
+ type="button"
+ >
+ Change reminders
+ </button>
+ </div>
+ ) : null}
+
{actionError ? (
<div className="notice notice-danger mt-5" role="alert">
{actionError}
@@ -588,6 +646,16 @@ export function EnvelopeDetailShell({
/>
) : null}
+ {activeModal === "change-reminders" ? (
+ <RemindersDialog
+ errorMessage={actionError}
+ initialIntervalDays={reminderIntervalDays}
+ onCancel={() => setActiveModal(null)}
+ onConfirm={handleConfirmChangeReminders}
+ processing={isChangingReminders}
+ />
+ ) : null}
+
{activeModal === "delete-draft" ? (
<ConfirmationDialog
confirmLabel="Delete draft"
@@ -709,6 +777,109 @@ function DeadlineDialog({
);
}
+type RemindersDialogProps = {
+ errorMessage?: string | null;
+ initialIntervalDays: number | null;
+ onCancel: () => void;
+ onConfirm: (intervalDays: number | null) => void | Promise<void>;
+ processing?: boolean;
+};
+
+function RemindersDialog({
+ errorMessage,
+ initialIntervalDays,
+ onCancel,
+ onConfirm,
+ processing = false,
+}: RemindersDialogProps) {
+ const [intervalDays, setIntervalDays] = useState<number | null>(
+ initialIntervalDays,
+ );
+ // An interval set some other way than these choices is still offered.
+ const options = [
+ ...new Set([
+ ...ENVELOPE_REMINDER_DAY_OPTIONS,
+ ...(initialIntervalDays === null ? [] : [initialIntervalDays]),
+ ]),
+ ].sort((left, right) => left - right);
+
+ 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>Automatic reminders</DialogTitle>
+ <DialogDescription asChild>
+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">
+ <p>
+ A reminder goes to the signer whose turn it is when they have
+ not heard from you for this long. Reminders stop once everyone
+ has signed or the deadline passes.
+ </p>
+ </div>
+ </DialogDescription>
+ </DialogHeader>
+
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Send a reminder
+ </span>
+ <select
+ autoFocus
+ className="field-input"
+ disabled={processing}
+ onChange={(event) =>
+ setIntervalDays(
+ event.target.value === "off"
+ ? null
+ : Number(event.target.value),
+ )
+ }
+ value={intervalDays ?? "off"}
+ >
+ <option value="off">{formatReminderInterval(null)}</option>
+ {options.map((option) => (
+ <option key={option} value={option}>
+ {formatReminderInterval(option)}
+ </option>
+ ))}
+ </select>
+ </label>
+
+ {errorMessage ? (
+ <div className="notice notice-danger" role="alert">
+ <p>{errorMessage}</p>
+ </div>
+ ) : null}
+
+ <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-end">
+ <ShellButton
+ disabled={processing}
+ onClick={onCancel}
+ variant="secondary"
+ >
+ Cancel
+ </ShellButton>
+ <ShellButton
+ loading={processing}
+ onClick={() => onConfirm(intervalDays)}
+ >
+ {processing ? "Saving..." : "Save reminders"}
+ </ShellButton>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
type ConfirmationDialogProps = {
confirmLabel: string;
description: readonly string[];
diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsx
index 7fc6c70..ea7c04a 100644
--- a/src/components/envelopes/review-shell.tsx
+++ b/src/components/envelopes/review-shell.tsx
@@ -17,9 +17,12 @@ import {
} from "@/components/ui/dialog";
import type { ReviewEnvelopeData } from "@/lib/envelopes";
import { PERMITTED_USE_PATH } from "@/lib/permitted-uses";
+import { formatReminderInterval } from "@/lib/services/reminders";
import {
DEFAULT_ENVELOPE_DEADLINE_DAYS,
+ DEFAULT_ENVELOPE_REMINDER_DAYS,
ENVELOPE_DEADLINE_DAY_OPTIONS,
+ ENVELOPE_REMINDER_DAY_OPTIONS,
} from "@/lib/types/domain";
import { getSignerPalette } from "./signer-palette";
@@ -68,6 +71,9 @@ export function ReviewShell({
const [deadlineDays, setDeadlineDays] = useState<number>(
DEFAULT_ENVELOPE_DEADLINE_DAYS,
);
+ const [reminderDays, setReminderDays] = useState<number | null>(
+ DEFAULT_ENVELOPE_REMINDER_DAYS,
+ );
const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);
const [notice, setNotice] = useState<string | null>(null);
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
@@ -116,6 +122,7 @@ export function ReviewShell({
body: JSON.stringify({
expiresInDays: deadlineDays,
permittedUseConfirmed: true,
+ reminderIntervalDays: reminderDays,
}),
headers: {
"content-type": "application/json",
@@ -330,28 +337,55 @@ export function ReviewShell({
</p>
<div className="well mt-4 p-4">
- <label className="grid gap-1.5 sm:max-w-xs">
- <span className="text-[0.8125rem] font-semibold text-(--secondary)">
- Signing deadline
- </span>
- <select
- className="field-input"
- disabled={sendPhase === "sending" || Boolean(notice)}
- onChange={(event) =>
- setDeadlineDays(Number(event.target.value))
- }
- value={deadlineDays}
- >
- {ENVELOPE_DEADLINE_DAY_OPTIONS.map((days) => (
- <option key={days} value={days}>
- {days} days
- </option>
- ))}
- </select>
- </label>
- <p className="mt-2 text-sm leading-6 text-(--secondary)">
- Signing links stop working after this. You can change the
- deadline later from the envelope.
+ <div className="grid gap-4 sm:grid-cols-2">
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Signing deadline
+ </span>
+ <select
+ className="field-input"
+ disabled={sendPhase === "sending" || Boolean(notice)}
+ onChange={(event) =>
+ setDeadlineDays(Number(event.target.value))
+ }
+ value={deadlineDays}
+ >
+ {ENVELOPE_DEADLINE_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {days} days
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Automatic reminders
+ </span>
+ <select
+ className="field-input"
+ disabled={sendPhase === "sending" || Boolean(notice)}
+ onChange={(event) =>
+ setReminderDays(
+ event.target.value === "off"
+ ? null
+ : Number(event.target.value),
+ )
+ }
+ value={reminderDays ?? "off"}
+ >
+ <option value="off">{formatReminderInterval(null)}</option>
+ {ENVELOPE_REMINDER_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {formatReminderInterval(days)}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <p className="mt-3 text-sm leading-6 text-(--secondary)">
+ Signing links stop working at the deadline. Reminders go to the
+ signer whose turn it is until they sign. You can change both
+ later from the envelope.
</p>
</div>
</article>
diff --git a/src/lib/automatic-reminders.dbtest.ts b/src/lib/automatic-reminders.dbtest.ts
new file mode 100644
index 0000000..0d4775c
--- /dev/null
+++ b/src/lib/automatic-reminders.dbtest.ts
@@ -0,0 +1,308 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import { openTestDatabase } from "./db/test-database.ts";
+import { runEnvelopeSchedule } from "./envelope-schedule.ts";
+import { changeEnvelopeReminders, EnvelopeMutationError } from "./envelopes.ts";
+import { verifyAuditChain } from "./services/audit.ts";
+import type {
+ EmailService,
+ TransactionalEmailMessage,
+} from "./services/email.ts";
+import { hashOpaqueToken } from "./services/opaque-tokens.ts";
+import { issueSigningLink } from "./services/signing-links.ts";
+
+// Automatic reminders against a real Postgres: who the daily job reminds,
+// how often, and what a failed email leaves behind.
+// Run with `npm run test:db`.
+
+process.env.APP_URL ??= "https://sign.example.test";
+
+const HOUR = 60 * 60;
+const DAY = 24 * HOUR;
+// Far from the present, so envelopes left by other tests are never due.
+const SENT_AT = 1_500_000_000;
+
+let database: pg.Pool;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ // The reminder email reads the install's name through the shared pool.
+ globalThis.__signudocPgPool = database;
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+});
+
+/** An envelope sent at SENT_AT and waiting on its one signer. */
+async function createSentEnvelope({
+ expiresAt = SENT_AT + 30 * DAY,
+ reminderIntervalDays,
+ signerStatus = "notified",
+}: {
+ expiresAt?: number | null;
+ reminderIntervalDays: number | null;
+ signerStatus?: "notified" | "signed";
+}) {
+ const userId = randomUUID();
+ const envelopeId = randomUUID();
+ const signerId = randomUUID();
+ const link = await issueSigningLink({
+ expiresInSeconds: 30 * DAY,
+ issuedAt: SENT_AT,
+ });
+
+ createdUsers.push(userId);
+ await database.query(
+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,
+ [userId, `${userId}@example.test`],
+ );
+ await database.query(
+ `
+ insert into envelopes (
+ id, user_id, title, status, 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)
+ `,
+ [
+ envelopeId,
+ userId,
+ `test/${envelopeId}.pdf`,
+ "a".repeat(64),
+ SENT_AT,
+ expiresAt,
+ reminderIntervalDays,
+ ],
+ );
+ await database.query(
+ `
+ insert into signers (
+ id, envelope_id, name, email, sign_order, status,
+ signing_token_hash, signing_token_expires_at, last_notified_at
+ ) values ($1, $2, 'Riley Recipient', $3, 1, $4, $5, $6, $7)
+ `,
+ [
+ signerId,
+ envelopeId,
+ `${signerId}@example.test`,
+ signerStatus,
+ signerStatus === "notified" ? link.tokenHash : null,
+ signerStatus === "notified" ? link.exp : null,
+ SENT_AT,
+ ],
+ );
+
+ return { envelopeId, signerId, tokenHash: link.tokenHash, userId };
+}
+
+async function readSigner(signerId: string) {
+ const result = await database.query<{
+ last_notified_at: number | null;
+ last_nudged_at: number | null;
+ signing_token_expires_at: number | null;
+ signing_token_hash: string | null;
+ }>(
+ `
+ select signing_token_hash, signing_token_expires_at, last_notified_at,
+ last_nudged_at
+ from signers where id = $1
+ `,
+ [signerId],
+ );
+
+ return result.rows[0]!;
+}
+
+async function auditEvents(envelopeId: string) {
+ const result = await database.query<{ event: string }>(
+ `select event from audit_events where envelope_id = $1 order by sequence`,
+ [envelopeId],
+ );
+
+ return result.rows.map((row) => row.event);
+}
+
+function recordingEmailService(failWith?: Error) {
+ const sent: TransactionalEmailMessage[] = [];
+ const service: EmailService = {
+ async send(message) {
+ if (failWith) {
+ throw failWith;
+ }
+
+ sent.push(message);
+
+ return { accepted: [message.to], messageId: "m-1", rejected: [] };
+ },
+ async sendBatch() {
+ throw new Error("not used");
+ },
+ };
+
+ return { sent, service };
+}
+
+function run(now: number, service: EmailService) {
+ return runEnvelopeSchedule({ database, emailService: service, now });
+}
+
+test("the daily job reminds the waiting signer once per interval", async () => {
+ const due = await createSentEnvelope({ reminderIntervalDays: 3 });
+ const { sent, service } = recordingEmailService();
+ const toSigner = () =>
+ sent.filter((message) => message.to.startsWith(due.signerId));
+
+ // Two days in, nothing yet.
+ await run(SENT_AT + 2 * DAY, service);
+ assert.equal(toSigner().length, 0);
+
+ const firstRunAt = SENT_AT + 3 * DAY - HOUR;
+ const first = await run(firstRunAt, service);
+
+ assert.deepEqual(first.reminderFailures, []);
+ assert.equal(toSigner().length, 1);
+
+ const reminder = toSigner()[0]!;
+ const link = /https:\/\/\S+\/sign\/(\S+)/.exec(reminder.textBody);
+
+ assert.equal(reminder.template, "automatic_reminder");
+ assert.equal(
+ reminder.subject,
+ 'Reminder: Sam Sender is waiting for your signature on "Lease"',
+ );
+ assert.match(reminder.textBody, /This request expires on /);
+ assert.ok(link);
+
+ // The reminder carries a new link, which lasts until the same deadline.
+ const signer = await readSigner(due.signerId);
+
+ assert.notEqual(signer.signing_token_hash, due.tokenHash);
+ assert.equal(signer.signing_token_hash, hashOpaqueToken(link[1]!));
+ assert.equal(signer.signing_token_expires_at, SENT_AT + 30 * DAY);
+ assert.equal(signer.last_nudged_at, firstRunAt);
+ assert.deepEqual(await auditEvents(due.envelopeId), [
+ "reminded_auto",
+ "email_sent",
+ ]);
+
+ // The same run again, and the next day's, send nothing more.
+ await run(firstRunAt, service);
+ await run(firstRunAt + DAY, service);
+ assert.equal(toSigner().length, 1);
+
+ await run(firstRunAt + 3 * DAY, service);
+ assert.equal(toSigner().length, 2);
+ assert.equal((await verifyAuditChain(due.envelopeId, database)).ok, true);
+});
+
+test("no reminder when they are off, the deadline passed, or nobody is waiting", async () => {
+ const off = await createSentEnvelope({ reminderIntervalDays: null });
+ const expired = await createSentEnvelope({
+ expiresAt: SENT_AT + DAY,
+ reminderIntervalDays: 1,
+ });
+ const signed = await createSentEnvelope({
+ reminderIntervalDays: 1,
+ signerStatus: "signed",
+ });
+ const { sent, service } = recordingEmailService();
+
+ await run(SENT_AT + 5 * DAY, service);
+
+ for (const envelope of [off, expired, signed]) {
+ assert.equal(
+ sent.some((message) => message.to.startsWith(envelope.signerId)),
+ false,
+ );
+ assert.ok(
+ !(await auditEvents(envelope.envelopeId)).includes("reminded_auto"),
+ );
+ }
+});
+
+test("a reminder whose email fails leaves the signer's link as it was", async () => {
+ const due = await createSentEnvelope({ reminderIntervalDays: 1 });
+ const failing = recordingEmailService(new Error("mail is down"));
+ const failed = await run(SENT_AT + DAY, failing.service);
+
+ assert.ok(failed.reminderFailures.includes(due.envelopeId));
+
+ const signer = await readSigner(due.signerId);
+
+ assert.equal(signer.signing_token_hash, due.tokenHash);
+ assert.equal(signer.last_nudged_at, null);
+ assert.equal(signer.last_notified_at, SENT_AT);
+ assert.deepEqual(await auditEvents(due.envelopeId), []);
+
+ // So the next run tries again.
+ const working = recordingEmailService();
+
+ await run(SENT_AT + DAY + HOUR, working.service);
+ assert.equal(
+ working.sent.filter((message) => message.to.startsWith(due.signerId))
+ .length,
+ 1,
+ );
+});
+
+test("a run that is out of time leaves the rest for the next one", async () => {
+ const due = await createSentEnvelope({ reminderIntervalDays: 1 });
+ const { sent, service } = recordingEmailService();
+ const summary = await runEnvelopeSchedule({
+ database,
+ emailService: service,
+ now: SENT_AT + DAY,
+ timeBudgetMs: 0,
+ });
+
+ assert.equal(summary.stoppedEarly, true);
+ assert.equal(sent.length, 0);
+ assert.equal(
+ (await readSigner(due.signerId)).signing_token_hash,
+ due.tokenHash,
+ );
+});
+
+test("only the owner changes reminders, and only while the envelope is out", async () => {
+ const mine = await createSentEnvelope({ reminderIntervalDays: null });
+ const other = await createSentEnvelope({ reminderIntervalDays: null });
+
+ await assert.rejects(
+ changeEnvelopeReminders(other.userId, mine.envelopeId, 2, { database }),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError && error.statusCode === 404,
+ );
+
+ assert.deepEqual(
+ await changeEnvelopeReminders(mine.userId, mine.envelopeId, 2, {
+ database,
+ }),
+ { envelopeId: mine.envelopeId, reminderIntervalDays: 2 },
+ );
+
+ const { sent, service } = recordingEmailService();
+
+ await run(SENT_AT + 2 * DAY, service);
+ assert.equal(
+ sent.filter((message) => message.to.startsWith(mine.signerId)).length,
+ 1,
+ );
+
+ await database.query(`update envelopes set status = 'voided' where id = $1`, [
+ mine.envelopeId,
+ ]);
+ await assert.rejects(
+ changeEnvelopeReminders(mine.userId, mine.envelopeId, null, { database }),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError && error.statusCode === 409,
+ );
+});
diff --git a/src/lib/envelope-schedule.ts b/src/lib/envelope-schedule.ts
index 149e38d..9904f71 100644
--- a/src/lib/envelope-schedule.ts
+++ b/src/lib/envelope-schedule.ts
@@ -1,11 +1,17 @@
import { type DbPool, queryMany, withTransaction } from "./db/connection.ts";
import { formatDeadline } from "./envelope-deadline.ts";
+import { sendAutomaticEnvelopeReminder } from "./reminders.ts";
import { lockEnvelopeAuditChain, recordAuditEvent } from "./services/audit.ts";
import { createEmailService, type EmailService } from "./services/email.ts";
+import { AUTOMATIC_REMINDER_SLACK_SECONDS } from "./services/reminders.ts";
import { resolveAppUrl } from "./utils/env.ts";
-// What the daily job does for envelopes that are out for signature: it tells
-// a sender once when a deadline has passed with signatures still missing.
+// What the daily job does for envelopes that are out for signature:
+//
+// - it tells a sender once when a deadline has passed with signatures still
+// missing;
+// - it reminds the signer whose turn it is, on envelopes whose sender asked
+// for automatic reminders.
//
// It runs from the same cron call as the cleanup (see retention-job.ts), so
// an install needs no second schedule. Each envelope is claimed in the
@@ -14,10 +20,26 @@ import { resolveAppUrl } from "./utils/env.ts";
// never sends twice.
const BATCH_SIZE = 200;
+// The job shares one function call with the cleanup, and a mail provider
+// takes about half a second per message. Past this, what is left waits for
+// the next run instead of risking the call being cut off mid-send.
+const TIME_BUDGET_MS = 60_000;
export type EnvelopeScheduleSummary = {
expiryNoticeFailures: string[];
expiryNoticesSent: number;
+ reminderFailures: string[];
+ remindersSent: number;
+ /** True when the time ran out and some envelopes wait for the next run. */
+ stoppedEarly: boolean;
+};
+
+type ScheduleRun = {
+ database: DbPool;
+ emailService: () => EmailService;
+ now: number;
+ outOfTime: () => boolean;
+ summary: EnvelopeScheduleSummary;
};
type ExpiredEnvelopeRow = {
@@ -164,15 +186,21 @@ function buildExpiryNotice(envelope: ExpiredEnvelopeRow) {
};
}
-async function sendExpiryNotices(
- now: number,
- database: DbPool,
- emailService: () => EmailService,
- summary: EnvelopeScheduleSummary,
-): Promise<void> {
+async function sendExpiryNotices({
+ database,
+ emailService,
+ now,
+ outOfTime,
+ summary,
+}: ScheduleRun): Promise<void> {
const expired = await listExpiredEnvelopesToNotify(now, database);
for (const envelope of expired) {
+ if (outOfTime()) {
+ summary.stoppedEarly = true;
+ return;
+ }
+
try {
if (!(await claimExpiryNotice(envelope, now, database))) {
continue;
@@ -203,25 +231,115 @@ async function sendExpiryNotices(
}
}
+/**
+ * Envelopes whose current signer has heard nothing for the envelope's
+ * reminder interval. Expired ones are left out: their link is dead, and the
+ * sender has been told.
+ */
+async function listEnvelopesDueForReminder(
+ now: number,
+ database: DbPool,
+): Promise<string[]> {
+ const rows = await queryMany<{ id: string }>(
+ database,
+ `
+ SELECT e.id
+ FROM envelopes e
+ JOIN signers s
+ ON s.envelope_id = e.id
+ AND s.status = 'notified'
+ WHERE e.status = 'sent'
+ AND e.reminder_interval_days IS NOT NULL
+ AND (e.expires_at IS NULL OR e.expires_at > $1)
+ AND GREATEST(
+ COALESCE(s.last_notified_at, 0),
+ COALESCE(s.last_nudged_at, 0)
+ ) > 0
+ AND GREATEST(
+ COALESCE(s.last_notified_at, 0),
+ COALESCE(s.last_nudged_at, 0)
+ ) + e.reminder_interval_days * 86400 - $2 <= $1
+ ORDER BY
+ GREATEST(
+ COALESCE(s.last_notified_at, 0),
+ COALESCE(s.last_nudged_at, 0)
+ ) ASC,
+ e.id ASC
+ LIMIT ${BATCH_SIZE}
+ `,
+ [now, AUTOMATIC_REMINDER_SLACK_SECONDS],
+ );
+
+ return rows.map((row) => row.id);
+}
+
+async function sendAutomaticReminders({
+ database,
+ emailService,
+ now,
+ outOfTime,
+ summary,
+}: ScheduleRun): Promise<void> {
+ for (const envelopeId of await listEnvelopesDueForReminder(now, database)) {
+ if (outOfTime()) {
+ summary.stoppedEarly = true;
+ return;
+ }
+
+ try {
+ const sent = await sendAutomaticEnvelopeReminder(envelopeId, {
+ database,
+ emailService: emailService(),
+ nowUnixTimestamp: now,
+ });
+
+ if (sent) {
+ summary.remindersSent += 1;
+ }
+ } catch (error) {
+ summary.reminderFailures.push(envelopeId);
+ console.error(
+ `Automatic reminder failed for envelope ${envelopeId}:`,
+ error,
+ );
+ }
+ }
+}
+
export async function runEnvelopeSchedule({
database,
emailService,
now = Math.floor(Date.now() / 1000),
+ timeBudgetMs = TIME_BUDGET_MS,
}: {
database: DbPool;
emailService?: EmailService;
now?: number;
+ timeBudgetMs?: number;
}): Promise<EnvelopeScheduleSummary> {
const summary: EnvelopeScheduleSummary = {
expiryNoticeFailures: [],
expiryNoticesSent: 0,
+ reminderFailures: [],
+ remindersSent: 0,
+ stoppedEarly: false,
};
+ const stopAt = Date.now() + timeBudgetMs;
let service = emailService;
// Made only when there is something to send: an install without email
// set up yet must not fail the whole job.
const getEmailService = () => (service ??= createEmailService());
- await sendExpiryNotices(now, database, getEmailService, summary);
+ const run: ScheduleRun = {
+ database,
+ emailService: getEmailService,
+ now,
+ outOfTime: () => Date.now() >= stopAt,
+ summary,
+ };
+
+ await sendExpiryNotices(run);
+ await sendAutomaticReminders(run);
return summary;
}
@@ -229,5 +347,8 @@ export async function runEnvelopeSchedule({
export function envelopeScheduleFailed(
summary: EnvelopeScheduleSummary,
): boolean {
- return summary.expiryNoticeFailures.length > 0;
+ return (
+ summary.expiryNoticeFailures.length > 0 ||
+ summary.reminderFailures.length > 0
+ );
}
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index b0ab41a..e69fe68 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -16,9 +16,11 @@ import {
} from "./envelope-deadline.ts";
import {
changeDeadlineResponseSchema,
+ changeRemindersResponseSchema,
envelopeListFiltersSchema,
type AuditEventRecord,
type ChangeDeadlineResponse,
+ type ChangeRemindersResponse,
envelopeCreateResponseSchema,
envelopePageSchema,
envelopeRecordSchema,
@@ -102,6 +104,8 @@ type CreateDraftEnvelopeInput = {
type SendDraftEnvelopeInput = {
/** How many days signers get. The default applies when left out. */
expiresInDays?: number;
+ /** Days between automatic reminders. Null or left out means none. */
+ reminderIntervalDays?: number | null;
ipAddress?: string | null;
senderEmail: string;
senderName: string;
@@ -130,6 +134,7 @@ type EnvelopeRow = {
evidenceKey: string | null;
expiresAt: number | null;
id: string;
+ reminderIntervalDays: number | null;
pageCount: number;
sentAt: number | null;
signedPdfKey: string | null;
@@ -319,6 +324,8 @@ export type EnvelopeDetailData = {
createdAtLabel: string;
/** Set while the envelope is out for signature. */
deadline: EnvelopeDetailDeadline | null;
+ /** Days between automatic reminders while it is out. Null when off. */
+ reminderIntervalDays: number | null;
envelopeId: string;
manualReminder: EnvelopeDetailManualReminderState | null;
signers: readonly EnvelopeDetailSignerView[];
@@ -394,6 +401,7 @@ const TIMELINE_TONE_MAP: Record<
declined: "danger",
email_sent: "neutral",
expired: "danger",
+ reminded_auto: "neutral",
reminded_manual: "neutral",
sent: "neutral",
signed: "success",
@@ -680,6 +688,7 @@ async function getEnvelopeByIdForUser(
declined_at AS "declinedAt",
voided_at AS "voidedAt",
expires_at AS "expiresAt",
+ reminder_interval_days AS "reminderIntervalDays",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -1024,6 +1033,8 @@ function buildTimelineDescription(event: AuditEventRecord): string {
: `Declined by ${targetLabel}`;
case "reminded_manual":
return `Manual reminder sent to ${targetLabel}`;
+ case "reminded_auto":
+ return `Automatic reminder sent to ${targetLabel}`;
case "consented":
return `${targetLabel} agreed to use electronic records and signatures`;
case "verified":
@@ -1173,6 +1184,7 @@ export async function listEnvelopesForUser(
declined_at AS "declinedAt",
voided_at AS "voidedAt",
expires_at AS "expiresAt",
+ reminder_interval_days AS "reminderIntervalDays",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM envelopes
@@ -1307,6 +1319,10 @@ export async function getEnvelopeDetailDataForUser(
}
: null,
envelopeId,
+ reminderIntervalDays:
+ envelope.status === "sent"
+ ? (envelope.reminderIntervalDays ?? null)
+ : null,
manualReminder,
signers: signerViews,
status: envelope.status,
@@ -1654,12 +1670,20 @@ export async function sendDraftEnvelope(
sent_at = $1,
updated_at = $2,
expires_at = $5,
- expiry_notified_at = NULL
+ expiry_notified_at = NULL,
+ reminder_interval_days = $6
WHERE id = $3
AND user_id = $4
AND status = 'draft'
`,
- [sentAt, sentAt, envelopeId, userId, expiresAt],
+ [
+ sentAt,
+ sentAt,
+ envelopeId,
+ userId,
+ expiresAt,
+ input.reminderIntervalDays ?? null,
+ ],
);
if (updatedEnvelope.rowCount !== 1) {
@@ -1730,6 +1754,7 @@ export async function sendDraftEnvelope(
metadata: {
// The send route refuses a send without this confirmation.
expiresAt,
+ reminderIntervalDays: input.reminderIntervalDays ?? null,
permittedUseConfirmed: true,
permittedUseVersion: PERMITTED_USE_VERSION,
signerEmail: firstSigner.email,
@@ -1770,6 +1795,7 @@ export async function sendDraftEnvelope(
status = 'draft',
sent_at = NULL,
expires_at = NULL,
+ reminder_interval_days = NULL,
updated_at = $1
WHERE id = $2
AND user_id = $3
@@ -1933,6 +1959,46 @@ export async function changeEnvelopeDeadline(
});
}
+/**
+ * Turns automatic reminders on, off, or to another interval for an envelope
+ * that is out for signature. The interval counts from the last time the
+ * signer was written to, so turning them on can send one the next day.
+ */
+export async function changeEnvelopeReminders(
+ userId: string,
+ envelopeId: string,
+ reminderIntervalDays: number | null,
+ {
+ database = getDb(),
+ nowUnixTimestamp = Math.floor(Date.now() / 1000),
+ }: { database?: DbExecutor; nowUnixTimestamp?: number } = {},
+): Promise<ChangeRemindersResponse> {
+ const updated = await database.query(
+ `
+ UPDATE envelopes
+ SET reminder_interval_days = $1, updated_at = $2
+ WHERE id = $3 AND user_id = $4 AND status = 'sent'
+ `,
+ [reminderIntervalDays, nowUnixTimestamp, envelopeId, userId],
+ );
+
+ 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);
+ }
+
+ return changeRemindersResponseSchema.parse({
+ envelopeId,
+ reminderIntervalDays,
+ });
+}
+
export async function voidSentEnvelope(
userId: string,
envelopeId: string,
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index 121a61f..ff620d2 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -22,12 +22,13 @@ import {
recordAuditEvent,
recordEmailSent,
} from "./services/audit.ts";
-import { createEmailService } from "./services/email.ts";
+import { createEmailService, type EmailService } from "./services/email.ts";
import { buildDeadlineLine } from "./services/signing-invitation-email.ts";
import { withUserEmailLegalFooter } from "./services/email-legal-footer.ts";
import {
formatReminderAvailableAt,
getManualNudgeAvailableAt,
+ isAutomaticReminderDue,
} from "./services/reminders.ts";
import {
issueSigningLink,
@@ -38,6 +39,9 @@ import { escapeHtml } from "./utils/html.ts";
type ReminderEnvelopeRow = {
expiresAt: number | null;
id: string;
+ ownerEmail: string;
+ ownerName: string | null;
+ reminderIntervalDays: number | null;
status: EnvelopeRecord["status"];
title: string;
updatedAt: number;
@@ -65,7 +69,16 @@ type ManualNudgeInput = {
userAgent?: string | null;
};
-type PersistedManualNudge = {
+/**
+ * Who is asking for a reminder: the sender, by pressing the button, or the
+ * daily job, because the envelope's reminder interval has passed.
+ */
+type ReminderRequest =
+ | ({ kind: "manual"; userId: string } & ManualNudgeInput)
+ | { kind: "automatic" };
+
+type PersistedReminder = {
+ auditEventId: string;
envelopeExpiresAt: number | null;
envelopeId: string;
envelopeTitle: string;
@@ -85,10 +98,12 @@ type PersistedManualNudge = {
signerId: string;
signerName: string;
senderName: string;
+ userId: string;
};
-type SendManualEnvelopeNudgeOptions = {
+type SendReminderOptions = {
database?: DbPool;
+ emailService?: EmailService;
nowUnixTimestamp?: number;
};
@@ -116,24 +131,29 @@ export class ReminderMutationError extends Error {
}
}
-async function getEnvelopeByIdForUser(
+/** The envelope, and only for its owner when a user is given. */
+async function getReminderEnvelope(
envelopeId: string,
- userId: string,
+ userId: string | null,
database: DbExecutor,
): Promise<ReminderEnvelopeRow | null> {
return queryOne<ReminderEnvelopeRow>(
database,
`
SELECT
- id,
- user_id AS "userId",
- title,
- status,
- expires_at AS "expiresAt",
- updated_at AS "updatedAt"
- FROM envelopes
- WHERE id = $1
- AND user_id = $2
+ e.id,
+ e.user_id AS "userId",
+ e.title,
+ e.status,
+ e.expires_at AS "expiresAt",
+ e.reminder_interval_days AS "reminderIntervalDays",
+ e.updated_at AS "updatedAt",
+ u.email AS "ownerEmail",
+ u.name AS "ownerName"
+ FROM envelopes e
+ JOIN "user" u ON u.id = e.user_id
+ WHERE e.id = $1
+ AND ($2::text IS NULL OR e.user_id = $2)
`,
[envelopeId, userId],
);
@@ -173,13 +193,19 @@ function buildReminderEmail(input: {
envelopeId: string;
envelopeTitle: string;
expiresAt?: number | null;
+ kind: ReminderRequest["kind"];
senderName: string;
signerEmail: string;
signerName: string;
signingUrl: string;
}) {
- const subject = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}"`;
- const introLine = `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}" through ${input.branding.productName}.`;
+ const automatic = input.kind === "automatic";
+ const subject = automatic
+ ? `Reminder: ${input.senderName} is waiting for your signature on "${input.envelopeTitle}"`
+ : `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}"`;
+ const introLine = automatic
+ ? `${input.senderName} is still waiting for your signature on "${input.envelopeTitle}", sent through ${input.branding.productName}.`
+ : `${input.senderName} sent you a reminder to sign "${input.envelopeTitle}" through ${input.branding.productName}.`;
const deadlineLine = buildDeadlineLine(input.expiresAt);
const textBody = [
`Hi ${input.signerName},`,
@@ -212,20 +238,44 @@ function buildReminderEmail(input: {
return {
htmlBody: legalFooter.htmlBody,
subject,
- template: "manual_nudge" as const,
+ template: automatic
+ ? ("automatic_reminder" as const)
+ : ("manual_nudge" as const),
textBody: legalFooter.textBody,
to: input.signerEmail,
};
}
-async function persistManualNudge(
- userId: string,
+/** Why the daily job should leave an envelope alone, or null to go ahead. */
+function getAutomaticReminderObstacle(
+ envelope: ReminderEnvelopeRow,
+ signer: ReminderSignerRow,
+ now: number,
+): string | null {
+ if (envelope.reminderIntervalDays === null) {
+ return "Automatic reminders are off for this envelope.";
+ }
+
+ return isAutomaticReminderDue(
+ {
+ intervalDays: envelope.reminderIntervalDays,
+ lastNotifiedAt: signer.lastNotifiedAt,
+ lastNudgedAt: signer.lastNudgedAt,
+ },
+ now,
+ )
+ ? null
+ : "This envelope's next reminder is not due yet.";
+}
+
+async function persistReminder(
envelopeId: string,
- input: ManualNudgeInput,
+ request: ReminderRequest,
dispatchedAt: number,
database: DbPool,
-): Promise<PersistedManualNudge> {
- const envelope = await getEnvelopeByIdForUser(envelopeId, userId, database);
+): Promise<PersistedReminder> {
+ const userId = request.kind === "manual" ? request.userId : null;
+ const envelope = await getReminderEnvelope(envelopeId, userId, database);
if (!envelope) {
throw new ReminderMutationError("This envelope is unavailable.", 404);
@@ -263,11 +313,7 @@ async function persistManualNudge(
issuedAt: dispatchedAt,
});
return withTransaction(async (tx) => {
- const persistedEnvelope = await getEnvelopeByIdForUser(
- envelopeId,
- userId,
- tx,
- );
+ const persistedEnvelope = await getReminderEnvelope(envelopeId, userId, tx);
if (!persistedEnvelope) {
throw new ReminderMutationError("This envelope is unavailable.", 404);
@@ -297,7 +343,17 @@ async function persistManualNudge(
);
}
- if (typeof persistedSigner.lastNudgedAt === "number") {
+ if (request.kind === "automatic") {
+ const obstacle = getAutomaticReminderObstacle(
+ persistedEnvelope,
+ persistedSigner,
+ dispatchedAt,
+ );
+
+ if (obstacle) {
+ throw new ReminderMutationError(obstacle, 409);
+ }
+ } else if (typeof persistedSigner.lastNudgedAt === "number") {
const nextAvailableAt = getManualNudgeAvailableAt(
persistedSigner.lastNudgedAt,
);
@@ -319,10 +375,9 @@ async function persistManualNudge(
UPDATE envelopes
SET updated_at = $1
WHERE id = $2
- AND user_id = $3
AND status = 'sent'
`,
- [dispatchedAt, envelopeId, userId],
+ [dispatchedAt, envelopeId],
);
const signerUpdate = await tx.query(
@@ -356,26 +411,39 @@ async function persistManualNudge(
);
}
- await recordAuditEvent(
- {
- actorEmail: input.senderEmail,
- actorType: "sender",
- createdAt: dispatchedAt,
- envelopeId,
- event: "reminded_manual",
- ipAddress: input.ipAddress ?? null,
- metadata: {
- signerEmail: persistedSigner.email,
- signerId: persistedSigner.id,
- signerName: persistedSigner.name,
- signerOrder: persistedSigner.signOrder,
- },
- userAgent: input.userAgent ?? null,
- },
+ const signerMetadata = {
+ signerEmail: persistedSigner.email,
+ signerId: persistedSigner.id,
+ signerName: persistedSigner.name,
+ signerOrder: persistedSigner.signOrder,
+ };
+ const auditEvent = await recordAuditEvent(
+ request.kind === "manual"
+ ? {
+ actorEmail: request.senderEmail,
+ actorType: "sender",
+ createdAt: dispatchedAt,
+ envelopeId,
+ event: "reminded_manual",
+ ipAddress: request.ipAddress ?? null,
+ metadata: signerMetadata,
+ userAgent: request.userAgent ?? null,
+ }
+ : {
+ actorType: "system",
+ createdAt: dispatchedAt,
+ envelopeId,
+ event: "reminded_auto",
+ metadata: {
+ ...signerMetadata,
+ intervalDays: persistedEnvelope.reminderIntervalDays,
+ },
+ },
tx,
);
return {
+ auditEventId: auditEvent.id,
envelopeExpiresAt: persistedEnvelope.expiresAt,
envelopeId,
envelopeTitle: persistedEnvelope.title,
@@ -390,32 +458,29 @@ async function persistManualNudge(
signingTokenHash: persistedSigner.signingTokenHash,
updatedAt: persistedSigner.updatedAt,
},
- senderName: input.senderName,
+ senderName:
+ request.kind === "manual"
+ ? request.senderName
+ : persistedEnvelope.ownerName?.trim() || persistedEnvelope.ownerEmail,
signerEmail: persistedSigner.email,
signerId: persistedSigner.id,
signerName: persistedSigner.name,
+ userId: persistedEnvelope.userId,
};
}, database);
}
-export async function sendManualEnvelopeNudge(
- userId: string,
- envelopeId: string,
- input: ManualNudgeInput,
- {
- database = getDb(),
- nowUnixTimestamp = Math.floor(Date.now() / 1000),
- }: SendManualEnvelopeNudgeOptions = {},
-) {
- const persisted = await persistManualNudge(
- userId,
- envelopeId,
- input,
- nowUnixTimestamp,
- database,
- );
- const emailService = createEmailService();
-
+/**
+ * Sends the reminder that was just written to the database. If the email
+ * fails, the database is put back as it was and the error is passed on.
+ */
+async function deliverReminder(
+ persisted: PersistedReminder,
+ kind: ReminderRequest["kind"],
+ database: DbPool,
+ emailService: EmailService,
+): Promise<void> {
+ const template = kind === "automatic" ? "automatic_reminder" : "manual_nudge";
let reminderMessageId: string | undefined;
try {
@@ -426,6 +491,7 @@ export async function sendManualEnvelopeNudge(
envelopeId: persisted.envelopeId,
envelopeTitle: persisted.envelopeTitle,
expiresAt: persisted.envelopeExpiresAt,
+ kind,
senderName: persisted.senderName,
signerEmail: persisted.signerEmail,
signerName: persisted.signerName,
@@ -443,7 +509,11 @@ export async function sendManualEnvelopeNudge(
AND user_id = $3
AND status = 'sent'
`,
- [persisted.previousEnvelopeUpdatedAt, persisted.envelopeId, userId],
+ [
+ persisted.previousEnvelopeUpdatedAt,
+ persisted.envelopeId,
+ persisted.userId,
+ ],
);
await tx.query(
@@ -475,9 +545,7 @@ export async function sendManualEnvelopeNudge(
`
DELETE FROM audit_events
WHERE envelope_id = $1
- AND event = 'reminded_manual'
- AND created_at = $2
- AND actor_email = $3
+ AND id = $2
-- Only while it is still the newest link of the audit chain: an
-- event recorded after it (say, the invitation was opened before
-- the send failed) chains to it, so it stays as history.
@@ -485,11 +553,11 @@ export async function sendManualEnvelopeNudge(
SELECT max(sequence) FROM audit_events WHERE envelope_id = $1
)
`,
- [persisted.envelopeId, nowUnixTimestamp, input.senderEmail],
+ [persisted.envelopeId, persisted.auditEventId],
);
}, database).catch((rollbackError) => {
console.error(
- `Failed to roll back manual reminder for envelope ${persisted.envelopeId} after email delivery failure:`,
+ `Failed to roll back a reminder for envelope ${persisted.envelopeId} after email delivery failure:`,
rollbackError,
);
});
@@ -503,10 +571,35 @@ export async function sendManualEnvelopeNudge(
messageId: reminderMessageId,
recipient: persisted.signerEmail,
signerId: persisted.signerId,
- template: "manual_nudge",
+ template,
},
database,
);
+}
+
+export async function sendManualEnvelopeNudge(
+ userId: string,
+ envelopeId: string,
+ input: ManualNudgeInput,
+ {
+ database = getDb(),
+ emailService,
+ nowUnixTimestamp = Math.floor(Date.now() / 1000),
+ }: SendReminderOptions = {},
+) {
+ const persisted = await persistReminder(
+ envelopeId,
+ { ...input, kind: "manual", userId },
+ nowUnixTimestamp,
+ database,
+ );
+
+ await deliverReminder(
+ persisted,
+ "manual",
+ database,
+ emailService ?? createEmailService(),
+ );
return manualNudgeResponseSchema.parse({
envelopeId: persisted.envelopeId,
@@ -517,3 +610,46 @@ export async function sendManualEnvelopeNudge(
signerName: persisted.signerName,
});
}
+
+/**
+ * The daily job's reminder to the signer whose turn it is. Like the
+ * sender's own reminder, it carries a new link and retires the old one.
+ *
+ * Returns false, having sent nothing, when the envelope no longer needs
+ * one: it was signed, voided or expired, reminders were turned off, or a
+ * reminder went out since the job listed it.
+ */
+export async function sendAutomaticEnvelopeReminder(
+ envelopeId: string,
+ {
+ database = getDb(),
+ emailService,
+ nowUnixTimestamp = Math.floor(Date.now() / 1000),
+ }: SendReminderOptions = {},
+): Promise<boolean> {
+ let persisted: PersistedReminder;
+
+ try {
+ persisted = await persistReminder(
+ envelopeId,
+ { kind: "automatic" },
+ nowUnixTimestamp,
+ database,
+ );
+ } catch (error) {
+ if (error instanceof ReminderMutationError) {
+ return false;
+ }
+
+ throw error;
+ }
+
+ await deliverReminder(
+ persisted,
+ "automatic",
+ database,
+ emailService ?? createEmailService(),
+ );
+
+ return true;
+}
diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.ts
index a06c551..4e5641b 100644
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@ -175,14 +175,21 @@ export async function runRetentionJob({
database,
emailService,
}).catch((error: unknown) => {
- // A database from before deadlines has no column to read: nothing is
- // due there. Anything else is a failure worth a red cron run.
+ // A database from before deadlines and reminders has no column to
+ // read: nothing is due there. Anything else is a failure worth a red
+ // cron run.
if (!isMissingSchemaError(error)) {
console.error("The envelope schedule failed:", error);
return null;
}
- return { expiryNoticeFailures: [], expiryNoticesSent: 0 };
+ return {
+ expiryNoticeFailures: [],
+ expiryNoticesSent: 0,
+ reminderFailures: [],
+ remindersSent: 0,
+ stoppedEarly: false,
+ };
});
return { schedule, status: "ran", summary };
diff --git a/src/lib/schemas/envelope.ts b/src/lib/schemas/envelope.ts
index be9f194..9208b28 100644
--- a/src/lib/schemas/envelope.ts
+++ b/src/lib/schemas/envelope.ts
@@ -6,6 +6,7 @@ import {
downloadFileTypes,
envelopeStatuses,
MAX_ENVELOPE_DEADLINE_DAYS,
+ MAX_ENVELOPE_REMINDER_DAYS,
} from "../types/domain.ts";
import {
emailSchema,
@@ -37,9 +38,27 @@ export const deadlineDaysSchema = z
.min(1)
.max(MAX_ENVELOPE_DEADLINE_DAYS);
+/** Days between automatic reminders. Null turns them off. */
+export const reminderIntervalDaysSchema = z
+ .number()
+ .int()
+ .min(1)
+ .max(MAX_ENVELOPE_REMINDER_DAYS)
+ .nullable();
+
/** What the sender chooses on the last step before sending. */
export const sendEnvelopeOptionsSchema = z.object({
expiresInDays: deadlineDaysSchema.optional(),
+ reminderIntervalDays: reminderIntervalDaysSchema.optional(),
+});
+
+export const changeRemindersSchema = z.object({
+ reminderIntervalDays: reminderIntervalDaysSchema,
+});
+
+export const changeRemindersResponseSchema = z.object({
+ envelopeId: idSchema,
+ reminderIntervalDays: reminderIntervalDaysSchema,
});
export const changeDeadlineSchema = z.object({
@@ -127,6 +146,8 @@ export const envelopeRecordSchema = z.object({
voidedAt: unixTimestampSchema.nullable().optional(),
/** When the request stops being signable. See envelope-deadline.ts. */
expiresAt: unixTimestampSchema.nullable().optional(),
+ /** Days between automatic reminders, or null for none. */
+ reminderIntervalDays: reminderIntervalDaysSchema.optional(),
createdAt: unixTimestampSchema,
updatedAt: unixTimestampSchema,
});
@@ -139,6 +160,9 @@ export type SendEnvelopeOptions = z.infer<typeof sendEnvelopeOptionsSchema>;
export type ChangeDeadlineResponse = z.infer<
typeof changeDeadlineResponseSchema
>;
+export type ChangeRemindersResponse = z.infer<
+ typeof changeRemindersResponseSchema
+>;
export type VoidEnvelopeResponse = z.infer<typeof voidEnvelopeResponseSchema>;
export type ManualNudgeResponse = z.infer<typeof manualNudgeResponseSchema>;
export type EnvelopeListFilters = z.infer<typeof envelopeListFiltersSchema>;
diff --git a/src/lib/services/reminders.test.ts b/src/lib/services/reminders.test.ts
new file mode 100644
index 0000000..c88bc56
--- /dev/null
+++ b/src/lib/services/reminders.test.ts
@@ -0,0 +1,51 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ formatReminderInterval,
+ getAutomaticReminderDueAt,
+ isAutomaticReminderDue,
+} from "./reminders.ts";
+
+const HOUR = 60 * 60;
+const DAY = 24 * HOUR;
+const SENT = 1_800_000_000;
+
+test("an automatic reminder is due half a day before its interval is up", () => {
+ assert.equal(getAutomaticReminderDueAt(SENT, 3), SENT + 3 * DAY - 12 * HOUR);
+
+ const signer = { intervalDays: 1, lastNotifiedAt: SENT, lastNudgedAt: null };
+
+ // Sent an hour after the job ran: the next day's run still counts.
+ assert.equal(isAutomaticReminderDue(signer, SENT + 23 * HOUR), true);
+ assert.equal(isAutomaticReminderDue(signer, SENT + 12 * HOUR), true);
+ assert.equal(isAutomaticReminderDue(signer, SENT + 11 * HOUR), false);
+});
+
+test("the interval counts from the last invitation or reminder of any kind", () => {
+ const reminded = {
+ intervalDays: 2,
+ lastNotifiedAt: SENT,
+ lastNudgedAt: SENT + 5 * DAY,
+ };
+
+ assert.equal(isAutomaticReminderDue(reminded, SENT + 6 * DAY), false);
+ assert.equal(isAutomaticReminderDue(reminded, SENT + 7 * DAY), true);
+});
+
+test("a signer who was never written to gets no reminder", () => {
+ assert.equal(
+ isAutomaticReminderDue(
+ { intervalDays: 1, lastNotifiedAt: null, lastNudgedAt: null },
+ SENT,
+ ),
+ false,
+ );
+});
+
+test("an interval is named the way a person would say it", () => {
+ assert.equal(formatReminderInterval(null), "Off");
+ assert.equal(formatReminderInterval(1), "Every day");
+ assert.equal(formatReminderInterval(3), "Every 3 days");
+ assert.equal(formatReminderInterval(7), "Every week");
+});
diff --git a/src/lib/services/reminders.ts b/src/lib/services/reminders.ts
index e4e27e2..27ec1e4 100644
--- a/src/lib/services/reminders.ts
+++ b/src/lib/services/reminders.ts
@@ -22,6 +22,71 @@ const reminderAvailabilityFormatter = new Intl.DateTimeFormat("en-US", {
month: "long",
});
+const SECONDS_PER_DAY = 24 * 60 * 60;
+
+/** "Off", "Every day", "Every 3 days", "Every week". */
+export function formatReminderInterval(intervalDays: number | null): string {
+ if (intervalDays === null) {
+ return "Off";
+ }
+
+ if (intervalDays === 1) {
+ return "Every day";
+ }
+
+ return intervalDays === 7
+ ? "Every week"
+ : `Every ${String(intervalDays)} days`;
+}
+
+/**
+ * The daily job runs once a day at a fixed hour, so "every N days" is read
+ * with half a day of slack: a reminder is due once N days less twelve hours
+ * have passed. Without it, an envelope sent an hour after the job ran would
+ * wait a whole extra day every time.
+ */
+export const AUTOMATIC_REMINDER_SLACK_SECONDS = 12 * 60 * 60;
+
+/** The moment from which the daily job may send the next reminder. */
+export function getAutomaticReminderDueAt(
+ lastContactAt: number,
+ intervalDays: number,
+): number {
+ return (
+ lastContactAt +
+ intervalDays * SECONDS_PER_DAY -
+ AUTOMATIC_REMINDER_SLACK_SECONDS
+ );
+}
+
+/**
+ * True when the signer has heard nothing, neither an invitation nor any
+ * kind of reminder, for the envelope's reminder interval.
+ */
+export function isAutomaticReminderDue(
+ {
+ intervalDays,
+ lastNotifiedAt,
+ lastNudgedAt,
+ }: {
+ intervalDays: number;
+ lastNotifiedAt: number | null | undefined;
+ lastNudgedAt: number | null | undefined;
+ },
+ nowUnixTimestamp: number,
+): boolean {
+ const lastContactAt = Math.max(lastNotifiedAt ?? 0, lastNudgedAt ?? 0);
+
+ // Never contacted means there is no invitation to follow up on.
+ if (lastContactAt === 0) {
+ return false;
+ }
+
+ return (
+ getAutomaticReminderDueAt(lastContactAt, intervalDays) <= nowUnixTimestamp
+ );
+}
+
export function formatReminderAvailableAt(unixTimestamp: number): string {
return reminderAvailabilityFormatter.format(new Date(unixTimestamp * 1000));
}
diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.ts
index ab26cf0..29ef732 100644
--- a/src/lib/types/domain.ts
+++ b/src/lib/types/domain.ts
@@ -9,6 +9,14 @@ export const ENVELOPE_DEADLINE_DAY_OPTIONS = [3, 7, 14, 30, 60, 90] as const;
export const DEFAULT_ENVELOPE_DEADLINE_DAYS = 30;
export const MAX_ENVELOPE_DEADLINE_DAYS = 365;
+/**
+ * Automatic reminders: how many days apart the send step offers, the limit,
+ * and what a new envelope starts with (null is off).
+ */
+export const ENVELOPE_REMINDER_DAY_OPTIONS = [1, 2, 3, 7] as const;
+export const MAX_ENVELOPE_REMINDER_DAYS = 30;
+export const DEFAULT_ENVELOPE_REMINDER_DAYS: number | null = null;
+
export const envelopeStatuses = [
"draft",
"sent",
@@ -49,6 +57,7 @@ export const auditEventTypes = [
"voided",
"deadline_changed",
"expired",
+ "reminded_auto",
] as const;
export const auditActorTypes = ["sender", "signer", "system"] as const;
@@ -63,6 +72,7 @@ export const emailTemplateKinds = [
"signing_code",
"change_email_confirmation",
"manual_nudge",
+ "automatic_reminder",
"completion_notification",
"download_links",
"decline_notification",