feat(admin): per-port email/Documenso/branding/reminder settings + invitations
All checks were successful
Build & Push Docker Images / lint (pull_request) Successful in 1m1s
Build & Push Docker Images / build-and-push (pull_request) Has been skipped

Centralizes everything operators need to configure into the admin panel,
each setting per-port with env fallback.

New admin pages
- /admin              landing page linking to every admin section as a card
- /admin/email        FROM name+address, reply-to, signature/footer HTML,
                      optional SMTP host/port/user/pass override
- /admin/documenso    API URL+key override, EOI Documenso template ID,
                      default EOI pathway (documenso-template vs inapp),
                      "Test connection" button
- /admin/branding     logo URL, primary color, app name, email
                      header/footer HTML
- /admin/reminders    port-level defaults for new interests +
                      port-wide daily-digest delivery window
- /admin/invitations  send / list / resend / revoke CRM invitations

Per-user reminder digest
- /notifications/preferences gains a Reminder digest card:
  immediate / daily / weekly / off, with HH:MM, day-of-week,
  IANA timezone fields. Stored in user_profiles.preferences.reminders.

Plumbing
- port-config.ts typed accessors (getPortEmailConfig, getPortDocumensoConfig,
  getPortBrandingConfig, getPortReminderConfig) — settings → env fallback.
- sendEmail accepts optional portId; resolves From/SMTP from settings
  when supplied.
- documensoFetch + downloadSignedPdf accept optional portId; each public
  function takes it through. checkDocumensoHealth() backs the test button.
- crm-invite.service gains listCrmInvites / revokeCrmInvite / resendCrmInvite
  with audit-log entries (revoke_invite, resend_invite added to AuditAction).
- AdminLandingPage card grid + shared SettingsFormCard component to remove
  per-page form boilerplate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-04-27 23:21:54 +02:00
parent f2c57c513e
commit 4877b97f27
22 changed files with 1937 additions and 43 deletions

View File

@@ -1,7 +1,8 @@
import { and, eq, gt, isNull } from 'drizzle-orm';
import { and, desc, eq, gt, isNull } from 'drizzle-orm';
import postgres from 'postgres';
import { auth } from '@/lib/auth';
import { createAuditLog } from '@/lib/audit';
import { db } from '@/lib/db';
import { crmUserInvites } from '@/lib/db/schema/crm-invites';
import { userProfiles } from '@/lib/db/schema/users';
@@ -11,6 +12,13 @@ import { crmInviteEmail } from '@/lib/email/templates/crm-invite';
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
import { hashToken, mintToken } from '@/lib/portal/passwords';
interface AuditMeta {
userId: string;
portId: string;
ipAddress: string;
userAgent: string;
}
const INVITE_TTL_HOURS = 72;
const MIN_PASSWORD_LENGTH = 9;
@@ -116,3 +124,111 @@ export async function consumeCrmInvite(args: {
return { userId, email: invite.email };
}
// ─── Admin operations ────────────────────────────────────────────────────────
export interface InviteRow {
id: string;
email: string;
name: string | null;
isSuperAdmin: boolean;
expiresAt: Date;
usedAt: Date | null;
createdAt: Date;
status: 'pending' | 'accepted' | 'expired';
}
export async function listCrmInvites(): Promise<InviteRow[]> {
const rows = await db
.select({
id: crmUserInvites.id,
email: crmUserInvites.email,
name: crmUserInvites.name,
isSuperAdmin: crmUserInvites.isSuperAdmin,
expiresAt: crmUserInvites.expiresAt,
usedAt: crmUserInvites.usedAt,
createdAt: crmUserInvites.createdAt,
})
.from(crmUserInvites)
.orderBy(desc(crmUserInvites.createdAt))
.limit(200);
const now = Date.now();
return rows.map((r) => {
let status: InviteRow['status'];
if (r.usedAt) status = 'accepted';
else if (r.expiresAt.getTime() < now) status = 'expired';
else status = 'pending';
return { ...r, status };
});
}
export async function revokeCrmInvite(inviteId: string, meta: AuditMeta): Promise<void> {
const invite = await db.query.crmUserInvites.findFirst({
where: eq(crmUserInvites.id, inviteId),
});
if (!invite) throw new NotFoundError('Invite');
if (invite.usedAt) throw new ConflictError('Invite already accepted — cannot revoke');
// Force expiration; tokenHash stays in place so any in-flight click fails
// the `expiresAt > now` check at consume time.
await db
.update(crmUserInvites)
.set({ expiresAt: new Date(0) })
.where(eq(crmUserInvites.id, inviteId));
void createAuditLog({
userId: meta.userId,
portId: meta.portId,
action: 'revoke_invite',
entityType: 'crm_invite',
entityId: inviteId,
metadata: { email: invite.email },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
}
export async function resendCrmInvite(
inviteId: string,
meta: AuditMeta,
): Promise<{ link: string }> {
const invite = await db.query.crmUserInvites.findFirst({
where: eq(crmUserInvites.id, inviteId),
});
if (!invite) throw new NotFoundError('Invite');
if (invite.usedAt) throw new ConflictError('Invite already accepted — nothing to resend');
// Mint a fresh token + push expiry forward so the resent link is the only
// working one. The old token hash is overwritten so prior emails become
// dead links.
const { raw, hash } = mintToken();
const expiresAt = new Date(Date.now() + INVITE_TTL_HOURS * 3600 * 1000);
await db
.update(crmUserInvites)
.set({ tokenHash: hash, expiresAt })
.where(eq(crmUserInvites.id, inviteId));
const link = `${env.APP_URL}/set-password?token=${raw}`;
const { subject, html, text } = crmInviteEmail({
link,
ttlHours: INVITE_TTL_HOURS,
recipientName: invite.name ?? undefined,
isSuperAdmin: invite.isSuperAdmin,
});
await sendEmail(invite.email, subject, html, undefined, text);
void createAuditLog({
userId: meta.userId,
portId: meta.portId,
action: 'resend_invite',
entityType: 'crm_invite',
entityId: inviteId,
metadata: { email: invite.email },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
return { link };
}

View File

@@ -1,14 +1,28 @@
import { env } from '@/lib/env';
import { logger } from '@/lib/logger';
import { getPortDocumensoConfig } from '@/lib/services/port-config';
const BASE_URL = env.DOCUMENSO_API_URL;
const API_KEY = env.DOCUMENSO_API_KEY;
interface DocumensoCreds {
baseUrl: string;
apiKey: string;
}
async function documensoFetch(path: string, options?: RequestInit): Promise<unknown> {
const res = await fetch(`${BASE_URL}${path}`, {
async function resolveCreds(portId?: string): Promise<DocumensoCreds> {
if (!portId) return { baseUrl: env.DOCUMENSO_API_URL, apiKey: env.DOCUMENSO_API_KEY };
const cfg = await getPortDocumensoConfig(portId);
return { baseUrl: cfg.apiUrl, apiKey: cfg.apiKey };
}
async function documensoFetch(
path: string,
options?: RequestInit,
portId?: string,
): Promise<unknown> {
const { baseUrl, apiKey } = await resolveCreds(portId);
const res = await fetch(`${baseUrl}${path}`, {
...options,
headers: {
Authorization: `Bearer ${API_KEY}`,
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
...options?.headers,
},
@@ -16,7 +30,7 @@ async function documensoFetch(path: string, options?: RequestInit): Promise<unkn
if (!res.ok) {
const err = await res.text();
logger.error({ path, status: res.status, err }, 'Documenso API error');
logger.error({ path, status: res.status, err, portId }, 'Documenso API error');
throw new Error(`Documenso API error: ${res.status}`);
}
@@ -70,50 +84,88 @@ export async function createDocument(
title: string,
pdfBase64: string,
recipients: DocumensoRecipient[],
portId?: string,
): Promise<DocumensoDocument> {
return documensoFetch('/api/v1/documents', {
method: 'POST',
body: JSON.stringify({ title, document: pdfBase64, recipients }),
}).then(normalizeDocument);
return documensoFetch(
'/api/v1/documents',
{
method: 'POST',
body: JSON.stringify({ title, document: pdfBase64, recipients }),
},
portId,
).then(normalizeDocument);
}
export async function generateDocumentFromTemplate(
templateId: number,
payload: Record<string, unknown>,
portId?: string,
): Promise<DocumensoDocument> {
return documensoFetch(`/api/v1/templates/${templateId}/generate-document`, {
method: 'POST',
body: JSON.stringify(payload),
}).then(normalizeDocument);
return documensoFetch(
`/api/v1/templates/${templateId}/generate-document`,
{
method: 'POST',
body: JSON.stringify(payload),
},
portId,
).then(normalizeDocument);
}
export async function sendDocument(docId: string): Promise<DocumensoDocument> {
return documensoFetch(`/api/v1/documents/${docId}/send`, {
method: 'POST',
}).then(normalizeDocument);
export async function sendDocument(docId: string, portId?: string): Promise<DocumensoDocument> {
return documensoFetch(
`/api/v1/documents/${docId}/send`,
{
method: 'POST',
},
portId,
).then(normalizeDocument);
}
export async function getDocument(docId: string): Promise<DocumensoDocument> {
return documensoFetch(`/api/v1/documents/${docId}`).then(normalizeDocument);
export async function getDocument(docId: string, portId?: string): Promise<DocumensoDocument> {
return documensoFetch(`/api/v1/documents/${docId}`, undefined, portId).then(normalizeDocument);
}
export async function sendReminder(docId: string, signerId: string): Promise<void> {
await documensoFetch(`/api/v1/documents/${docId}/recipients/${signerId}/remind`, {
method: 'POST',
});
export async function sendReminder(
docId: string,
signerId: string,
portId?: string,
): Promise<void> {
await documensoFetch(
`/api/v1/documents/${docId}/recipients/${signerId}/remind`,
{
method: 'POST',
},
portId,
);
}
export async function downloadSignedPdf(docId: string): Promise<Buffer> {
const res = await fetch(`${BASE_URL}/api/v1/documents/${docId}/download`, {
headers: { Authorization: `Bearer ${API_KEY}` },
export async function downloadSignedPdf(docId: string, portId?: string): Promise<Buffer> {
const { baseUrl, apiKey } = await resolveCreds(portId);
const res = await fetch(`${baseUrl}/api/v1/documents/${docId}/download`, {
headers: { Authorization: `Bearer ${apiKey}` },
});
if (!res.ok) {
const err = await res.text();
logger.error({ docId, status: res.status, err }, 'Documenso download error');
logger.error({ docId, status: res.status, err, portId }, 'Documenso download error');
throw new Error(`Documenso download error: ${res.status}`);
}
const arrayBuffer = await res.arrayBuffer();
return Buffer.from(arrayBuffer);
}
/** Convenience health-check used by the admin "Test connection" button. */
export async function checkDocumensoHealth(
portId?: string,
): Promise<{ ok: boolean; status?: number; error?: string }> {
try {
const { baseUrl, apiKey } = await resolveCreds(portId);
const res = await fetch(`${baseUrl}/api/v1/health`, {
headers: { Authorization: `Bearer ${apiKey}` },
});
return { ok: res.ok, status: res.status };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : 'Unknown error' };
}
}

View File

@@ -0,0 +1,217 @@
/**
* Typed accessors for port-level configuration with env-fallback.
*
* Settings are stored in the `system_settings` table keyed by (key, portId).
* The functions in this module resolve a port's effective configuration for
* a given domain (email, Documenso, branding, reminders) by reading the
* port-scoped row first, falling back to the global row, and finally to the
* env var when neither is set.
*/
import { env } from '@/lib/env';
import { getSetting } from '@/lib/services/settings.service';
// ─── Setting key constants ───────────────────────────────────────────────────
export const SETTING_KEYS = {
// Email
emailFromName: 'email_from_name',
emailFromAddress: 'email_from_address',
emailReplyTo: 'email_reply_to',
emailSignatureHtml: 'email_signature_html',
emailFooterHtml: 'email_footer_html',
smtpHostOverride: 'smtp_host_override',
smtpPortOverride: 'smtp_port_override',
smtpUserOverride: 'smtp_user_override',
smtpPassOverride: 'smtp_pass_override',
// Documenso / EOI
documensoApiUrlOverride: 'documenso_api_url_override',
documensoApiKeyOverride: 'documenso_api_key_override',
documensoEoiTemplateId: 'documenso_eoi_template_id',
eoiDefaultPathway: 'eoi_default_pathway',
// Branding
brandingLogoUrl: 'branding_logo_url',
brandingPrimaryColor: 'branding_primary_color',
brandingAppName: 'branding_app_name',
brandingEmailHeaderHtml: 'branding_email_header_html',
brandingEmailFooterHtml: 'branding_email_footer_html',
// Reminders (port-level defaults)
reminderDefaultDays: 'reminder_default_days',
reminderDefaultEnabled: 'reminder_default_enabled',
reminderDigestEnabled: 'reminder_digest_enabled',
reminderDigestTime: 'reminder_digest_time',
reminderDigestTimezone: 'reminder_digest_timezone',
} as const;
// ─── Helper ──────────────────────────────────────────────────────────────────
async function readSetting<T>(key: string, portId: string): Promise<T | null> {
const setting = await getSetting(key, portId);
if (!setting) return null;
return setting.value as T;
}
// ─── Email ──────────────────────────────────────────────────────────────────
export interface PortEmailConfig {
fromName: string;
fromAddress: string;
replyTo: string | null;
signatureHtml: string | null;
footerHtml: string | null;
smtpHost: string;
smtpPort: number;
smtpUser: string | null;
smtpPass: string | null;
}
export async function getPortEmailConfig(portId: string): Promise<PortEmailConfig> {
const [
fromName,
fromAddress,
replyTo,
signatureHtml,
footerHtml,
smtpHost,
smtpPort,
smtpUser,
smtpPass,
] = await Promise.all([
readSetting<string>(SETTING_KEYS.emailFromName, portId),
readSetting<string>(SETTING_KEYS.emailFromAddress, portId),
readSetting<string>(SETTING_KEYS.emailReplyTo, portId),
readSetting<string>(SETTING_KEYS.emailSignatureHtml, portId),
readSetting<string>(SETTING_KEYS.emailFooterHtml, portId),
readSetting<string>(SETTING_KEYS.smtpHostOverride, portId),
readSetting<number>(SETTING_KEYS.smtpPortOverride, portId),
readSetting<string>(SETTING_KEYS.smtpUserOverride, portId),
readSetting<string>(SETTING_KEYS.smtpPassOverride, portId),
]);
// Parse env.SMTP_FROM into name + address if no port override
let envFromName = 'Port Nimara CRM';
let envFromAddress = `noreply@${env.SMTP_HOST}`;
if (env.SMTP_FROM) {
const match = env.SMTP_FROM.match(/^(.+?)\s*<(.+)>$/);
if (match) {
envFromName = match[1]!.trim();
envFromAddress = match[2]!.trim();
} else {
envFromAddress = env.SMTP_FROM;
}
}
return {
fromName: fromName ?? envFromName,
fromAddress: fromAddress ?? envFromAddress,
replyTo: replyTo ?? null,
signatureHtml: signatureHtml ?? null,
footerHtml: footerHtml ?? null,
smtpHost: smtpHost ?? env.SMTP_HOST,
smtpPort: smtpPort ?? env.SMTP_PORT,
smtpUser: smtpUser ?? env.SMTP_USER ?? null,
smtpPass: smtpPass ?? env.SMTP_PASS ?? null,
};
}
// ─── Documenso ──────────────────────────────────────────────────────────────
export type EoiPathway = 'documenso-template' | 'inapp';
export interface PortDocumensoConfig {
apiUrl: string;
apiKey: string;
eoiTemplateId: string | null;
defaultPathway: EoiPathway;
}
export async function getPortDocumensoConfig(portId: string): Promise<PortDocumensoConfig> {
const [apiUrl, apiKey, eoiTemplateId, defaultPathway] = await Promise.all([
readSetting<string>(SETTING_KEYS.documensoApiUrlOverride, portId),
readSetting<string>(SETTING_KEYS.documensoApiKeyOverride, portId),
readSetting<string>(SETTING_KEYS.documensoEoiTemplateId, portId),
readSetting<EoiPathway>(SETTING_KEYS.eoiDefaultPathway, portId),
]);
return {
apiUrl: apiUrl ?? env.DOCUMENSO_API_URL,
apiKey: apiKey ?? env.DOCUMENSO_API_KEY,
eoiTemplateId: eoiTemplateId ?? null,
defaultPathway: defaultPathway ?? 'documenso-template',
};
}
// ─── Branding ───────────────────────────────────────────────────────────────
export interface PortBrandingConfig {
logoUrl: string | null;
primaryColor: string;
appName: string;
emailHeaderHtml: string | null;
emailFooterHtml: string | null;
}
const DEFAULT_BRANDING: PortBrandingConfig = {
logoUrl: null,
primaryColor: '#1e293b',
appName: 'Port Nimara CRM',
emailHeaderHtml: null,
emailFooterHtml: null,
};
export async function getPortBrandingConfig(portId: string): Promise<PortBrandingConfig> {
const [logoUrl, primaryColor, appName, emailHeaderHtml, emailFooterHtml] = await Promise.all([
readSetting<string>(SETTING_KEYS.brandingLogoUrl, portId),
readSetting<string>(SETTING_KEYS.brandingPrimaryColor, portId),
readSetting<string>(SETTING_KEYS.brandingAppName, portId),
readSetting<string>(SETTING_KEYS.brandingEmailHeaderHtml, portId),
readSetting<string>(SETTING_KEYS.brandingEmailFooterHtml, portId),
]);
return {
logoUrl: logoUrl ?? DEFAULT_BRANDING.logoUrl,
primaryColor: primaryColor ?? DEFAULT_BRANDING.primaryColor,
appName: appName ?? DEFAULT_BRANDING.appName,
emailHeaderHtml: emailHeaderHtml ?? DEFAULT_BRANDING.emailHeaderHtml,
emailFooterHtml: emailFooterHtml ?? DEFAULT_BRANDING.emailFooterHtml,
};
}
// ─── Reminders ──────────────────────────────────────────────────────────────
export interface PortReminderConfig {
defaultDays: number;
defaultEnabled: boolean;
digestEnabled: boolean;
digestTime: string; // 'HH:MM'
digestTimezone: string;
}
const DEFAULT_REMINDER: PortReminderConfig = {
defaultDays: 7,
defaultEnabled: false,
digestEnabled: false,
digestTime: '09:00',
digestTimezone: 'Europe/Warsaw',
};
export async function getPortReminderConfig(portId: string): Promise<PortReminderConfig> {
const [defaultDays, defaultEnabled, digestEnabled, digestTime, digestTimezone] =
await Promise.all([
readSetting<number>(SETTING_KEYS.reminderDefaultDays, portId),
readSetting<boolean>(SETTING_KEYS.reminderDefaultEnabled, portId),
readSetting<boolean>(SETTING_KEYS.reminderDigestEnabled, portId),
readSetting<string>(SETTING_KEYS.reminderDigestTime, portId),
readSetting<string>(SETTING_KEYS.reminderDigestTimezone, portId),
]);
return {
defaultDays: defaultDays ?? DEFAULT_REMINDER.defaultDays,
defaultEnabled: defaultEnabled ?? DEFAULT_REMINDER.defaultEnabled,
digestEnabled: digestEnabled ?? DEFAULT_REMINDER.digestEnabled,
digestTime: digestTime ?? DEFAULT_REMINDER.digestTime,
digestTimezone: digestTimezone ?? DEFAULT_REMINDER.digestTimezone,
};
}