feat(emails): sales send-out flows + brochures + email-from settings
Phase 7 of the berth-recommender refactor (plan §3.3, §4.8, §4.9, §5.7,
§5.8, §5.9, §11.1, §14.7, §14.9). Adds the rep-driven send-out path for
per-berth PDFs and port-wide brochures, the per-port sales SMTP/IMAP
config + body templates, and the supporting admin UI.
Migration: 0031_brochures_and_document_sends.sql
Schema additions:
- brochures (port-wide, with isDefault marker + archive)
- brochure_versions (versioned uploads, storageKey per §4.7a)
- document_sends (audit log of every rep-initiated send; failures
captured with failedAt + errorReason). berthPdfVersionId is a plain
text column (no FK) — loose-coupled to Phase 6b's berth_pdf_versions
so the two phases stay independent.
§14.7 critical mitigations:
- Body XSS: rep-authored markdown goes through renderEmailBody()
(HTML-escape first, then a tight allowlist of bold/italic/code/link
rules). https:// + mailto: only — javascript:/data: URLs stripped.
Tested against script/img/iframe/svg/onerror polyglots.
- Recipient typo: strict email regex + two-step confirm modal that
shows the exact recipient before send.
- Unresolved merge fields: pre-send dry-run /preview endpoint blocks
submission until findUnresolvedTokens() returns empty.
- SMTP failure: every transport rejection writes a document_sends row
with failedAt + errorReason; UI surfaces the message.
- Hourly per-user rate limit: 50 sends/user/hour via existing
checkRateLimit().
- Size threshold fallback (§11.1): files above
email_attach_threshold_mb (default 15) ship as a 24h signed-URL
download link in the body instead of an attachment. Storage stream
flows directly to nodemailer to avoid buffering 20MB+.
§14.10 critical mitigation:
- SMTP/IMAP passwords encrypted at rest via the existing
EMAIL_CREDENTIAL_KEY (AES-256-GCM). The /api/v1/admin/email/
sales-config GET endpoint never returns the decrypted value — only
a *PassIsSet boolean. PATCH treats empty string as "leave unchanged"
and explicit null as "clear", so the masked-placeholder UI round-
trips without forcing re-entry on every save.
system_settings keys (per-port unless noted):
- sales_from_address, sales_smtp_{host,port,secure,user,pass_encrypted}
- sales_imap_{host,port,user,pass_encrypted}
- sales_auth_method (default app_password)
- noreply_from_address
- email_template_send_berth_pdf_body, email_template_send_brochure_body
- brochure_max_upload_mb (default 50)
- email_attach_threshold_mb (default 15)
UI surfaces (per §5.7, §5.8, §5.9):
- <SendDocumentDialog> shared 2-step compose+confirm flow.
- <SendBerthPdfDialog>, <SendDocumentsDialog>, <SendFromInterestButton>
wrappers per detail page.
- /[portSlug]/admin/brochures: list, upload (direct-to-storage
presigned PUT for the 20MB+ files per §11.1), default toggle,
archive.
- /[portSlug]/admin/email extended with <SalesEmailConfigCard>:
SMTP + IMAP creds, body templates, threshold/max settings.
Storage: every upload + download goes through getStorageBackend() —
no direct minio imports, per Phase 6a contract.
Tests: 1145 vitest passing (+ 50 new in
markdown-email-sanitization.test.ts, document-sends-validators.test.ts,
sales-email-config-validators.test.ts).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
59
src/lib/db/migrations/0031_brochures_and_document_sends.sql
Normal file
59
src/lib/db/migrations/0031_brochures_and_document_sends.sql
Normal file
@@ -0,0 +1,59 @@
|
||||
CREATE TABLE "brochure_versions" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"brochure_id" text NOT NULL,
|
||||
"version_number" integer NOT NULL,
|
||||
"storage_key" text NOT NULL,
|
||||
"file_name" text NOT NULL,
|
||||
"file_size_bytes" integer NOT NULL,
|
||||
"content_sha256" text NOT NULL,
|
||||
"uploaded_by" text NOT NULL,
|
||||
"uploaded_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"download_url_expires_at" timestamp with time zone
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "brochures" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"port_id" text NOT NULL,
|
||||
"label" text NOT NULL,
|
||||
"description" text,
|
||||
"is_default" boolean DEFAULT false NOT NULL,
|
||||
"archived_at" timestamp with time zone,
|
||||
"created_by" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "document_sends" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"port_id" text NOT NULL,
|
||||
"client_id" text,
|
||||
"interest_id" text,
|
||||
"recipient_email" text NOT NULL,
|
||||
"document_kind" text NOT NULL,
|
||||
"berth_id" text,
|
||||
"berth_pdf_version_id" text,
|
||||
"brochure_id" text,
|
||||
"brochure_version_id" text,
|
||||
"body_markdown" text,
|
||||
"sent_by_user_id" text NOT NULL,
|
||||
"from_address" text NOT NULL,
|
||||
"sent_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"message_id" text,
|
||||
"fallback_to_link_reason" text,
|
||||
"failed_at" timestamp with time zone,
|
||||
"error_reason" text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "brochure_versions" ADD CONSTRAINT "brochure_versions_brochure_id_brochures_id_fk" FOREIGN KEY ("brochure_id") REFERENCES "public"."brochures"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "brochures" ADD CONSTRAINT "brochures_port_id_ports_id_fk" FOREIGN KEY ("port_id") REFERENCES "public"."ports"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "document_sends" ADD CONSTRAINT "document_sends_port_id_ports_id_fk" FOREIGN KEY ("port_id") REFERENCES "public"."ports"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "document_sends" ADD CONSTRAINT "document_sends_client_id_clients_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."clients"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "document_sends" ADD CONSTRAINT "document_sends_interest_id_interests_id_fk" FOREIGN KEY ("interest_id") REFERENCES "public"."interests"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "document_sends" ADD CONSTRAINT "document_sends_berth_id_berths_id_fk" FOREIGN KEY ("berth_id") REFERENCES "public"."berths"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "document_sends" ADD CONSTRAINT "document_sends_brochure_id_brochures_id_fk" FOREIGN KEY ("brochure_id") REFERENCES "public"."brochures"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "document_sends" ADD CONSTRAINT "document_sends_brochure_version_id_brochure_versions_id_fk" FOREIGN KEY ("brochure_version_id") REFERENCES "public"."brochure_versions"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "idx_brochure_versions_brochure" ON "brochure_versions" USING btree ("brochure_id","uploaded_at");--> statement-breakpoint
|
||||
CREATE INDEX "idx_brochures_port" ON "brochures" USING btree ("port_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_ds_client" ON "document_sends" USING btree ("client_id","sent_at");--> statement-breakpoint
|
||||
CREATE INDEX "idx_ds_interest" ON "document_sends" USING btree ("interest_id","sent_at");--> statement-breakpoint
|
||||
CREATE INDEX "idx_ds_berth" ON "document_sends" USING btree ("berth_id","sent_at");--> statement-breakpoint
|
||||
CREATE INDEX "idx_ds_port" ON "document_sends" USING btree ("port_id","sent_at");
|
||||
11467
src/lib/db/migrations/meta/0031_snapshot.json
Normal file
11467
src/lib/db/migrations/meta/0031_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -218,6 +218,13 @@
|
||||
"when": 1777944021221,
|
||||
"tag": "0030_berth_pdf_versions",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 31,
|
||||
"version": "7",
|
||||
"when": 1777944191753,
|
||||
"tag": "0031_brochures_and_document_sends",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
127
src/lib/db/schema/brochures.ts
Normal file
127
src/lib/db/schema/brochures.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { pgTable, text, boolean, integer, timestamp, index } from 'drizzle-orm/pg-core';
|
||||
|
||||
import { ports } from './ports';
|
||||
import { clients } from './clients';
|
||||
import { interests } from './interests';
|
||||
import { berths } from './berths';
|
||||
|
||||
/**
|
||||
* Port-wide brochures (Phase 7 — see plan §3.3 / §4.8).
|
||||
*
|
||||
* Each port can have multiple brochures (e.g. "General", "Investor Pack")
|
||||
* with one marked as `isDefault`. Archived brochures stay queryable for
|
||||
* audit purposes but are hidden from the send-out picker.
|
||||
*/
|
||||
export const brochures = pgTable(
|
||||
'brochures',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
portId: text('port_id')
|
||||
.notNull()
|
||||
.references(() => ports.id, { onDelete: 'cascade' }),
|
||||
label: text('label').notNull(),
|
||||
description: text('description'),
|
||||
isDefault: boolean('is_default').notNull().default(false),
|
||||
archivedAt: timestamp('archived_at', { withTimezone: true }),
|
||||
createdBy: text('created_by').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [index('idx_brochures_port').on(table.portId)],
|
||||
);
|
||||
|
||||
/**
|
||||
* Versioned brochure files. Identical lifecycle to `berth_pdf_versions`:
|
||||
* each upload creates a new immutable row with a monotonic version number
|
||||
* per brochure. `storageKey` follows the §4.7a renamed convention.
|
||||
*/
|
||||
export const brochureVersions = pgTable(
|
||||
'brochure_versions',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
brochureId: text('brochure_id')
|
||||
.notNull()
|
||||
.references(() => brochures.id, { onDelete: 'cascade' }),
|
||||
versionNumber: integer('version_number').notNull(),
|
||||
/** Object key in the active storage backend (renamed from `s3_key` per §4.7a). */
|
||||
storageKey: text('storage_key').notNull(),
|
||||
fileName: text('file_name').notNull(),
|
||||
fileSizeBytes: integer('file_size_bytes').notNull(),
|
||||
contentSha256: text('content_sha256').notNull(),
|
||||
uploadedBy: text('uploaded_by').notNull(),
|
||||
uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
/** Cached signed-URL expiry per §11.1 — re-sign only when within 1h of expiry. */
|
||||
downloadUrlExpiresAt: timestamp('download_url_expires_at', { withTimezone: true }),
|
||||
},
|
||||
(table) => [index('idx_brochure_versions_brochure').on(table.brochureId, table.uploadedAt)],
|
||||
);
|
||||
|
||||
/**
|
||||
* Send-out audit log for berth PDFs and brochures (Phase 7 — plan §3.3).
|
||||
*
|
||||
* One row per recipient per send. `documentKind` discriminates between
|
||||
* `'berth_pdf'` and `'brochure'`; the corresponding `*_version_id` column
|
||||
* pins the exact version sent.
|
||||
*
|
||||
* `berthPdfVersionId` is intentionally a plain text column (no FK) — the
|
||||
* referenced table `berth_pdf_versions` is owned by Phase 6b. Loose-coupling
|
||||
* keeps the two phases independent (per Phase 7 task brief).
|
||||
*
|
||||
* `failedAt` and `errorReason` capture send failures (SMTP auth, transport
|
||||
* errors). Failed sends are still written so reps can see "I clicked send
|
||||
* but it didn't go" in the timeline (per §14.7).
|
||||
*/
|
||||
export const documentSends = pgTable(
|
||||
'document_sends',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
portId: text('port_id')
|
||||
.notNull()
|
||||
.references(() => ports.id),
|
||||
/** Either client_id or interest_id is set (or both). */
|
||||
clientId: text('client_id').references(() => clients.id),
|
||||
interestId: text('interest_id').references(() => interests.id),
|
||||
recipientEmail: text('recipient_email').notNull(),
|
||||
/** 'berth_pdf' | 'brochure' */
|
||||
documentKind: text('document_kind').notNull(),
|
||||
berthId: text('berth_id').references(() => berths.id),
|
||||
/** Forward FK ref — berth_pdf_versions defined in Phase 6b. Loose-coupled. */
|
||||
berthPdfVersionId: text('berth_pdf_version_id'),
|
||||
brochureId: text('brochure_id').references(() => brochures.id),
|
||||
brochureVersionId: text('brochure_version_id').references(() => brochureVersions.id),
|
||||
/** Exact body used (after merge-field expansion + sanitization). */
|
||||
bodyMarkdown: text('body_markdown'),
|
||||
sentByUserId: text('sent_by_user_id').notNull(),
|
||||
fromAddress: text('from_address').notNull(),
|
||||
sentAt: timestamp('sent_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
/** SMTP provider message-id for deliverability tracking. */
|
||||
messageId: text('message_id'),
|
||||
/** When the initial send had its attachment dropped because the SMTP server
|
||||
* rejected the size (552 etc.) and the system retried with a download
|
||||
* link, this captures the rejection reason for ops visibility. Null when
|
||||
* the original send went through as-is. */
|
||||
fallbackToLinkReason: text('fallback_to_link_reason'),
|
||||
/** Set when the SMTP send transaction itself failed (auth/transport/etc). */
|
||||
failedAt: timestamp('failed_at', { withTimezone: true }),
|
||||
/** Human-readable failure reason; only meaningful when failedAt is non-null. */
|
||||
errorReason: text('error_reason'),
|
||||
},
|
||||
(t) => [
|
||||
index('idx_ds_client').on(t.clientId, t.sentAt),
|
||||
index('idx_ds_interest').on(t.interestId, t.sentAt),
|
||||
index('idx_ds_berth').on(t.berthId, t.sentAt),
|
||||
index('idx_ds_port').on(t.portId, t.sentAt),
|
||||
],
|
||||
);
|
||||
|
||||
export type Brochure = typeof brochures.$inferSelect;
|
||||
export type NewBrochure = typeof brochures.$inferInsert;
|
||||
export type BrochureVersion = typeof brochureVersions.$inferSelect;
|
||||
export type NewBrochureVersion = typeof brochureVersions.$inferInsert;
|
||||
export type DocumentSend = typeof documentSends.$inferSelect;
|
||||
export type NewDocumentSend = typeof documentSends.$inferInsert;
|
||||
@@ -25,6 +25,9 @@ export * from './reservations';
|
||||
// Documents & Files
|
||||
export * from './documents';
|
||||
|
||||
// Brochures + send-outs (Phase 7)
|
||||
export * from './brochures';
|
||||
|
||||
// Financial
|
||||
export * from './financial';
|
||||
|
||||
|
||||
@@ -58,6 +58,9 @@ import {
|
||||
formSubmissions,
|
||||
} from './documents';
|
||||
|
||||
// Brochures + send-outs (Phase 7)
|
||||
import { brochures, brochureVersions, documentSends } from './brochures';
|
||||
|
||||
// Financial
|
||||
import { expenses, invoices, invoiceLineItems, invoiceExpenses } from './financial';
|
||||
|
||||
@@ -883,3 +886,49 @@ export const residentialInterestsRelations = relations(residentialInterests, ({
|
||||
references: [residentialClients.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
// ─── Brochures + send-outs (Phase 7) ──────────────────────────────────────────
|
||||
|
||||
export const brochuresRelations = relations(brochures, ({ one, many }) => ({
|
||||
port: one(ports, {
|
||||
fields: [brochures.portId],
|
||||
references: [ports.id],
|
||||
}),
|
||||
versions: many(brochureVersions),
|
||||
sends: many(documentSends),
|
||||
}));
|
||||
|
||||
export const brochureVersionsRelations = relations(brochureVersions, ({ one, many }) => ({
|
||||
brochure: one(brochures, {
|
||||
fields: [brochureVersions.brochureId],
|
||||
references: [brochures.id],
|
||||
}),
|
||||
sends: many(documentSends),
|
||||
}));
|
||||
|
||||
export const documentSendsRelations = relations(documentSends, ({ one }) => ({
|
||||
port: one(ports, {
|
||||
fields: [documentSends.portId],
|
||||
references: [ports.id],
|
||||
}),
|
||||
client: one(clients, {
|
||||
fields: [documentSends.clientId],
|
||||
references: [clients.id],
|
||||
}),
|
||||
interest: one(interests, {
|
||||
fields: [documentSends.interestId],
|
||||
references: [interests.id],
|
||||
}),
|
||||
berth: one(berths, {
|
||||
fields: [documentSends.berthId],
|
||||
references: [berths.id],
|
||||
}),
|
||||
brochure: one(brochures, {
|
||||
fields: [documentSends.brochureId],
|
||||
references: [brochures.id],
|
||||
}),
|
||||
brochureVersion: one(brochureVersions, {
|
||||
fields: [documentSends.brochureVersionId],
|
||||
references: [brochureVersions.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user