feat(admin): per-port email/Documenso/branding/reminder settings + invitations
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:
69
src/app/(dashboard)/[portSlug]/admin/branding/page.tsx
Normal file
69
src/app/(dashboard)/[portSlug]/admin/branding/page.tsx
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import {
|
||||||
|
SettingsFormCard,
|
||||||
|
type SettingFieldDef,
|
||||||
|
} from '@/components/admin/shared/settings-form-card';
|
||||||
|
|
||||||
|
const FIELDS: SettingFieldDef[] = [
|
||||||
|
{
|
||||||
|
key: 'branding_app_name',
|
||||||
|
label: 'App name',
|
||||||
|
description: 'Shown in the email subject prefix and the in-app header.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'Port Nimara CRM',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'branding_logo_url',
|
||||||
|
label: 'Logo URL',
|
||||||
|
description:
|
||||||
|
'Public HTTPS URL of the logo used in email headers and the branded auth shell. Recommended size: 240×80 PNG with transparent background.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'https://example.com/logo.png',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'branding_primary_color',
|
||||||
|
label: 'Primary color',
|
||||||
|
description: 'Used for buttons and links in transactional email templates.',
|
||||||
|
type: 'color',
|
||||||
|
defaultValue: '#1e293b',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'branding_email_header_html',
|
||||||
|
label: 'Email header HTML',
|
||||||
|
description: 'Optional HTML rendered above each email body. Leave blank to use the default.',
|
||||||
|
type: 'html',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'branding_email_footer_html',
|
||||||
|
label: 'Email footer HTML',
|
||||||
|
description: 'Optional HTML rendered at the very bottom of each email (above the signature).',
|
||||||
|
type: 'html',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function BrandingSettingsPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">Branding</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Logo, primary color, app name, and email header/footer HTML used by the branded auth shell
|
||||||
|
and outgoing email templates.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<SettingsFormCard
|
||||||
|
title="Identity"
|
||||||
|
description="App name, logo, and primary color."
|
||||||
|
fields={FIELDS.slice(0, 3)}
|
||||||
|
/>
|
||||||
|
<SettingsFormCard
|
||||||
|
title="Email branding"
|
||||||
|
description="HTML fragments rendered around every transactional email."
|
||||||
|
fields={FIELDS.slice(3)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
73
src/app/(dashboard)/[portSlug]/admin/documenso/page.tsx
Normal file
73
src/app/(dashboard)/[portSlug]/admin/documenso/page.tsx
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import {
|
||||||
|
SettingsFormCard,
|
||||||
|
type SettingFieldDef,
|
||||||
|
} from '@/components/admin/shared/settings-form-card';
|
||||||
|
import { DocumensoTestButton } from '@/components/admin/documenso/documenso-test-button';
|
||||||
|
|
||||||
|
const API_FIELDS: SettingFieldDef[] = [
|
||||||
|
{
|
||||||
|
key: 'documenso_api_url_override',
|
||||||
|
label: 'API URL override',
|
||||||
|
description: 'Optional. Falls back to DOCUMENSO_API_URL env when blank.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'https://documenso.example.com',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'documenso_api_key_override',
|
||||||
|
label: 'API key override',
|
||||||
|
description: 'Optional. Falls back to DOCUMENSO_API_KEY env when blank. Stored in plain text.',
|
||||||
|
type: 'password',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const EOI_FIELDS: SettingFieldDef[] = [
|
||||||
|
{
|
||||||
|
key: 'documenso_eoi_template_id',
|
||||||
|
label: 'EOI Documenso template ID',
|
||||||
|
description: 'Numeric template ID used by the Documenso EOI pathway.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: '12345',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'eoi_default_pathway',
|
||||||
|
label: 'Default EOI pathway',
|
||||||
|
description:
|
||||||
|
'Which pathway is used when an EOI is generated without an explicit choice. Documenso = signed via Documenso, In-app = filled locally with pdf-lib.',
|
||||||
|
type: 'select',
|
||||||
|
options: [
|
||||||
|
{ value: 'documenso-template', label: 'Documenso template' },
|
||||||
|
{ value: 'inapp', label: 'In-app (pdf-lib)' },
|
||||||
|
],
|
||||||
|
defaultValue: 'documenso-template',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function DocumensoSettingsPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">Documenso & EOI</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
API credentials and default EOI generation pathway. Use the test-connection button to
|
||||||
|
verify a saved configuration before relying on it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SettingsFormCard
|
||||||
|
title="Documenso API"
|
||||||
|
description="Per-port API credentials. Leave blank to use the global env defaults."
|
||||||
|
fields={API_FIELDS}
|
||||||
|
extra={<DocumensoTestButton />}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SettingsFormCard
|
||||||
|
title="EOI generation"
|
||||||
|
description="Default pathway and template used when an interest's EOI is generated."
|
||||||
|
fields={EOI_FIELDS}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
101
src/app/(dashboard)/[portSlug]/admin/email/page.tsx
Normal file
101
src/app/(dashboard)/[portSlug]/admin/email/page.tsx
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
import {
|
||||||
|
SettingsFormCard,
|
||||||
|
type SettingFieldDef,
|
||||||
|
} from '@/components/admin/shared/settings-form-card';
|
||||||
|
|
||||||
|
const FIELDS: SettingFieldDef[] = [
|
||||||
|
{
|
||||||
|
key: 'email_from_name',
|
||||||
|
label: 'From name',
|
||||||
|
description: 'Display name shown in the From: header on outgoing email.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'Port Nimara',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'email_from_address',
|
||||||
|
label: 'From address',
|
||||||
|
description: 'Sender email address. Falls back to SMTP_FROM env when blank.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'noreply@example.com',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'email_reply_to',
|
||||||
|
label: 'Reply-to address',
|
||||||
|
description: 'Optional Reply-To: header for replies (e.g. sales@example.com).',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'sales@example.com',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'email_signature_html',
|
||||||
|
label: 'Default signature (HTML)',
|
||||||
|
description: 'Appended to the bottom of system-generated emails.',
|
||||||
|
type: 'html',
|
||||||
|
placeholder: '<p>—<br>The Port Nimara team</p>',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'email_footer_html',
|
||||||
|
label: 'Email footer (HTML)',
|
||||||
|
description: 'Legal/contact footer rendered at the very bottom of all emails.',
|
||||||
|
type: 'html',
|
||||||
|
placeholder: '<p style="font-size:11px;color:#888;">© Port Nimara · ul. ...</p>',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smtp_host_override',
|
||||||
|
label: 'SMTP host override',
|
||||||
|
description: 'Optional. Falls back to SMTP_HOST env when blank.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'mail.example.com',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smtp_port_override',
|
||||||
|
label: 'SMTP port override',
|
||||||
|
description: 'Optional. Falls back to SMTP_PORT env when blank.',
|
||||||
|
type: 'number',
|
||||||
|
placeholder: '587',
|
||||||
|
defaultValue: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smtp_user_override',
|
||||||
|
label: 'SMTP username override',
|
||||||
|
description: 'Optional. Falls back to SMTP_USER env when blank.',
|
||||||
|
type: 'string',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'smtp_pass_override',
|
||||||
|
label: 'SMTP password override',
|
||||||
|
description: 'Optional. Stored in plain text — only set when overriding env credentials.',
|
||||||
|
type: 'password',
|
||||||
|
defaultValue: '',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function EmailSettingsPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">Email Settings</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Per-port outgoing email configuration. SMTP credentials and the From address default to
|
||||||
|
environment variables when these fields are blank.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<SettingsFormCard
|
||||||
|
title="From address & signature"
|
||||||
|
description="Identity headers and shared HTML used by system-generated emails."
|
||||||
|
fields={FIELDS.slice(0, 5)}
|
||||||
|
/>
|
||||||
|
<SettingsFormCard
|
||||||
|
title="SMTP transport overrides"
|
||||||
|
description="Optional per-port SMTP credentials. Leave blank to use the global env defaults."
|
||||||
|
fields={FIELDS.slice(5)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
16
src/app/(dashboard)/[portSlug]/admin/invitations/page.tsx
Normal file
16
src/app/(dashboard)/[portSlug]/admin/invitations/page.tsx
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { InvitationsManager } from '@/components/admin/invitations/invitations-manager';
|
||||||
|
|
||||||
|
export default function InvitationsPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">Invitations</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Send a single-use invitation to a new CRM user. The recipient sets their own password via
|
||||||
|
the link in the email.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<InvitationsManager />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
196
src/app/(dashboard)/[portSlug]/admin/page.tsx
Normal file
196
src/app/(dashboard)/[portSlug]/admin/page.tsx
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
|
import {
|
||||||
|
Bell,
|
||||||
|
Briefcase,
|
||||||
|
Database,
|
||||||
|
FileText,
|
||||||
|
HardDrive,
|
||||||
|
Key,
|
||||||
|
LayoutDashboard,
|
||||||
|
Mail,
|
||||||
|
Palette,
|
||||||
|
ScrollText,
|
||||||
|
Settings,
|
||||||
|
Shield,
|
||||||
|
Sliders,
|
||||||
|
Tag,
|
||||||
|
Upload,
|
||||||
|
Users,
|
||||||
|
Webhook,
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
|
||||||
|
interface AdminSection {
|
||||||
|
href: string;
|
||||||
|
label: string;
|
||||||
|
description: string;
|
||||||
|
icon: typeof Settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SECTIONS: AdminSection[] = [
|
||||||
|
{
|
||||||
|
href: 'users',
|
||||||
|
label: 'Users',
|
||||||
|
description: 'CRM accounts, role assignments, and per-user residential access toggles.',
|
||||||
|
icon: Users,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'invitations',
|
||||||
|
label: 'Invitations',
|
||||||
|
description: 'Send invitations, track pending invites, and resend or revoke them.',
|
||||||
|
icon: Mail,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'roles',
|
||||||
|
label: 'Roles & Permissions',
|
||||||
|
description: 'Default permission sets and per-port role overrides.',
|
||||||
|
icon: Shield,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'audit',
|
||||||
|
label: 'Audit Log',
|
||||||
|
description: 'Searchable log of every authenticated mutation in the system.',
|
||||||
|
icon: ScrollText,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'email',
|
||||||
|
label: 'Email Settings',
|
||||||
|
description: 'From address, signatures, and per-port SMTP overrides.',
|
||||||
|
icon: Mail,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'documenso',
|
||||||
|
label: 'Documenso & EOI',
|
||||||
|
description: 'API credentials, EOI template, and default in-app vs Documenso pathway.',
|
||||||
|
icon: FileText,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'reminders',
|
||||||
|
label: 'Reminders',
|
||||||
|
description: 'Default reminder behaviour and the daily-digest delivery window.',
|
||||||
|
icon: Bell,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'branding',
|
||||||
|
label: 'Branding',
|
||||||
|
description: 'App name, logo, primary color, and email header/footer HTML.',
|
||||||
|
icon: Palette,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'settings',
|
||||||
|
label: 'System Settings',
|
||||||
|
description: 'Generic key/value configuration store for advanced flags.',
|
||||||
|
icon: Settings,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'webhooks',
|
||||||
|
label: 'Webhooks',
|
||||||
|
description: 'Outgoing webhook subscriptions, secrets, and delivery log.',
|
||||||
|
icon: Webhook,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'forms',
|
||||||
|
label: 'Forms',
|
||||||
|
description: 'Form templates used by client-facing inquiry and intake flows.',
|
||||||
|
icon: Sliders,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'templates',
|
||||||
|
label: 'Document Templates',
|
||||||
|
description: 'PDF + email templates with merge-field placeholders.',
|
||||||
|
icon: FileText,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'tags',
|
||||||
|
label: 'Tags',
|
||||||
|
description: 'Color-coded tags applied to clients, yachts, companies, and interests.',
|
||||||
|
icon: Tag,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'custom-fields',
|
||||||
|
label: 'Custom Fields',
|
||||||
|
description: 'Tenant-defined fields for clients, yachts, and reservations.',
|
||||||
|
icon: Key,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'reports',
|
||||||
|
label: 'Reports',
|
||||||
|
description: 'Saved analytics views and ad-hoc query results.',
|
||||||
|
icon: LayoutDashboard,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'monitoring',
|
||||||
|
label: 'Queue Monitoring',
|
||||||
|
description: 'BullMQ queue health, throughput, and retry diagnostics.',
|
||||||
|
icon: Database,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'import',
|
||||||
|
label: 'Bulk Import',
|
||||||
|
description: 'CSV-driven imports for clients, yachts, and reservations.',
|
||||||
|
icon: Upload,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'backup',
|
||||||
|
label: 'Backup & Restore',
|
||||||
|
description: 'Database snapshots and on-demand exports.',
|
||||||
|
icon: HardDrive,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'ports',
|
||||||
|
label: 'Ports',
|
||||||
|
description: 'Manage the marinas/ports this installation serves.',
|
||||||
|
icon: Briefcase,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: 'onboarding',
|
||||||
|
label: 'Onboarding',
|
||||||
|
description: 'Initial-setup wizard for fresh ports.',
|
||||||
|
icon: LayoutDashboard,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function AdminLandingPage({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ portSlug: string }>;
|
||||||
|
}) {
|
||||||
|
const { portSlug } = await params;
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">Administration</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Per-port configuration and system administration. Each card below opens a dedicated
|
||||||
|
settings page.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
{SECTIONS.map((s) => {
|
||||||
|
const Icon = s.icon;
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
key={s.href}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
href={`/${portSlug}/admin/${s.href}` as any}
|
||||||
|
className="block group"
|
||||||
|
>
|
||||||
|
<Card className="h-full transition-colors group-hover:border-primary/50 group-hover:bg-muted/30">
|
||||||
|
<CardHeader className="flex flex-row items-start gap-3 space-y-0 pb-2">
|
||||||
|
<Icon className="h-5 w-5 mt-0.5 text-muted-foreground group-hover:text-primary" />
|
||||||
|
<div className="flex-1">
|
||||||
|
<CardTitle className="text-base">{s.label}</CardTitle>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<CardDescription>{s.description}</CardDescription>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
78
src/app/(dashboard)/[portSlug]/admin/reminders/page.tsx
Normal file
78
src/app/(dashboard)/[portSlug]/admin/reminders/page.tsx
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import {
|
||||||
|
SettingsFormCard,
|
||||||
|
type SettingFieldDef,
|
||||||
|
} from '@/components/admin/shared/settings-form-card';
|
||||||
|
|
||||||
|
const DEFAULT_FIELDS: SettingFieldDef[] = [
|
||||||
|
{
|
||||||
|
key: 'reminder_default_enabled',
|
||||||
|
label: 'Enable reminders by default on new interests',
|
||||||
|
description:
|
||||||
|
'When on, newly-created interests inherit reminderEnabled=true. Users can still toggle it on a per-interest basis.',
|
||||||
|
type: 'boolean',
|
||||||
|
defaultValue: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'reminder_default_days',
|
||||||
|
label: 'Default inactivity days',
|
||||||
|
description:
|
||||||
|
"Default value for an interest's reminderDays field. Reminders fire after this many days of no contact.",
|
||||||
|
type: 'number',
|
||||||
|
placeholder: '7',
|
||||||
|
defaultValue: 7,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const DIGEST_FIELDS: SettingFieldDef[] = [
|
||||||
|
{
|
||||||
|
key: 'reminder_digest_enabled',
|
||||||
|
label: 'Batch reminders into a daily digest',
|
||||||
|
description:
|
||||||
|
'Off (default): reminders fire as soon as the threshold is hit. On: pending reminders are accumulated and delivered once per day at the digest time.',
|
||||||
|
type: 'boolean',
|
||||||
|
defaultValue: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'reminder_digest_time',
|
||||||
|
label: 'Digest delivery time',
|
||||||
|
description: '24-hour HH:MM in the digest timezone.',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: '09:00',
|
||||||
|
defaultValue: '09:00',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'reminder_digest_timezone',
|
||||||
|
label: 'Digest timezone',
|
||||||
|
description: 'IANA timezone name used to interpret the delivery time (e.g. Europe/Warsaw).',
|
||||||
|
type: 'string',
|
||||||
|
placeholder: 'Europe/Warsaw',
|
||||||
|
defaultValue: 'Europe/Warsaw',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function ReminderSettingsPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">Reminders</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Default reminder behaviour for new interests and the optional daily-digest delivery
|
||||||
|
window. Individual users can still configure their own digest preferences in Notifications
|
||||||
|
→ Preferences.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SettingsFormCard
|
||||||
|
title="Defaults for new interests"
|
||||||
|
description="Applied when an interest is created without an explicit reminder configuration."
|
||||||
|
fields={DEFAULT_FIELDS}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SettingsFormCard
|
||||||
|
title="Daily digest"
|
||||||
|
description="Optional batching window so reminder notifications go out once per day instead of as they fire."
|
||||||
|
fields={DIGEST_FIELDS}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
import { NotificationPreferencesForm } from '@/components/notifications/notification-preferences-form';
|
import { NotificationPreferencesForm } from '@/components/notifications/notification-preferences-form';
|
||||||
|
import { ReminderDigestForm } from '@/components/notifications/reminder-digest-form';
|
||||||
|
|
||||||
export default function NotificationPreferencesPage() {
|
export default function NotificationPreferencesPage() {
|
||||||
return (
|
return (
|
||||||
<div className="max-w-2xl mx-auto py-6">
|
<div className="max-w-2xl mx-auto py-6 space-y-6">
|
||||||
<div className="mb-6">
|
<div>
|
||||||
<h1 className="text-2xl font-bold">Notification Preferences</h1>
|
<h1 className="text-2xl font-bold">Notification Preferences</h1>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Choose which notifications you receive and how.
|
Choose which notifications you receive and how.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<NotificationPreferencesForm />
|
<NotificationPreferencesForm />
|
||||||
|
<ReminderDigestForm />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
20
src/app/api/v1/admin/documenso/health/route.ts
Normal file
20
src/app/api/v1/admin/documenso/health/route.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||||
|
import { errorResponse } from '@/lib/errors';
|
||||||
|
import { checkDocumensoHealth } from '@/lib/services/documenso-client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Admin probe — calls Documenso /api/v1/health using the port's effective
|
||||||
|
* config. Used by the "Test connection" button on /admin/documenso.
|
||||||
|
*/
|
||||||
|
export const POST = withAuth(
|
||||||
|
withPermission('admin', 'manage_settings', async (_req, ctx) => {
|
||||||
|
try {
|
||||||
|
const result = await checkDocumensoHealth(ctx.portId);
|
||||||
|
return NextResponse.json({ data: result });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
22
src/app/api/v1/admin/invitations/[id]/resend/route.ts
Normal file
22
src/app/api/v1/admin/invitations/[id]/resend/route.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||||
|
import { errorResponse } from '@/lib/errors';
|
||||||
|
import { resendCrmInvite } from '@/lib/services/crm-invite.service';
|
||||||
|
|
||||||
|
export const POST = withAuth(
|
||||||
|
withPermission('admin', 'manage_users', async (_req, ctx, params) => {
|
||||||
|
try {
|
||||||
|
const id = params.id ?? '';
|
||||||
|
const result = await resendCrmInvite(id, {
|
||||||
|
userId: ctx.userId,
|
||||||
|
portId: ctx.portId,
|
||||||
|
ipAddress: ctx.ipAddress,
|
||||||
|
userAgent: ctx.userAgent,
|
||||||
|
});
|
||||||
|
return NextResponse.json({ data: result });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
22
src/app/api/v1/admin/invitations/[id]/route.ts
Normal file
22
src/app/api/v1/admin/invitations/[id]/route.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||||
|
import { errorResponse } from '@/lib/errors';
|
||||||
|
import { revokeCrmInvite } from '@/lib/services/crm-invite.service';
|
||||||
|
|
||||||
|
export const DELETE = withAuth(
|
||||||
|
withPermission('admin', 'manage_users', async (_req, ctx, params) => {
|
||||||
|
try {
|
||||||
|
const id = params.id ?? '';
|
||||||
|
await revokeCrmInvite(id, {
|
||||||
|
userId: ctx.userId,
|
||||||
|
portId: ctx.portId,
|
||||||
|
ipAddress: ctx.ipAddress,
|
||||||
|
userAgent: ctx.userAgent,
|
||||||
|
});
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
36
src/app/api/v1/admin/invitations/route.ts
Normal file
36
src/app/api/v1/admin/invitations/route.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||||
|
import { parseBody } from '@/lib/api/route-helpers';
|
||||||
|
import { errorResponse } from '@/lib/errors';
|
||||||
|
import { createCrmInvite, listCrmInvites } from '@/lib/services/crm-invite.service';
|
||||||
|
|
||||||
|
export const GET = withAuth(
|
||||||
|
withPermission('admin', 'manage_users', async (_req, _ctx) => {
|
||||||
|
try {
|
||||||
|
const data = await listCrmInvites();
|
||||||
|
return NextResponse.json({ data });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const createInviteSchema = z.object({
|
||||||
|
email: z.string().email(),
|
||||||
|
name: z.string().min(1).max(200).optional(),
|
||||||
|
isSuperAdmin: z.boolean().optional().default(false),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const POST = withAuth(
|
||||||
|
withPermission('admin', 'manage_users', async (req, _ctx) => {
|
||||||
|
try {
|
||||||
|
const body = await parseBody(req, createInviteSchema);
|
||||||
|
const result = await createCrmInvite(body);
|
||||||
|
return NextResponse.json({ data: result }, { status: 201 });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
47
src/app/api/v1/users/me/preferences/route.ts
Normal file
47
src/app/api/v1/users/me/preferences/route.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
import { withAuth } from '@/lib/api/helpers';
|
||||||
|
import { parseBody } from '@/lib/api/route-helpers';
|
||||||
|
import { db } from '@/lib/db';
|
||||||
|
import { userProfiles, type UserPreferences } from '@/lib/db/schema/users';
|
||||||
|
import { errorResponse } from '@/lib/errors';
|
||||||
|
import { updateUserPreferencesSchema } from '@/lib/validators/user-preferences';
|
||||||
|
|
||||||
|
export const GET = withAuth(async (_req, ctx) => {
|
||||||
|
try {
|
||||||
|
const profile = await db.query.userProfiles.findFirst({
|
||||||
|
where: eq(userProfiles.userId, ctx.userId),
|
||||||
|
});
|
||||||
|
return NextResponse.json({ data: profile?.preferences ?? {} });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const PATCH = withAuth(async (req, ctx) => {
|
||||||
|
try {
|
||||||
|
const patch = await parseBody(req, updateUserPreferencesSchema);
|
||||||
|
|
||||||
|
const profile = await db.query.userProfiles.findFirst({
|
||||||
|
where: eq(userProfiles.userId, ctx.userId),
|
||||||
|
});
|
||||||
|
if (!profile) {
|
||||||
|
return NextResponse.json({ error: 'Profile not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const next: UserPreferences = {
|
||||||
|
...(profile.preferences ?? {}),
|
||||||
|
...patch,
|
||||||
|
};
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(userProfiles)
|
||||||
|
.set({ preferences: next })
|
||||||
|
.where(eq(userProfiles.userId, ctx.userId));
|
||||||
|
|
||||||
|
return NextResponse.json({ data: next });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
64
src/components/admin/documenso/documenso-test-button.tsx
Normal file
64
src/components/admin/documenso/documenso-test-button.tsx
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Loader2, CheckCircle2, XCircle } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
|
||||||
|
interface HealthResponse {
|
||||||
|
ok: boolean;
|
||||||
|
status?: number;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DocumensoTestButton() {
|
||||||
|
const [pending, setPending] = useState(false);
|
||||||
|
const [result, setResult] = useState<HealthResponse | null>(null);
|
||||||
|
|
||||||
|
async function runTest() {
|
||||||
|
setPending(true);
|
||||||
|
setResult(null);
|
||||||
|
try {
|
||||||
|
const res = await apiFetch<{ data: HealthResponse }>('/api/v1/admin/documenso/health', {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
setResult(res.data);
|
||||||
|
if (res.data.ok) {
|
||||||
|
toast.success(`Documenso reachable (HTTP ${res.data.status ?? 200})`);
|
||||||
|
} else {
|
||||||
|
toast.error(
|
||||||
|
res.data.error ?? `Documenso responded with HTTP ${res.data.status ?? 'unknown'}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : 'Test failed';
|
||||||
|
setResult({ ok: false, error: message });
|
||||||
|
toast.error(message);
|
||||||
|
} finally {
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{result &&
|
||||||
|
(result.ok ? (
|
||||||
|
<span className="flex items-center text-xs text-green-600">
|
||||||
|
<CheckCircle2 className="mr-1 h-3.5 w-3.5" />
|
||||||
|
HTTP {result.status}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="flex items-center text-xs text-destructive">
|
||||||
|
<XCircle className="mr-1 h-3.5 w-3.5" />
|
||||||
|
{result.error ?? `HTTP ${result.status}`}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
<Button variant="outline" onClick={runTest} disabled={pending}>
|
||||||
|
{pending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
Test connection
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
241
src/components/admin/invitations/invitations-manager.tsx
Normal file
241
src/components/admin/invitations/invitations-manager.tsx
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { Loader2, Mail, RotateCw, Plus, Trash2 } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||||
|
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
|
||||||
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
|
||||||
|
interface Invite {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
name: string | null;
|
||||||
|
isSuperAdmin: boolean;
|
||||||
|
expiresAt: string;
|
||||||
|
usedAt: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
status: 'pending' | 'accepted' | 'expired';
|
||||||
|
}
|
||||||
|
|
||||||
|
const STATUS_STYLES: Record<Invite['status'], string> = {
|
||||||
|
pending: 'bg-amber-100 text-amber-800 border-amber-200',
|
||||||
|
accepted: 'bg-green-100 text-green-800 border-green-200',
|
||||||
|
expired: 'bg-muted text-muted-foreground border-muted',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function InvitationsManager() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [sheetOpen, setSheetOpen] = useState(false);
|
||||||
|
const [email, setEmail] = useState('');
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [isSuperAdmin, setIsSuperAdmin] = useState(false);
|
||||||
|
|
||||||
|
const { data: invites = [], isLoading } = useQuery<Invite[]>({
|
||||||
|
queryKey: ['admin', 'invitations'],
|
||||||
|
queryFn: () => apiFetch<{ data: Invite[] }>('/api/v1/admin/invitations').then((r) => r.data),
|
||||||
|
});
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
apiFetch('/api/v1/admin/invitations', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { email, name: name || undefined, isSuperAdmin },
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success(`Invite sent to ${email}`);
|
||||||
|
setSheetOpen(false);
|
||||||
|
setEmail('');
|
||||||
|
setName('');
|
||||||
|
setIsSuperAdmin(false);
|
||||||
|
qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to send invite'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const resendMutation = useMutation({
|
||||||
|
mutationFn: (id: string) =>
|
||||||
|
apiFetch(`/api/v1/admin/invitations/${id}/resend`, { method: 'POST' }),
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Invite resent');
|
||||||
|
qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to resend'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const revokeMutation = useMutation({
|
||||||
|
mutationFn: (id: string) => apiFetch(`/api/v1/admin/invitations/${id}`, { method: 'DELETE' }),
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Invite revoked');
|
||||||
|
qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err instanceof Error ? err.message : 'Failed to revoke'),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold">Pending invitations</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Invitations expire 72 hours after issue. Resending mints a new token and emails it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setSheetOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
|
Send invite
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="text-sm text-muted-foreground">Loading…</p>
|
||||||
|
) : invites.length === 0 ? (
|
||||||
|
<div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
|
||||||
|
<Mail className="mx-auto h-6 w-6 mb-2" />
|
||||||
|
<p className="text-sm">No invitations issued yet.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-lg border bg-card overflow-hidden">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left font-medium px-3 py-2">Email</th>
|
||||||
|
<th className="text-left font-medium px-3 py-2">Name</th>
|
||||||
|
<th className="text-left font-medium px-3 py-2">Role</th>
|
||||||
|
<th className="text-left font-medium px-3 py-2">Status</th>
|
||||||
|
<th className="text-left font-medium px-3 py-2">Expires</th>
|
||||||
|
<th className="px-3 py-2"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{invites.map((i) => (
|
||||||
|
<tr key={i.id} className="border-t">
|
||||||
|
<td className="px-3 py-2 font-medium">{i.email}</td>
|
||||||
|
<td className="px-3 py-2 text-muted-foreground">{i.name ?? '—'}</td>
|
||||||
|
<td className="px-3 py-2 text-muted-foreground">
|
||||||
|
{i.isSuperAdmin ? 'Super admin' : 'Standard user'}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<span
|
||||||
|
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium capitalize ${STATUS_STYLES[i.status]}`}
|
||||||
|
>
|
||||||
|
{i.status}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-muted-foreground">
|
||||||
|
{new Date(i.expiresAt).toLocaleString()}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-right">
|
||||||
|
{i.status === 'pending' || i.status === 'expired' ? (
|
||||||
|
<div className="inline-flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => resendMutation.mutate(i.id)}
|
||||||
|
disabled={resendMutation.isPending || !!i.usedAt}
|
||||||
|
title="Resend invite"
|
||||||
|
>
|
||||||
|
<RotateCw className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
{i.status === 'pending' && (
|
||||||
|
<ConfirmationDialog
|
||||||
|
trigger={
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="text-destructive"
|
||||||
|
title="Revoke"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
title="Revoke invitation?"
|
||||||
|
description={`Revoke the pending invitation for ${i.email}? The link in the email will stop working.`}
|
||||||
|
confirmLabel="Revoke"
|
||||||
|
onConfirm={() => revokeMutation.mutate(i.id)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-muted-foreground">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
|
||||||
|
<SheetContent>
|
||||||
|
<SheetHeader>
|
||||||
|
<SheetTitle>Send invitation</SheetTitle>
|
||||||
|
</SheetHeader>
|
||||||
|
<form
|
||||||
|
className="mt-6 space-y-4"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
createMutation.mutate();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="invite-email">Email *</Label>
|
||||||
|
<Input
|
||||||
|
id="invite-email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="invite-name">Display name</Label>
|
||||||
|
<Input
|
||||||
|
id="invite-name"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
placeholder="Optional"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-start justify-between gap-4 rounded-lg border p-3">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="invite-superadmin" className="text-sm font-medium">
|
||||||
|
Grant super admin
|
||||||
|
</Label>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Super admins bypass per-port permission checks. Use sparingly.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
id="invite-superadmin"
|
||||||
|
checked={isSuperAdmin}
|
||||||
|
onCheckedChange={setIsSuperAdmin}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<SheetFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setSheetOpen(false)}
|
||||||
|
disabled={createMutation.isPending}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={!email.trim() || createMutation.isPending}>
|
||||||
|
{createMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
Send invite
|
||||||
|
</Button>
|
||||||
|
</SheetFooter>
|
||||||
|
</form>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
309
src/components/admin/shared/settings-form-card.tsx
Normal file
309
src/components/admin/shared/settings-form-card.tsx
Normal file
@@ -0,0 +1,309 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState, type ReactNode } from 'react';
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
|
||||||
|
export type SettingFieldType =
|
||||||
|
| 'string'
|
||||||
|
| 'password'
|
||||||
|
| 'number'
|
||||||
|
| 'boolean'
|
||||||
|
| 'textarea'
|
||||||
|
| 'html'
|
||||||
|
| 'select'
|
||||||
|
| 'color';
|
||||||
|
|
||||||
|
export interface SettingFieldDef {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
type: SettingFieldType;
|
||||||
|
placeholder?: string;
|
||||||
|
defaultValue: unknown;
|
||||||
|
options?: Array<{ value: string; label: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SettingsRowResponse {
|
||||||
|
key: string;
|
||||||
|
value: unknown;
|
||||||
|
portId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ListResponse {
|
||||||
|
data: { portSettings: SettingsRowResponse[]; globalSettings: SettingsRowResponse[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SettingsFormCardProps {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
fields: SettingFieldDef[];
|
||||||
|
/** Optional extra slot rendered below the form (e.g. test-connection button). */
|
||||||
|
extra?: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reusable card that fetches /api/v1/admin/settings, renders editable form
|
||||||
|
* fields for the supplied keys, and PUTs each on save.
|
||||||
|
*/
|
||||||
|
export function SettingsFormCard({ title, description, fields, extra }: SettingsFormCardProps) {
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [values, setValues] = useState<Record<string, unknown>>({});
|
||||||
|
const [originals, setOriginals] = useState<Record<string, unknown>>({});
|
||||||
|
|
||||||
|
const fetchValues = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await apiFetch<ListResponse>('/api/v1/admin/settings');
|
||||||
|
const next: Record<string, unknown> = {};
|
||||||
|
for (const field of fields) {
|
||||||
|
const port = res.data.portSettings.find((s) => s.key === field.key);
|
||||||
|
const global = res.data.globalSettings.find((s) => s.key === field.key);
|
||||||
|
next[field.key] = port?.value ?? global?.value ?? field.defaultValue;
|
||||||
|
}
|
||||||
|
setValues(next);
|
||||||
|
setOriginals(next);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [fields]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchValues();
|
||||||
|
}, [fetchValues]);
|
||||||
|
|
||||||
|
function setField(key: string, value: unknown) {
|
||||||
|
setValues((prev) => ({ ...prev, [key]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const changedFields = fields.filter((f) => values[f.key] !== originals[f.key]);
|
||||||
|
if (changedFields.length === 0) {
|
||||||
|
toast.info('No changes to save');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const f of changedFields) {
|
||||||
|
await apiFetch('/api/v1/admin/settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: { key: f.key, value: values[f.key] },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
toast.success(`Saved ${changedFields.length} setting(s)`);
|
||||||
|
setOriginals(values);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : 'Save failed');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{title}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex items-center text-sm text-muted-foreground">
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
Loading…
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirty = fields.some((f) => values[f.key] !== originals[f.key]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{title}</CardTitle>
|
||||||
|
{description && <CardDescription>{description}</CardDescription>}
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-5">
|
||||||
|
{fields.map((field) => (
|
||||||
|
<FieldRow
|
||||||
|
key={field.key}
|
||||||
|
field={field}
|
||||||
|
value={values[field.key]}
|
||||||
|
onChange={(v) => setField(field.key, v)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2 pt-2 border-t">
|
||||||
|
{extra}
|
||||||
|
<Button onClick={handleSave} disabled={saving || !dirty}>
|
||||||
|
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
Save changes
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldRow({
|
||||||
|
field,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
field: SettingFieldDef;
|
||||||
|
value: unknown;
|
||||||
|
onChange: (v: unknown) => void;
|
||||||
|
}) {
|
||||||
|
const id = `setting-${field.key}`;
|
||||||
|
|
||||||
|
switch (field.type) {
|
||||||
|
case 'boolean':
|
||||||
|
return (
|
||||||
|
<div className="flex items-start justify-between gap-4">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Switch id={id} checked={!!value} onCheckedChange={(checked) => onChange(checked)} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'textarea':
|
||||||
|
case 'html':
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
<Textarea
|
||||||
|
id={id}
|
||||||
|
rows={field.type === 'html' ? 6 : 3}
|
||||||
|
value={typeof value === 'string' ? value : ''}
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
className={field.type === 'html' ? 'font-mono text-xs' : undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'select':
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
<Select value={typeof value === 'string' ? value : ''} onValueChange={(v) => onChange(v)}>
|
||||||
|
<SelectTrigger id={id}>
|
||||||
|
<SelectValue placeholder={field.placeholder ?? 'Choose…'} />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{(field.options ?? []).map((o) => (
|
||||||
|
<SelectItem key={o.value} value={o.value}>
|
||||||
|
{o.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'number':
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
type="number"
|
||||||
|
value={typeof value === 'number' ? value : ''}
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
onChange={(e) => {
|
||||||
|
const n = e.target.value === '' ? null : Number(e.target.value);
|
||||||
|
onChange(n);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'color':
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
value={typeof value === 'string' ? value : '#000000'}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
className="h-9 w-14 cursor-pointer rounded border"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
value={typeof value === 'string' ? value : ''}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
placeholder="#000000"
|
||||||
|
className="font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'password':
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
type="password"
|
||||||
|
value={typeof value === 'string' ? value : ''}
|
||||||
|
placeholder={field.placeholder ?? '(unchanged)'}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'string':
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor={id}>{field.label}</Label>
|
||||||
|
{field.description && (
|
||||||
|
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||||
|
)}
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
value={typeof value === 'string' ? value : ''}
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
173
src/components/notifications/reminder-digest-form.tsx
Normal file
173
src/components/notifications/reminder-digest-form.tsx
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
|
||||||
|
interface ReminderPrefs {
|
||||||
|
delivery: 'immediate' | 'daily' | 'weekly' | 'off';
|
||||||
|
digestTime?: string;
|
||||||
|
digestDayOfWeek?: number;
|
||||||
|
timezone?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserPrefsResponse {
|
||||||
|
reminders?: ReminderPrefs;
|
||||||
|
timezone?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DAYS = [
|
||||||
|
{ value: '0', label: 'Sunday' },
|
||||||
|
{ value: '1', label: 'Monday' },
|
||||||
|
{ value: '2', label: 'Tuesday' },
|
||||||
|
{ value: '3', label: 'Wednesday' },
|
||||||
|
{ value: '4', label: 'Thursday' },
|
||||||
|
{ value: '5', label: 'Friday' },
|
||||||
|
{ value: '6', label: 'Saturday' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function ReminderDigestForm() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const { data, isLoading } = useQuery<UserPrefsResponse>({
|
||||||
|
queryKey: ['user', 'preferences'],
|
||||||
|
queryFn: () =>
|
||||||
|
apiFetch<{ data: UserPrefsResponse }>('/api/v1/users/me/preferences').then((r) => r.data),
|
||||||
|
});
|
||||||
|
|
||||||
|
const [delivery, setDelivery] = useState<ReminderPrefs['delivery']>('immediate');
|
||||||
|
const [digestTime, setDigestTime] = useState('09:00');
|
||||||
|
const [digestDay, setDigestDay] = useState('1');
|
||||||
|
const [timezone, setTimezone] = useState('Europe/Warsaw');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const r = data?.reminders;
|
||||||
|
if (r) {
|
||||||
|
setDelivery(r.delivery ?? 'immediate');
|
||||||
|
setDigestTime(r.digestTime ?? '09:00');
|
||||||
|
setDigestDay(String(r.digestDayOfWeek ?? 1));
|
||||||
|
setTimezone(r.timezone ?? data?.timezone ?? 'Europe/Warsaw');
|
||||||
|
} else if (data?.timezone) {
|
||||||
|
setTimezone(data.timezone);
|
||||||
|
}
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
apiFetch('/api/v1/users/me/preferences', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: {
|
||||||
|
reminders: {
|
||||||
|
delivery,
|
||||||
|
...(delivery !== 'immediate' && delivery !== 'off' ? { digestTime, timezone } : {}),
|
||||||
|
...(delivery === 'weekly' ? { digestDayOfWeek: Number(digestDay) } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Reminder preferences saved');
|
||||||
|
qc.invalidateQueries({ queryKey: ['user', 'preferences'] });
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err instanceof Error ? err.message : 'Save failed'),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="py-6 text-sm text-muted-foreground">
|
||||||
|
<Loader2 className="mr-2 inline h-4 w-4 animate-spin" />
|
||||||
|
Loading…
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Reminder digest</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Choose how reminder notifications are delivered to you. Immediate fires as soon as a
|
||||||
|
reminder triggers; daily/weekly batch them into a digest at the time you pick.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label>Delivery</Label>
|
||||||
|
<Select
|
||||||
|
value={delivery}
|
||||||
|
onValueChange={(v) => setDelivery(v as ReminderPrefs['delivery'])}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="immediate">Immediate (default)</SelectItem>
|
||||||
|
<SelectItem value="daily">Daily digest</SelectItem>
|
||||||
|
<SelectItem value="weekly">Weekly digest</SelectItem>
|
||||||
|
<SelectItem value="off">Off (do not send)</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(delivery === 'daily' || delivery === 'weekly') && (
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label>Delivery time (HH:MM)</Label>
|
||||||
|
<Input
|
||||||
|
value={digestTime}
|
||||||
|
onChange={(e) => setDigestTime(e.target.value)}
|
||||||
|
placeholder="09:00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{delivery === 'weekly' && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label>Day of week</Label>
|
||||||
|
<Select value={digestDay} onValueChange={setDigestDay}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{DAYS.map((d) => (
|
||||||
|
<SelectItem key={d.value} value={d.value}>
|
||||||
|
{d.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-1 col-span-2">
|
||||||
|
<Label>Timezone (IANA)</Label>
|
||||||
|
<Input
|
||||||
|
value={timezone}
|
||||||
|
onChange={(e) => setTimezone(e.target.value)}
|
||||||
|
placeholder="Europe/Warsaw"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button onClick={() => mutation.mutate()} disabled={mutation.isPending}>
|
||||||
|
{mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
Save digest preferences
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,7 +12,9 @@ export type AuditAction =
|
|||||||
| 'login'
|
| 'login'
|
||||||
| 'logout'
|
| 'logout'
|
||||||
| 'permission_denied'
|
| 'permission_denied'
|
||||||
| 'revert';
|
| 'revert'
|
||||||
|
| 'revoke_invite'
|
||||||
|
| 'resend_invite';
|
||||||
|
|
||||||
export interface AuditLogParams {
|
export interface AuditLogParams {
|
||||||
/** Null for system-generated events. */
|
/** Null for system-generated events. */
|
||||||
@@ -30,13 +32,7 @@ export interface AuditLogParams {
|
|||||||
userAgent: string;
|
userAgent: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SENSITIVE_FIELDS = new Set([
|
const SENSITIVE_FIELDS = new Set(['email', 'phone', 'password', 'credentials_enc', 'token']);
|
||||||
'email',
|
|
||||||
'phone',
|
|
||||||
'password',
|
|
||||||
'credentials_enc',
|
|
||||||
'token',
|
|
||||||
]);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Masks sensitive field values to prevent PII or secrets from being stored
|
* Masks sensitive field values to prevent PII or secrets from being stored
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ import nodemailer, { type Transporter } from 'nodemailer';
|
|||||||
|
|
||||||
import { env } from '@/lib/env';
|
import { env } from '@/lib/env';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
|
import { getPortEmailConfig, type PortEmailConfig } from '@/lib/services/port-config';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates and returns a new Nodemailer SMTP transporter.
|
* Creates and returns a new Nodemailer SMTP transporter using env defaults.
|
||||||
|
* For port-scoped configuration use {@link createPortTransporter} instead.
|
||||||
*
|
*
|
||||||
* A new instance is created on each call so the factory can be used in
|
* A new instance is created on each call so the factory can be used in
|
||||||
* contexts where connection pooling is managed externally (e.g. per-request
|
* contexts where connection pooling is managed externally (e.g. per-request
|
||||||
@@ -22,11 +24,23 @@ export function createTransporter(): Transporter {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createTransporterFromConfig(cfg: PortEmailConfig): Transporter {
|
||||||
|
return nodemailer.createTransport({
|
||||||
|
host: cfg.smtpHost,
|
||||||
|
port: cfg.smtpPort,
|
||||||
|
secure: cfg.smtpPort === 465,
|
||||||
|
...(cfg.smtpUser && cfg.smtpPass ? { auth: { user: cfg.smtpUser, pass: cfg.smtpPass } } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export interface SendEmailOptions {
|
export interface SendEmailOptions {
|
||||||
to: string | string[];
|
to: string | string[];
|
||||||
subject: string;
|
subject: string;
|
||||||
html: string;
|
html: string;
|
||||||
from?: string;
|
from?: string;
|
||||||
|
/** When provided, port-level email settings override env defaults. */
|
||||||
|
portId?: string;
|
||||||
|
text?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,8 +56,10 @@ export async function sendEmail(
|
|||||||
html: string,
|
html: string,
|
||||||
from?: string,
|
from?: string,
|
||||||
text?: string,
|
text?: string,
|
||||||
|
portId?: string,
|
||||||
): Promise<nodemailer.SentMessageInfo> {
|
): Promise<nodemailer.SentMessageInfo> {
|
||||||
const transporter = createTransporter();
|
const cfg = portId ? await getPortEmailConfig(portId) : null;
|
||||||
|
const transporter = cfg ? createTransporterFromConfig(cfg) : createTransporter();
|
||||||
|
|
||||||
const requestedTo = Array.isArray(to) ? to.join(', ') : to;
|
const requestedTo = Array.isArray(to) ? to.join(', ') : to;
|
||||||
const effectiveTo = env.EMAIL_REDIRECT_TO ?? requestedTo;
|
const effectiveTo = env.EMAIL_REDIRECT_TO ?? requestedTo;
|
||||||
@@ -51,16 +67,23 @@ export async function sendEmail(
|
|||||||
? `[redirected from ${requestedTo}] ${subject}`
|
? `[redirected from ${requestedTo}] ${subject}`
|
||||||
: subject;
|
: subject;
|
||||||
|
|
||||||
|
const fromHeader =
|
||||||
|
from ??
|
||||||
|
(cfg ? `${cfg.fromName} <${cfg.fromAddress}>` : undefined) ??
|
||||||
|
env.SMTP_FROM ??
|
||||||
|
`Port Nimara CRM <noreply@${env.SMTP_HOST}>`;
|
||||||
|
|
||||||
const info = await transporter.sendMail({
|
const info = await transporter.sendMail({
|
||||||
from: from ?? env.SMTP_FROM ?? `Port Nimara CRM <noreply@${env.SMTP_HOST}>`,
|
from: fromHeader,
|
||||||
to: effectiveTo,
|
to: effectiveTo,
|
||||||
subject: effectiveSubject,
|
subject: effectiveSubject,
|
||||||
html,
|
html,
|
||||||
|
...(cfg?.replyTo ? { replyTo: cfg.replyTo } : {}),
|
||||||
...(text ? { text } : {}),
|
...(text ? { text } : {}),
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
{ messageId: info.messageId, to: effectiveTo, originalTo: requestedTo, subject },
|
{ messageId: info.messageId, to: effectiveTo, originalTo: requestedTo, subject, portId },
|
||||||
env.EMAIL_REDIRECT_TO ? 'Email sent (redirected)' : 'Email sent',
|
env.EMAIL_REDIRECT_TO ? 'Email sent (redirected)' : 'Email sent',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -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 postgres from 'postgres';
|
||||||
|
|
||||||
import { auth } from '@/lib/auth';
|
import { auth } from '@/lib/auth';
|
||||||
|
import { createAuditLog } from '@/lib/audit';
|
||||||
import { db } from '@/lib/db';
|
import { db } from '@/lib/db';
|
||||||
import { crmUserInvites } from '@/lib/db/schema/crm-invites';
|
import { crmUserInvites } from '@/lib/db/schema/crm-invites';
|
||||||
import { userProfiles } from '@/lib/db/schema/users';
|
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 { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
|
||||||
import { hashToken, mintToken } from '@/lib/portal/passwords';
|
import { hashToken, mintToken } from '@/lib/portal/passwords';
|
||||||
|
|
||||||
|
interface AuditMeta {
|
||||||
|
userId: string;
|
||||||
|
portId: string;
|
||||||
|
ipAddress: string;
|
||||||
|
userAgent: string;
|
||||||
|
}
|
||||||
|
|
||||||
const INVITE_TTL_HOURS = 72;
|
const INVITE_TTL_HOURS = 72;
|
||||||
const MIN_PASSWORD_LENGTH = 9;
|
const MIN_PASSWORD_LENGTH = 9;
|
||||||
|
|
||||||
@@ -116,3 +124,111 @@ export async function consumeCrmInvite(args: {
|
|||||||
|
|
||||||
return { userId, email: invite.email };
|
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 };
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +1,28 @@
|
|||||||
import { env } from '@/lib/env';
|
import { env } from '@/lib/env';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
|
import { getPortDocumensoConfig } from '@/lib/services/port-config';
|
||||||
|
|
||||||
const BASE_URL = env.DOCUMENSO_API_URL;
|
interface DocumensoCreds {
|
||||||
const API_KEY = env.DOCUMENSO_API_KEY;
|
baseUrl: string;
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
async function documensoFetch(path: string, options?: RequestInit): Promise<unknown> {
|
async function resolveCreds(portId?: string): Promise<DocumensoCreds> {
|
||||||
const res = await fetch(`${BASE_URL}${path}`, {
|
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,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${API_KEY}`,
|
Authorization: `Bearer ${apiKey}`,
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
...options?.headers,
|
...options?.headers,
|
||||||
},
|
},
|
||||||
@@ -16,7 +30,7 @@ async function documensoFetch(path: string, options?: RequestInit): Promise<unkn
|
|||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.text();
|
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}`);
|
throw new Error(`Documenso API error: ${res.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,50 +84,88 @@ export async function createDocument(
|
|||||||
title: string,
|
title: string,
|
||||||
pdfBase64: string,
|
pdfBase64: string,
|
||||||
recipients: DocumensoRecipient[],
|
recipients: DocumensoRecipient[],
|
||||||
|
portId?: string,
|
||||||
): Promise<DocumensoDocument> {
|
): Promise<DocumensoDocument> {
|
||||||
return documensoFetch('/api/v1/documents', {
|
return documensoFetch(
|
||||||
method: 'POST',
|
'/api/v1/documents',
|
||||||
body: JSON.stringify({ title, document: pdfBase64, recipients }),
|
{
|
||||||
}).then(normalizeDocument);
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ title, document: pdfBase64, recipients }),
|
||||||
|
},
|
||||||
|
portId,
|
||||||
|
).then(normalizeDocument);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateDocumentFromTemplate(
|
export async function generateDocumentFromTemplate(
|
||||||
templateId: number,
|
templateId: number,
|
||||||
payload: Record<string, unknown>,
|
payload: Record<string, unknown>,
|
||||||
|
portId?: string,
|
||||||
): Promise<DocumensoDocument> {
|
): Promise<DocumensoDocument> {
|
||||||
return documensoFetch(`/api/v1/templates/${templateId}/generate-document`, {
|
return documensoFetch(
|
||||||
method: 'POST',
|
`/api/v1/templates/${templateId}/generate-document`,
|
||||||
body: JSON.stringify(payload),
|
{
|
||||||
}).then(normalizeDocument);
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
},
|
||||||
|
portId,
|
||||||
|
).then(normalizeDocument);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendDocument(docId: string): Promise<DocumensoDocument> {
|
export async function sendDocument(docId: string, portId?: string): Promise<DocumensoDocument> {
|
||||||
return documensoFetch(`/api/v1/documents/${docId}/send`, {
|
return documensoFetch(
|
||||||
method: 'POST',
|
`/api/v1/documents/${docId}/send`,
|
||||||
}).then(normalizeDocument);
|
{
|
||||||
|
method: 'POST',
|
||||||
|
},
|
||||||
|
portId,
|
||||||
|
).then(normalizeDocument);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getDocument(docId: string): Promise<DocumensoDocument> {
|
export async function getDocument(docId: string, portId?: string): Promise<DocumensoDocument> {
|
||||||
return documensoFetch(`/api/v1/documents/${docId}`).then(normalizeDocument);
|
return documensoFetch(`/api/v1/documents/${docId}`, undefined, portId).then(normalizeDocument);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendReminder(docId: string, signerId: string): Promise<void> {
|
export async function sendReminder(
|
||||||
await documensoFetch(`/api/v1/documents/${docId}/recipients/${signerId}/remind`, {
|
docId: string,
|
||||||
method: 'POST',
|
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> {
|
export async function downloadSignedPdf(docId: string, portId?: string): Promise<Buffer> {
|
||||||
const res = await fetch(`${BASE_URL}/api/v1/documents/${docId}/download`, {
|
const { baseUrl, apiKey } = await resolveCreds(portId);
|
||||||
headers: { Authorization: `Bearer ${API_KEY}` },
|
const res = await fetch(`${baseUrl}/api/v1/documents/${docId}/download`, {
|
||||||
|
headers: { Authorization: `Bearer ${apiKey}` },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.text();
|
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}`);
|
throw new Error(`Documenso download error: ${res.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const arrayBuffer = await res.arrayBuffer();
|
const arrayBuffer = await res.arrayBuffer();
|
||||||
return Buffer.from(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' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
217
src/lib/services/port-config.ts
Normal file
217
src/lib/services/port-config.ts
Normal 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,
|
||||||
|
};
|
||||||
|
}
|
||||||
21
src/lib/validators/user-preferences.ts
Normal file
21
src/lib/validators/user-preferences.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const reminderPreferencesSchema = z.object({
|
||||||
|
delivery: z.enum(['immediate', 'daily', 'weekly', 'off']).default('immediate'),
|
||||||
|
digestTime: z
|
||||||
|
.string()
|
||||||
|
.regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Must be HH:MM')
|
||||||
|
.optional(),
|
||||||
|
digestDayOfWeek: z.number().int().min(0).max(6).optional(),
|
||||||
|
timezone: z.string().min(1).max(64).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateUserPreferencesSchema = z.object({
|
||||||
|
darkMode: z.boolean().optional(),
|
||||||
|
locale: z.string().optional(),
|
||||||
|
timezone: z.string().optional(),
|
||||||
|
reminders: reminderPreferencesSchema.optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type UpdateUserPreferencesInput = z.infer<typeof updateUserPreferencesSchema>;
|
||||||
|
export type ReminderPreferences = z.infer<typeof reminderPreferencesSchema>;
|
||||||
Reference in New Issue
Block a user