fix(audit): comprehensive 2026-05-15 audit fix wave + Documenso v2 polish
Bundles the prior session's 50-task fix sweep (Documenso v2 + EOI/signing-
progress redesign + env-to-admin migration + dev-mode banner) with the
2026-05-18 audit fix wave (3 CRITICAL, 14 HIGH, 28 MEDIUM, 6 LOW).
CRITICAL (3):
- C-01 interest-berths INNER JOIN -> LEFT JOIN so hard-deleted berths
no longer silently drop interest links
- C-02 /setup added to PUBLIC_PATHS; fresh-deploy bootstrap loop fixed
- C-03 generic PATCH /interests/[id] no longer accepts pipelineStage —
callers must go through /stage with the override-guard chain
HIGH (14/15):
- H-01 explicit ON DELETE on previously-implicit NO ACTION FKs across
interests/documents/reservations/reminders/invoices (migration 0070)
- H-02 login page reads ?redirect= param with same-origin guard
- H-03 CRM invite token moves to URL fragment so it never lands in
nginx access logs / Referer headers
- H-04 Retry-After header on sign-in-by-identifier 429 (RFC 6585 §4)
- H-05 toggleAccount writes an audit row
- H-06 upsertSetting masks any value whose key ends with _encrypted
- H-07 archiveClient cascade fires per-interest audit rows
- H-08 createSalesTransporter applies SMTP_TIMEOUTS
- H-09 AppShell stable children — viewport flip across breakpoint no
longer destroys in-progress form drafts
- H-10 portal documents page swaps Unicode glyph status icons for
Lucide CheckCircle2/XCircle/Circle + aria-labels
- H-12 list components swap alert(...) for toast.warning(...)
- H-13 5 icon-only buttons gain aria-label
- H-14 parseBody treats empty bodies as {}
- H-15 admin layout renders a 403 panel instead of silent bounce
- H-11 not applicable — mobile-search-overlay IS a mobile bottom-sheet
MEDIUM (28+):
- M-MT01-05 defense-in-depth port_id/parent-id filters on UPDATE/DELETE
WHEREs across custom-fields, notes (all 6 entity types x update +
delete), client-contacts, yacht ownerClient lookup, webhook reads
- M-D01 documents-hub realtime event-name typo (file:created -> uploaded)
- M-EM01 portal-auth emails thread through portId
- M-EM02 sendEmail accepts cc/bcc params
- M-EM04 notification_digest catalog key
- M-IN01 portal presigned download URLs use 4h TTL
- M-IN02 OpenAI client lazy-instantiated
- M-IN04 stale pdfme refs updated to pdf-lib AcroForm
- M-IN05 umami.testConnection returns tagged union
- M-L01 reservations tenure_type unified with berths
- M-L02 report-generators canonicalize stage values
- M-AU01 audit log placeholder copy fixed
- M-AU04 outcome_set / outcome_cleared distinct audit verbs
- M-NEW-2 activity feed entity name+type separator
- M-R01 portal allowlist narrowed + portal_session backstop in proxy
- M-SC02 companies archived partial index
- M-SC04 audit_logs.searchText documented as DB-managed
- M-S01 storage_s3_access_key_encrypted admin field
- M-U01 audit log empty state uses <EmptyState>
- M-U09 invoice delete dialog -> <AlertDialog>
- M-U10 toast.success on ClientForm + InterestForm create/edit
- M-U11 settings-form-card logo preview alt text
- M-U14 mobile topbar title on clients/yachts/interests/berths
- M-U15 Invoices in mobile More-sheet
LOW (6/8):
- L-AU01 severity defaults for security-relevant verbs
- L-AU02 +13 missing actions in admin audit filter
- L-AU03 +7 missing entity types in admin audit filter
- L-AU04 dead listAuditLogs stubbed
- L-D02 CLAUDE.md Owner-wins chain tightened
Bonus — Document detail polish (#67 partial, 3/6 deliverables):
- state-aware action button per signer
- watcher Add UI with display-name resolution
- cleanSignerName cleanup
Prior session work bundled in:
- Documenso v2 webhook + envelope-ID normalization + sequential signing
- SigningProgress UI redesign (avatars, per-signer state, timestamps)
- env->admin settings registry + RegistryDrivenForm + encrypted creds
- Embedded-signing card + Test connection + setup help
- Dev-mode EMAIL_REDIRECT_TO banner
- Pipeline rules admin page
- Sales email config card
- Audit log details Sheet
- EOI tab: Finalising badge, absolute timestamps, sequential indicator
- Notes pipeline_stage_at_creation (migration 0069)
- Documenso numeric ID dual-key webhook (migration 0068)
- Dimensions criterion copy (migration 0067)
Tests: 1374/1374 vitest pass. tsc clean. lint clean.
See docs/AUDIT-FIX-WAVE-2026-05-18.md for the full progress report and
the user-input items still pending.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { and, desc, eq, gte, inArray, isNull, lt, lte, ne, sql, exists } from 'drizzle-orm';
|
||||
import { and, desc, eq, gte, inArray, isNull, lt, lte, ne, or, sql, exists } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import {
|
||||
@@ -26,7 +26,7 @@ import { env } from '@/lib/env';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { evaluateRule } from '@/lib/services/berth-rules-engine';
|
||||
import { PIPELINE_STAGES } from '@/lib/constants';
|
||||
import { advanceStageIfBehind } from '@/lib/services/interests.service';
|
||||
import { advanceStageIfBehind, advanceStageIfBehindGated } from '@/lib/services/interests.service';
|
||||
import {
|
||||
createDocument as documensoCreate,
|
||||
sendDocument as documensoSend,
|
||||
@@ -184,7 +184,14 @@ export async function listDocuments(
|
||||
if (interestId) filters.push(eq(documents.interestId, interestId));
|
||||
if (clientId) filters.push(eq(documents.clientId, clientId));
|
||||
if (documentType) filters.push(eq(documents.documentType, documentType));
|
||||
if (status) filters.push(eq(documents.status, status));
|
||||
if (status) {
|
||||
filters.push(eq(documents.status, status));
|
||||
} else {
|
||||
// Hide soft-deleted rows by default from the standard list endpoint.
|
||||
// Callers that explicitly want the deleted bucket pass `status='deleted'`
|
||||
// (e.g. the "Deleted" filter chip on the EOI history list).
|
||||
filters.push(ne(documents.status, 'deleted'));
|
||||
}
|
||||
if (query.folderId !== undefined) {
|
||||
if (query.folderId === null) {
|
||||
filters.push(isNull(documents.folderId));
|
||||
@@ -603,14 +610,58 @@ export async function updateDocument(
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Soft-deletes a document by setting `status='deleted'`. The row stays so
|
||||
* audit-log/event history references it; the document is hidden from
|
||||
* primary lists via the `status != 'deleted'` filter at the read layer.
|
||||
*
|
||||
* If the document is wired to a Documenso envelope, the call also voids
|
||||
* the envelope upstream (Documenso DELETE = void, not hard-erase; the
|
||||
* envelope moves to VOIDED status in Documenso's UI so it stops
|
||||
* accepting signatures and outstanding signing URLs invalidate).
|
||||
*
|
||||
* Refuses to delete a document in the middle of signing (`sent` /
|
||||
* `partially_signed`) — reps must cancel first, then delete the
|
||||
* cancelled record.
|
||||
*/
|
||||
export async function deleteDocument(id: string, portId: string, meta: AuditMeta) {
|
||||
const existing = await getDocumentById(id, portId);
|
||||
|
||||
if (['sent', 'partially_signed'].includes(existing.status)) {
|
||||
throw new ConflictError('Cannot delete a document that is currently in signing process');
|
||||
throw new ConflictError(
|
||||
'Cannot delete a document while signing is in progress — cancel it first, then delete the cancelled record.',
|
||||
);
|
||||
}
|
||||
if (existing.status === 'deleted') {
|
||||
// Idempotent: a second DELETE is a no-op rather than a 409.
|
||||
return;
|
||||
}
|
||||
|
||||
await db.delete(documents).where(and(eq(documents.id, id), eq(documents.portId, portId)));
|
||||
// Best-effort upstream void. A transient Documenso failure shouldn't
|
||||
// block the CRM-side delete — the document_events row + audit log
|
||||
// capture what happened, and `voidDocument` treats 404 (already gone)
|
||||
// as success so a Documenso UI re-delete remains safe.
|
||||
if (existing.documensoId) {
|
||||
try {
|
||||
await documensoVoid(existing.documensoId, portId);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, documentId: id, documensoId: existing.documensoId },
|
||||
'Documenso void failed during delete; soft-deleting CRM-side anyway',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await db
|
||||
.update(documents)
|
||||
.set({ status: 'deleted', updatedAt: new Date() })
|
||||
.where(and(eq(documents.id, id), eq(documents.portId, portId)));
|
||||
|
||||
await db.insert(documentEvents).values({
|
||||
documentId: id,
|
||||
eventType: 'deleted',
|
||||
eventData: { initiatedBy: meta.userId },
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
@@ -619,6 +670,7 @@ export async function deleteDocument(id: string, portId: string, meta: AuditMeta
|
||||
entityType: 'document',
|
||||
entityId: id,
|
||||
oldValue: { title: existing.title, status: existing.status },
|
||||
newValue: { status: 'deleted' },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
@@ -788,7 +840,14 @@ export async function sendForSigning(documentId: string, portId: string, meta: A
|
||||
// Advance pipeline stage to eoi (no-op if already further along).
|
||||
// Doc sub-status is set by the webhook receiver when Documenso confirms;
|
||||
// we stamp eoiDocStatus optimistically here so the UI shows "sent".
|
||||
void advanceStageIfBehind(interest.id, portId, 'eoi', meta, 'EOI sent for signing');
|
||||
void advanceStageIfBehindGated(
|
||||
interest.id,
|
||||
portId,
|
||||
'eoi',
|
||||
meta,
|
||||
'EOI sent for signing',
|
||||
'eoi_sent',
|
||||
);
|
||||
await db
|
||||
.update(interests)
|
||||
.set({ eoiDocStatus: 'sent', updatedAt: new Date() })
|
||||
@@ -998,9 +1057,19 @@ async function resolveWebhookDocument(
|
||||
documensoId: string,
|
||||
portId: string | undefined,
|
||||
): Promise<typeof documents.$inferSelect | null> {
|
||||
// Documenso v1 sends `payload.id` = the same numeric id we stored in
|
||||
// `documents.documenso_id`. Documenso v2 sends `payload.id` = the
|
||||
// internal numeric pk, while `documents.documenso_id` holds the public
|
||||
// `envelope_xxx` string and the numeric pk lives in
|
||||
// `documents.documenso_numeric_id`. Match either column so both
|
||||
// versions resolve.
|
||||
const idMatch = or(
|
||||
eq(documents.documensoId, documensoId),
|
||||
eq(documents.documensoNumericId, documensoId),
|
||||
);
|
||||
if (portId) {
|
||||
const doc = await db.query.documents.findFirst({
|
||||
where: and(eq(documents.documensoId, documensoId), eq(documents.portId, portId)),
|
||||
where: and(idMatch, eq(documents.portId, portId)),
|
||||
});
|
||||
if (!doc) {
|
||||
logger.warn({ documensoId, portId }, 'Document not found for webhook (port-scoped)');
|
||||
@@ -1009,7 +1078,7 @@ async function resolveWebhookDocument(
|
||||
return doc;
|
||||
}
|
||||
const matches = await db.query.documents.findMany({
|
||||
where: eq(documents.documensoId, documensoId),
|
||||
where: idMatch,
|
||||
});
|
||||
if (matches.length === 0) {
|
||||
logger.warn({ documensoId }, 'Document not found for webhook');
|
||||
@@ -1052,9 +1121,24 @@ export async function handleRecipientSigned(eventData: {
|
||||
eq(documentSigners.signerEmail, eventData.recipientEmail),
|
||||
);
|
||||
|
||||
// Read prior status so we know whether this delivery is the first
|
||||
// signing transition. Documenso v2 retries deliver the same
|
||||
// DOCUMENT_RECIPIENT_COMPLETED multiple times with slightly different
|
||||
// rawBody hashes — without this gate the cascade fires on every
|
||||
// delivery, the "your turn" email goes out twice, and downstream side
|
||||
// effects (rule engine, audit, notifications) duplicate.
|
||||
const [priorSigner] = await db.select().from(documentSigners).where(signerWhere);
|
||||
const wasAlreadySigned = priorSigner?.status === 'signed';
|
||||
|
||||
const [signer] = await db
|
||||
.update(documentSigners)
|
||||
.set({ status: 'signed', signedAt: new Date() })
|
||||
.set({
|
||||
status: 'signed',
|
||||
// Preserve the original signedAt timestamp on duplicate webhook
|
||||
// deliveries — overwriting it makes every signer card show the
|
||||
// most-recent webhook timestamp instead of the actual sign time.
|
||||
...(wasAlreadySigned ? {} : { signedAt: new Date() }),
|
||||
})
|
||||
.where(signerWhere)
|
||||
.returning();
|
||||
|
||||
@@ -1083,13 +1167,21 @@ export async function handleRecipientSigned(eventData: {
|
||||
.where(and(eq(documents.id, doc.id), eq(documents.portId, doc.portId)));
|
||||
}
|
||||
|
||||
await db.insert(documentEvents).values({
|
||||
documentId: doc.id,
|
||||
eventType: 'signed',
|
||||
signerId: signer?.id ?? null,
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { recipientEmail: eventData.recipientEmail },
|
||||
});
|
||||
// Idempotent insert: Documenso v2 retries the same logical event with
|
||||
// varying rawBody hashes, so the (documentId, hash:signed:email) unique
|
||||
// index would otherwise throw on duplicate deliveries and short-circuit
|
||||
// the cascade below. `onConflictDoNothing` treats the duplicate as the
|
||||
// no-op it is.
|
||||
await db
|
||||
.insert(documentEvents)
|
||||
.values({
|
||||
documentId: doc.id,
|
||||
eventType: 'signed',
|
||||
signerId: signer?.id ?? null,
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { recipientEmail: eventData.recipientEmail },
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
|
||||
emitToRoom(`port:${doc.portId}`, 'document:signer:signed', {
|
||||
documentId: doc.id,
|
||||
@@ -1098,9 +1190,10 @@ export async function handleRecipientSigned(eventData: {
|
||||
|
||||
// Phase 2 cascade: now that this signer is done, fire the branded
|
||||
// "your turn" invitation to the next pending signer in signing order.
|
||||
// The webhook may fire multiple times per document (one per recipient
|
||||
// sign event); the `invitedAt` guard prevents duplicate invites.
|
||||
if (signer) {
|
||||
// Skip the cascade entirely on duplicate deliveries — only fire on
|
||||
// the first pending→signed transition. The `invitedAt` guard inside
|
||||
// sendCascadingInviteForNextSigner is a second safety net.
|
||||
if (signer && !wasAlreadySigned) {
|
||||
await sendCascadingInviteForNextSigner(doc).catch((err) => {
|
||||
// Cascading-invite failure is non-fatal — the webhook itself
|
||||
// succeeded. The rep can manually click "Send invitation" if the
|
||||
@@ -1289,7 +1382,13 @@ export async function handleDocumentCompleted(eventData: { documentId: string; p
|
||||
let putStoragePath: string | null = null;
|
||||
|
||||
try {
|
||||
const signedPdfBuffer = await downloadSignedPdf(eventData.documentId);
|
||||
// Download by the stored Documenso ID (envelope_xxx on v2, numeric on
|
||||
// v1) rather than `eventData.documentId` — webhooks deliver the v2
|
||||
// numeric internal pk, but the download endpoint expects the public
|
||||
// envelope_xxx string. Falls back to the webhook's value when the
|
||||
// stored ID is somehow missing (e.g. legacy pre-#69 rows).
|
||||
const downloadId = doc.documensoId ?? eventData.documentId;
|
||||
const signedPdfBuffer = await downloadSignedPdf(downloadId, doc.portId);
|
||||
|
||||
// Guard: a 0-byte response from Documenso would otherwise persist a
|
||||
// permanent corrupt signedFileId pointing at a blob with no content.
|
||||
@@ -1503,13 +1602,18 @@ export async function handleDocumentCompleted(eventData: { documentId: string; p
|
||||
void evaluateRule('eoi_signed', doc.interestId, doc.portId, systemMeta);
|
||||
}
|
||||
|
||||
// Stage stays at 'eoi' — sub-status flips to signed.
|
||||
void advanceStageIfBehind(
|
||||
// EOI signed = formal commitment to proceed → advance to 'reservation'
|
||||
// (the next milestone). Conventional CRM behaviour: stage reflects the
|
||||
// deal's CURRENT pursuit phase, not the most recently signed document.
|
||||
// Per-port admins can override the rule via the `eoi_signed` entry in
|
||||
// the stage_advance_rules setting (auto / suggest / off).
|
||||
void advanceStageIfBehindGated(
|
||||
doc.interestId,
|
||||
doc.portId,
|
||||
'eoi',
|
||||
'reservation',
|
||||
systemMeta,
|
||||
'EOI signed via Documenso',
|
||||
'eoi_signed',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1533,12 +1637,13 @@ export async function handleDocumentCompleted(eventData: { documentId: string; p
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(interests.id, doc.interestId));
|
||||
void advanceStageIfBehind(
|
||||
void advanceStageIfBehindGated(
|
||||
doc.interestId,
|
||||
doc.portId,
|
||||
'reservation',
|
||||
systemMeta,
|
||||
'Reservation agreement signed',
|
||||
'reservation_signed',
|
||||
);
|
||||
void import('@/lib/services/berth-rules-engine').then(({ evaluateRule }) =>
|
||||
evaluateRule('contract_signed', doc.interestId!, doc.portId, systemMeta),
|
||||
@@ -1563,12 +1668,13 @@ export async function handleDocumentCompleted(eventData: { documentId: string; p
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(interests.id, doc.interestId));
|
||||
void advanceStageIfBehind(
|
||||
void advanceStageIfBehindGated(
|
||||
doc.interestId,
|
||||
doc.portId,
|
||||
'contract',
|
||||
systemMeta,
|
||||
'Contract signed via Documenso',
|
||||
'contract_signed',
|
||||
);
|
||||
void import('@/lib/services/berth-rules-engine').then(({ evaluateRule }) =>
|
||||
evaluateRule('contract_signed', doc.interestId!, doc.portId, systemMeta),
|
||||
@@ -1717,13 +1823,16 @@ export async function handleDocumentOpened(eventData: {
|
||||
.where(eq(documentSigners.id, signer.id));
|
||||
}
|
||||
|
||||
await db.insert(documentEvents).values({
|
||||
documentId: doc.id,
|
||||
eventType: 'viewed',
|
||||
signerId: signer?.id ?? null,
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { recipientEmail: eventData.recipientEmail },
|
||||
});
|
||||
await db
|
||||
.insert(documentEvents)
|
||||
.values({
|
||||
documentId: doc.id,
|
||||
eventType: 'viewed',
|
||||
signerId: signer?.id ?? null,
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { recipientEmail: eventData.recipientEmail },
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
|
||||
emitToRoom(`port:${doc.portId}`, 'document:signer:opened', {
|
||||
documentId: doc.id,
|
||||
@@ -1767,13 +1876,16 @@ export async function handleDocumentRejected(eventData: {
|
||||
.where(and(eq(interests.id, doc.interestId), eq(interests.portId, doc.portId)));
|
||||
}
|
||||
|
||||
await db.insert(documentEvents).values({
|
||||
documentId: doc.id,
|
||||
eventType: 'rejected',
|
||||
signerId,
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { recipientEmail: eventData.recipientEmail ?? null },
|
||||
});
|
||||
await db
|
||||
.insert(documentEvents)
|
||||
.values({
|
||||
documentId: doc.id,
|
||||
eventType: 'rejected',
|
||||
signerId,
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { recipientEmail: eventData.recipientEmail ?? null },
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
|
||||
emitToRoom(`port:${doc.portId}`, 'document:rejected', {
|
||||
documentId: doc.id,
|
||||
@@ -1801,12 +1913,15 @@ export async function handleDocumentCancelled(eventData: {
|
||||
.where(and(eq(interests.id, doc.interestId), eq(interests.portId, doc.portId)));
|
||||
}
|
||||
|
||||
await db.insert(documentEvents).values({
|
||||
documentId: doc.id,
|
||||
eventType: 'cancelled',
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { documensoId: eventData.documentId },
|
||||
});
|
||||
await db
|
||||
.insert(documentEvents)
|
||||
.values({
|
||||
documentId: doc.id,
|
||||
eventType: 'cancelled',
|
||||
signatureHash: eventData.signatureHash ?? null,
|
||||
eventData: { documensoId: eventData.documentId },
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
|
||||
emitToRoom(`port:${doc.portId}`, 'document:cancelled', { documentId: doc.id });
|
||||
}
|
||||
@@ -1865,10 +1980,20 @@ export async function getDocumentDetail(id: string, portId: string): Promise<Doc
|
||||
* The actual Documenso void call lands in PR2 (`documenso-client.voidDocument`);
|
||||
* this skeleton updates DB state only.
|
||||
*/
|
||||
export interface CancelDocumentOptions {
|
||||
/** Rep-authored reason inlined into notification emails + audit log. */
|
||||
reason?: string | null;
|
||||
/** Document_signers ids the rep wants to email about the cancellation.
|
||||
* Empty list = silent void (Regenerate flow). Each id is validated to
|
||||
* belong to this document before any email fires. */
|
||||
notifyRecipients?: string[];
|
||||
}
|
||||
|
||||
export async function cancelDocument(
|
||||
documentId: string,
|
||||
portId: string,
|
||||
meta: AuditMeta,
|
||||
options: CancelDocumentOptions = {},
|
||||
): Promise<typeof documents.$inferSelect> {
|
||||
const existing = await getDocumentById(documentId, portId);
|
||||
|
||||
@@ -1900,7 +2025,11 @@ export async function cancelDocument(
|
||||
await db.insert(documentEvents).values({
|
||||
documentId,
|
||||
eventType: 'cancelled',
|
||||
eventData: { initiatedBy: meta.userId },
|
||||
eventData: {
|
||||
initiatedBy: meta.userId,
|
||||
reason: options.reason ?? null,
|
||||
notifyCount: options.notifyRecipients?.length ?? 0,
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
@@ -1910,13 +2039,58 @@ export async function cancelDocument(
|
||||
entityType: 'document',
|
||||
entityId: documentId,
|
||||
oldValue: { status: existing.status },
|
||||
newValue: { status: 'cancelled' },
|
||||
newValue: { status: 'cancelled', reason: options.reason ?? null },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
|
||||
emitToRoom(`port:${portId}`, 'document:cancelled', { documentId });
|
||||
|
||||
// Notify selected signers (rep-picked subset via the cancel-with-notify
|
||||
// modal). Pull the matching signer rows so we can render the recipient's
|
||||
// canonical name; skip silently when the rep passed no ids (Regenerate
|
||||
// flow). Failure to send is logged + non-fatal — the cancellation has
|
||||
// already committed locally.
|
||||
const notifyIds = options.notifyRecipients ?? [];
|
||||
if (notifyIds.length > 0) {
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: documentSigners.id,
|
||||
signerName: documentSigners.signerName,
|
||||
signerEmail: documentSigners.signerEmail,
|
||||
})
|
||||
.from(documentSigners)
|
||||
.where(
|
||||
and(eq(documentSigners.documentId, documentId), inArray(documentSigners.id, notifyIds)),
|
||||
);
|
||||
if (rows.length > 0) {
|
||||
const portRow = await db.query.ports.findFirst({
|
||||
where: eq(ports.id, portId),
|
||||
columns: { name: true },
|
||||
});
|
||||
const { sendSigningCancelled } =
|
||||
await import('@/lib/services/document-signing-emails.service');
|
||||
await sendSigningCancelled({
|
||||
portId,
|
||||
portName: portRow?.name ?? 'Port Nimara',
|
||||
recipients: rows.map((r) => ({ name: r.signerName, email: r.signerEmail })),
|
||||
documentLabel:
|
||||
(DOC_TYPE_LABEL[existing.documentType] as
|
||||
| 'Expression of Interest'
|
||||
| 'Sales Contract'
|
||||
| 'Reservation Agreement') ?? 'Expression of Interest',
|
||||
reason: options.reason ?? null,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ err, documentId, notifyIds },
|
||||
'cancel-with-notify email fan-out failed; cancellation already committed',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return updated!;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user