Skip to content

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

TypeScript

Keep retention working before the migration; skip stale deletion emails

Claude5c49650ed464
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.ts
index 896760c..fface8a 100644
--- a/src/lib/envelope-deletion.dbtest.ts
+++ b/src/lib/envelope-deletion.dbtest.ts
@@ -682,6 +682,78 @@ test("a cancellation while the notice is going out still reaches the sender", as
assert.equal(await envelopeExists(envelope.envelopeId), true);
});
+test("a cancellation email still owed is not sent once the deletion is scheduled again", async () => {
+ sent = [];
+ const admin = await createUser("admin");
+ const first = { owner: await createUser("user") };
+ const second = { owner: await createUser("user") };
+ const firstEnvelope = await createEnvelope(first.owner.userId, {
+ status: "completed",
+ });
+ const secondEnvelope = await createEnvelope(second.owner.userId, {
+ status: "completed",
+ });
+ // Long ago, so the daily run reaches these two before anything else.
+ const start = 1_000_000_000;
+
+ // The first sender is still owed their notice.
+ await quietly(() =>
+ scheduleAs(admin, firstEnvelope.envelopeId, undefined, {
+ emailService: createOutbox(true),
+ now: start,
+ }),
+ );
+ // The second was told, then the cancellation email failed.
+ await scheduleAs(admin, secondEnvelope.envelopeId, undefined, {
+ now: start + 1,
+ });
+ await quietly(() =>
+ cancelAs(admin, secondEnvelope.envelopeId, {
+ emailService: createOutbox(true),
+ now: start + 2,
+ }),
+ );
+
+ // While the daily run sends the first notice, an administrator schedules
+ // the second deletion again, and its sender is told so.
+ const outbox = createOutbox();
+ let rescheduled = false;
+ const reschedulingOutbox: EmailService = {
+ ...outbox,
+ async send(message, options) {
+ if (!rescheduled && message.to === first.owner.email) {
+ rescheduled = true;
+ await scheduleAs(admin, secondEnvelope.envelopeId, "Again.", {
+ now: start + DAY,
+ });
+ }
+
+ return outbox.send(message, options);
+ },
+ };
+
+ await runDaily(start + DAY, reschedulingOutbox);
+
+ assert.equal(rescheduled, true);
+ // The old cancellation never followed the new notice.
+ assert.deepEqual(
+ emailsTo(second.owner.email).map((message) => message.subject),
+ [
+ `"Lease" will be deleted on ${new Date((start + 1 + WAIT) * 1000).toISOString().slice(0, 10)}`,
+ `"Lease" will be deleted on ${new Date((start + DAY + WAIT) * 1000).toISOString().slice(0, 10)}`,
+ ],
+ );
+ assert.equal(
+ (await getScheduledEnvelopeDeletion(secondEnvelope.envelopeId, database))
+ ?.reason,
+ "Again.",
+ );
+
+ // Nor does a later run send it.
+ await runDaily(start + 2 * DAY);
+ assert.equal(emailsTo(second.owner.email).length, 2);
+});
+
test("a cancelled deletion can be scheduled again", async () => {
const admin = await createUser("admin");
const envelope = await createEnvelope(admin.userId, { status: "voided" });
diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.ts
index 3b48b37..d64682d 100644
--- a/src/lib/envelope-deletion.ts
+++ b/src/lib/envelope-deletion.ts
@@ -720,6 +720,38 @@ const CANCELLED_KEPT_SECONDS = DAY_IN_SECONDS;
/** After this, a cancellation notice that keeps failing is given up. */
const CANCELLED_GIVE_UP_SECONDS = 30 * DAY_IN_SECONDS;
+/** Whether the notice a row was read as owing is still owed, as it is now. */
+async function isNoticeStillOwed(
+ row: PendingNoticeRow,
+ database: DbExecutor,
+): Promise<boolean> {
+ const result =
+ row.cancelledAt === null
+ ? await database.query(
+ `
+ SELECT 1
+ FROM scheduled_envelope_deletions
+ WHERE envelope_id = $1
+ AND requested_at = $2
+ AND cancelled_at IS NULL
+ AND sender_notified_at IS NULL
+ `,
+ [row.envelopeId, row.requestedAt],
+ )
+ : await database.query(
+ `
+ SELECT 1
+ FROM scheduled_envelope_deletions
+ WHERE envelope_id = $1
+ AND cancelled_at = $2
+ AND cancel_notified_at IS NULL
+ `,
+ [row.envelopeId, row.cancelledAt],
+ );
+
+ return result.rowCount === 1;
+}
+
/**
* The daily part: emails any sender still owed a notice of a deletion or of
* its cancellation, clears cancelled requests nobody is owed anything for,
@@ -775,6 +807,12 @@ export async function runScheduledEnvelopeDeletions({
for (const row of owed) {
try {
+ // The list was read before any of it was sent: a request rescheduled
+ // or cancelled since then is owed something else, or nothing.
+ if (!(await isNoticeStillOwed(row, database))) {
+ continue;
+ }
+
service ??= createEmailService();
if (row.cancelledAt === null) {
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index 549e992..109904f 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -733,6 +733,16 @@ type FinishedEnvelopeRow = EnvelopeArtifactRow & {
title: string;
};
+async function hasScheduledDeletionsTable(
+ database: DbExecutor,
+): Promise<boolean> {
+ const result = await database.query<{ present: boolean }>(
+ `SELECT to_regclass('scheduled_envelope_deletions') IS NOT NULL AS present`,
+ );
+
+ return result.rows[0]?.present === true;
+}
+
/**
* Finished envelopes there is something to do with now: not yet warned and
* inside the warning window, or warned long enough ago and past the period.
@@ -747,6 +757,17 @@ async function listFinishedEnvelopesToHandle(
}: { deleteBefore: number; warnBefore: number; warnedBefore: number },
database: DbExecutor,
): Promise<FinishedEnvelopeRow[]> {
+ // An administrator's scheduled deletion has its own notice and wait,
+ // which this timer must not cut short. A database the new migration has
+ // not reached yet has no such deletions, and its retention keeps working.
+ const scheduledDeletionClause = (await hasScheduledDeletionsTable(database))
+ ? `AND NOT EXISTS (
+ SELECT 1
+ FROM scheduled_envelope_deletions s
+ WHERE s.envelope_id = e.id AND s.cancelled_at IS NULL
+ )`
+ : "";
+
return queryMany<FinishedEnvelopeRow>(
database,
`
@@ -769,13 +790,7 @@ async function listFinishedEnvelopesToHandle(
-- Part 11 records are kept for as long as the rules that apply to
-- them say, never by this timer.
AND NOT e.part11
- -- An administrator's scheduled deletion has its own notice and
- -- wait, which this timer must not cut short.
- AND NOT EXISTS (
- SELECT 1
- FROM scheduled_envelope_deletions s
- WHERE s.envelope_id = e.id AND s.cancelled_at IS NULL
- )
+ ${scheduledDeletionClause}
AND (
(
e.retention_warned_at IS NULL
diff --git a/src/lib/signature-evidence.dbtest.ts b/src/lib/signature-evidence.dbtest.ts
index 9f7b12b..6d80fb3 100644
--- a/src/lib/signature-evidence.dbtest.ts
+++ b/src/lib/signature-evidence.dbtest.ts
@@ -382,3 +382,52 @@ test("the retention period leaves an envelope alone while its scheduled deletion
});
assert.equal(await envelopeOwner(record), null);
});
+
+test("retention keeps working on a database the scheduled-deletion migration has not reached", async () => {
+ const owner = await createUser();
+ const now = 2_000_000_000;
+ const day = 24 * 60 * 60;
+ const record = await createEnvelope(
+ owner,
+ "completed",
+ now - 400 * day,
+ );
+ const emailService = {
+ send: async (message: { to: string }) => ({
+ accepted: [message.to],
+ rejected: [],
+ }),
+ sendBatch: async () => [],
+ } as unknown as EmailService;
+
+ await database.query(
+ `update envelopes set retention_warned_at = $1 where id = $2`,
+ [now - 60 * day, record],
+ );
+ await database.query(
+ `insert into app_settings (id, signup_mode, retention_days, created_at, updated_at)
+ values (true, 'closed', 30, 1, 1)
+ on conflict (id) do update set retention_days = 30`,
+ );
+ // As a preview sharing the production database sees it before the
+ // migration runs: no scheduled deletions table.
+ await database.query(
+ `alter table scheduled_envelope_deletions rename to scheduled_envelope_deletions_hidden`,
+ );
+
+ try {
+ await runRetentionSweep({
+ database,
+ emailService,
+ now,
+ storageService: storage(),
+ });
+ } finally {
+ await database.query(
+ `alter table scheduled_envelope_deletions_hidden rename to scheduled_envelope_deletions`,
+ );
+ }
+
+ assert.equal(await envelopeOwner(record), null);
+});