feat: autonomous backlog push — admin UX overhaul + storage parity + residential parity + Documenso Phase 1
Massive multi-area push driven by docs/admin-ux-backlog.md. Every byte
path now goes through getStorageBackend() so signed EOIs, contracts,
brochures, berth PDFs, files, avatars, branding logos, and DB backups
all work identically on S3 and filesystem backends.
USER SETTINGS (rebuild)
- Country + Timezone selectors with cross-defaulting
- Browser-detected timezone banner ("Looks like you're in Europe/Paris…")
- Email change with verification flow (user_email_changes table,
OLD-address cancel link + NEW-address confirm link)
+ EMAIL_CHANGE_INSTANT=true dev shortcut
- Password reset triggered via better-auth requestPasswordReset
- Profile photo upload + crop (square 256×256) via shared
<ImageCropperDialog> + /api/v1/me/avatar
BRANDING
- Shared <ImageCropperDialog> using react-easy-crop
- Logo upload + crop in /admin/branding (writes via
/api/v1/admin/settings/image -> storage backend)
- Email header/footer HTML defaults injectable via "Insert default"
- SettingsFormCard new field types: timezone (combobox), image-upload
STORAGE ADMIN OVERHAUL
- S3 config form FIRST, swap action SECOND
- Test connection before any switch
- Two-button switch: "Switch + migrate" vs "Switch only" with
warning modals
- runMigration() honours skipMigration flag
- /api/ready + system-monitoring health check use the active
storage backend instead of always probing MinIO
- Filesystem backend already had full feature parity — verified
BACKUP MANAGEMENT (real)
- New backup_jobs table (id / status / trigger / size / storage_path)
- runBackup() service spawns pg_dump --format=custom, streams to
active storage backend via getStorageBackend().put()
- /admin/backup page: trigger, history, download .dump for restore
- Super-admin gated
AI ADMIN PANEL
- /admin/ai consolidates master switch + monthly token cap +
provider credentials
- Per-feature settings (OCR, berth-PDF parser, recommender)
linked from the same page
ONBOARDING WIZARD
- /admin/onboarding now real with auto-checked steps
- Reads each setting key + lists endpoint (roles/users/tags) to
decide completion
- Manual checkboxes for steps without an auto-detect signal
- Progress bar + Mark done/Mark incomplete buttons
- State persisted in system_settings.onboarding_manual_status
RESIDENTIAL PARITY (full)
- New residential_client_notes + residential_interest_notes tables
(mirror marina-side shape)
- Polymorphic notes.service.ts extended (verifyParent, listForEntity,
create, update, delete) for residential_clients/_interests
- <NotesList> component accepts the new entity types
- 4 new note endpoints (GET/POST/PATCH/DELETE for clients + interests)
- 2 new activity endpoints (residential clients + interests)
- residential-client-tabs.tsx + residential-interest-tabs.tsx use
DetailLayout (Overview / Interests / Notes / Activity)
- residential-client-detail-header.tsx mirrors marina-side strip
- useBreadcrumbHint wired into both detail components
- Configurable Assigned-to dropdown (residential_interests.view perm)
CONFIGURABLE RESIDENTIAL STAGES
- residential-stages.service.ts with list / save / orphan-check
- /api/v1/residential/stages GET/PUT
- /admin/residential-stages admin UI with reassign-on-remove modal
- Validators relaxed from z.enum to z.string
DOCUMENSO PHASE 1
- Schema: document_signers.invited_at / opened_at /
last_reminder_sent_at / signing_token (+ idx_ds_signing_token)
- Schema: documents.completion_cc_emails (text[]) +
auto_reminder_interval_days (int)
- transformSigningUrl() now maps SignerRole -> URL segment via
ROLE_TO_URL_SEGMENT (approver->cc, witness->witness) — fixes
Risk #5 where approver invites landed on /sign/error
- POST /api/v1/documents/[id]/send-invitation with auto-pick of
next pending signer
- Per-port settings: documenso_developer_label / _approver_label
+ documenso_developer_user_id / _approver_user_id (Phase 7
Project Director RBAC binding fields)
ADMIN UX RAPID-FIRE
- Sidebar collapse removed (always-expanded design)
- Audit log: input sizes (h-9), date pickers w-44, action cell
sub-label so single-row entries aren't blank
- Sales email config: token list <details> + tooltips on
threshold + body fields
- Custom Settings card: long-form description
- Reminder digest timezone uses TimezoneCombobox
- Port form: currency dropdown (10 common currencies) + timezone
combobox + brand color picker
- Permissions count badge opens modal with granted/denied per
resource
- Role names display-normalized via prettifyRoleName
- Tag form: native input type=color
- Custom Fields page: amber heads-up about non-integration
- Settings manager: select field type + fallthrough_policy as dropdown
- Storage admin S3 fields ship as proper password + boolean
LIST PAGES
- Residential client list: clickable email/phone (mailto/tel/wa.me)
- Residential interests + Documents Hub search inputs sized h-9
CURRENCY API
- scripts/test-currency-api.ts verifies live Frankfurter fetch
-> DB upsert -> getRate -> convert. Inverse-rate drift <=0.001
TESTS
- 1185/1185 vitest passing
- tsc clean
- eslint 0 errors (16 pre-existing warnings)
Note: WEBSITE_INTAKE_SECRET added to .env.example but committed
separately due to pre-commit hook policy on .env* files.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -230,23 +230,30 @@ export function AuditLogList() {
|
||||
{
|
||||
accessorKey: 'action',
|
||||
header: 'Action',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Badge
|
||||
className={`${ACTION_COLORS[row.original.action] ?? 'bg-gray-500'} text-white text-xs`}
|
||||
>
|
||||
{row.original.action}
|
||||
</Badge>
|
||||
{row.original.severity !== 'info' && (
|
||||
<Badge
|
||||
className={`${SEVERITY_BADGE[row.original.severity] ?? ''} text-[10px] px-1.5 py-0 uppercase`}
|
||||
variant="outline"
|
||||
>
|
||||
{row.original.severity}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const verbLabel = row.original.action.replace(/_/g, ' ');
|
||||
const entityLabel = row.original.entityType.replace(/_/g, ' ');
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Badge
|
||||
className={`${ACTION_COLORS[row.original.action] ?? 'bg-gray-500'} text-white text-xs`}
|
||||
>
|
||||
{verbLabel}
|
||||
</Badge>
|
||||
{row.original.severity !== 'info' && (
|
||||
<Badge
|
||||
className={`${SEVERITY_BADGE[row.original.severity] ?? ''} text-[10px] px-1.5 py-0 uppercase`}
|
||||
variant="outline"
|
||||
>
|
||||
{row.original.severity}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground capitalize">{entityLabel}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
@@ -342,7 +349,7 @@ export function AuditLogList() {
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
id="audit-search"
|
||||
className="pl-9"
|
||||
className="pl-9 h-9"
|
||||
placeholder="entity id, action, vendor…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
@@ -440,7 +447,7 @@ export function AuditLogList() {
|
||||
</Label>
|
||||
<Input
|
||||
id="audit-user"
|
||||
className="w-44"
|
||||
className="w-44 h-9"
|
||||
placeholder="exact user id"
|
||||
value={userId}
|
||||
onChange={(e) => setUserId(e.target.value)}
|
||||
@@ -454,7 +461,7 @@ export function AuditLogList() {
|
||||
<Input
|
||||
id="audit-from"
|
||||
type="date"
|
||||
className="w-36"
|
||||
className="w-44 h-9"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
/>
|
||||
@@ -467,7 +474,7 @@ export function AuditLogList() {
|
||||
<Input
|
||||
id="audit-to"
|
||||
type="date"
|
||||
className="w-36"
|
||||
className="w-44 h-9"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
/>
|
||||
|
||||
208
src/components/admin/backup-admin-panel.tsx
Normal file
208
src/components/admin/backup-admin-panel.tsx
Normal file
@@ -0,0 +1,208 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Loader2, Download, Database, RefreshCw, AlertTriangle } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
|
||||
interface BackupJob {
|
||||
id: string;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed';
|
||||
trigger: 'manual' | 'cron';
|
||||
triggeredBy: string | null;
|
||||
sizeBytes: number | null;
|
||||
storagePath: string | null;
|
||||
errorMessage: string | null;
|
||||
startedAt: string;
|
||||
completedAt: string | null;
|
||||
}
|
||||
|
||||
const STATUS_TONE: Record<string, string> = {
|
||||
pending: 'bg-muted text-muted-foreground',
|
||||
running: 'bg-amber-100 text-amber-900',
|
||||
completed: 'bg-emerald-100 text-emerald-900',
|
||||
failed: 'bg-rose-100 text-rose-900',
|
||||
};
|
||||
|
||||
function formatBytes(n: number | null): string {
|
||||
if (n === null) return '—';
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
||||
return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`;
|
||||
}
|
||||
|
||||
export function BackupAdminPanel() {
|
||||
const [jobs, setJobs] = useState<BackupJob[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiFetch<{ data: BackupJob[] }>('/api/v1/admin/backup');
|
||||
setJobs(res.data);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function trigger() {
|
||||
setConfirmOpen(false);
|
||||
setRunning(true);
|
||||
try {
|
||||
const res = await apiFetch<{
|
||||
data: { id: string; status: 'completed' | 'failed'; error?: string };
|
||||
}>('/api/v1/admin/backup', { method: 'POST' });
|
||||
if (res.data.status === 'completed') {
|
||||
toast.success('Backup completed');
|
||||
} else {
|
||||
toast.error(`Backup failed: ${res.data.error ?? 'unknown error'}`);
|
||||
}
|
||||
await load();
|
||||
} catch (err) {
|
||||
toastError(err);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function download(id: string) {
|
||||
try {
|
||||
const res = await apiFetch<{ data: { url: string } }>(`/api/v1/admin/backup/${id}/download`);
|
||||
const a = document.createElement('a');
|
||||
a.href = res.data.url;
|
||||
a.download = `backup-${id}.dump`;
|
||||
a.click();
|
||||
} catch (err) {
|
||||
toastError(err);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Database className="h-4 w-4" />
|
||||
Run a backup now
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Triggers <code>pg_dump --format=custom</code> against the live database and uploads
|
||||
the result to the active storage backend.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={load} disabled={loading || running}>
|
||||
<RefreshCw className="mr-1.5 h-3.5 w-3.5" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button onClick={() => setConfirmOpen(true)} disabled={running}>
|
||||
{running && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
|
||||
{running ? 'Running…' : 'Run backup'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="text-xs text-muted-foreground">
|
||||
Backups land at <code>backups/<id>.dump</code> via{' '}
|
||||
<code>getStorageBackend().put()</code>. Restore is intentionally not exposed in the UI —
|
||||
download the .dump file and run <code>pg_restore</code> manually.
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">History</CardTitle>
|
||||
<CardDescription>Last 50 backup jobs.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> Loading…
|
||||
</div>
|
||||
) : jobs.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No backups yet.</p>
|
||||
) : (
|
||||
<ul className="divide-y">
|
||||
{jobs.map((j) => (
|
||||
<li key={j.id} className="flex items-center justify-between gap-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={`text-[10px] uppercase font-medium px-1.5 py-0.5 rounded-full ${STATUS_TONE[j.status]}`}
|
||||
>
|
||||
{j.status}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(j.startedAt).toLocaleString()}
|
||||
</span>
|
||||
{j.trigger === 'cron' && (
|
||||
<span className="text-[10px] text-muted-foreground">cron</span>
|
||||
)}
|
||||
</div>
|
||||
{j.errorMessage && (
|
||||
<p className="mt-1 text-xs text-rose-700 truncate">{j.errorMessage}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 shrink-0">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatBytes(j.sizeBytes)}
|
||||
</span>
|
||||
{j.status === 'completed' && (
|
||||
<Button size="sm" variant="outline" onClick={() => download(j.id)}>
|
||||
<Download className="mr-1.5 h-3.5 w-3.5" />
|
||||
Download
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-600" />
|
||||
Run a fresh backup now?
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
This streams the entire database through <code>pg_dump</code> and stores the result in
|
||||
the active backend. On large databases the operation can take several minutes. The CRM
|
||||
stays online throughout.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setConfirmOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={trigger} disabled={running}>
|
||||
Run backup
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,10 +11,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import {
|
||||
CustomFieldForm,
|
||||
type CustomFieldDefinition,
|
||||
} from './custom-field-form';
|
||||
import { CustomFieldForm, type CustomFieldDefinition } from './custom-field-form';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -47,9 +44,7 @@ export function CustomFieldsManager() {
|
||||
const fetchFields = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiFetch<{ data: CustomFieldDefinition[] }>(
|
||||
'/api/v1/admin/custom-fields',
|
||||
);
|
||||
const res = await apiFetch<{ data: CustomFieldDefinition[] }>('/api/v1/admin/custom-fields');
|
||||
setFields(res.data);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -90,16 +85,12 @@ export function CustomFieldsManager() {
|
||||
{
|
||||
accessorKey: 'fieldName',
|
||||
header: 'Name',
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-sm">{row.original.fieldName}</span>
|
||||
),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.fieldName}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'fieldLabel',
|
||||
header: 'Label',
|
||||
cell: ({ row }) => (
|
||||
<span className="font-medium">{row.original.fieldLabel}</span>
|
||||
),
|
||||
cell: ({ row }) => <span className="font-medium">{row.original.fieldLabel}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: 'fieldType',
|
||||
@@ -126,9 +117,7 @@ export function CustomFieldsManager() {
|
||||
accessorKey: 'sortOrder',
|
||||
header: 'Order',
|
||||
cell: ({ row }) => (
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
{row.original.sortOrder}
|
||||
</span>
|
||||
<span className="tabular-nums text-muted-foreground">{row.original.sortOrder}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -136,11 +125,7 @@ export function CustomFieldsManager() {
|
||||
header: '',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(row.original)}
|
||||
>
|
||||
<Button variant="ghost" size="sm" onClick={() => handleEdit(row.original)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
<span className="sr-only">Edit</span>
|
||||
</Button>
|
||||
@@ -182,6 +167,15 @@ export function CustomFieldsManager() {
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2.5 text-xs text-amber-900">
|
||||
<strong>Heads up:</strong> custom fields render in detail-page sidebars and the entity
|
||||
export, but they don’t plug into core platform behaviour: search doesn’t index
|
||||
them, the recommender doesn’t score on them, audit logs don’t diff them, and
|
||||
merge-tokens won’t expand them in EOI/contract templates. Use them for rep-only
|
||||
annotations (e.g. “Berth visit notes”, “Referral source”) — anything
|
||||
load-bearing for the deal flow needs a first-class column.
|
||||
</div>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as EntityTab)}>
|
||||
<TabsList>
|
||||
{(Object.keys(TAB_LABELS) as EntityTab[]).map((tab) => (
|
||||
|
||||
261
src/components/admin/onboarding-checklist.tsx
Normal file
261
src/components/admin/onboarding-checklist.tsx
Normal file
@@ -0,0 +1,261 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { Check, Circle, Loader2, ExternalLink } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
interface OnboardingStep {
|
||||
id: string;
|
||||
href: string;
|
||||
label: string;
|
||||
description: string;
|
||||
/** Setting key whose presence proves the step is done. When set, the
|
||||
* checkmark auto-fills from the settings list. When undefined, the
|
||||
* step relies on the manual checkbox in `onboarding_status`. */
|
||||
autoCheckSettingKey?: string;
|
||||
/** Override: read this many users / tags / roles from a list endpoint
|
||||
* and consider the step done when count > 0. */
|
||||
autoCheckListEndpoint?: string;
|
||||
}
|
||||
|
||||
const STEPS: OnboardingStep[] = [
|
||||
{
|
||||
id: 'branding',
|
||||
href: 'branding',
|
||||
label: 'Set port name, logo, primary colour',
|
||||
description: 'Branding flows into the navbar, emails, EOI PDFs, and the public auth shell.',
|
||||
autoCheckSettingKey: 'branding_logo_url',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
href: 'email',
|
||||
label: 'Configure outgoing email',
|
||||
description:
|
||||
'From-address, signature, footer, plus per-port SMTP overrides if you don’t use the global account.',
|
||||
autoCheckSettingKey: 'sales_email_smtp_host',
|
||||
},
|
||||
{
|
||||
id: 'documenso',
|
||||
href: 'documenso',
|
||||
label: 'Connect Documenso for EOIs',
|
||||
description:
|
||||
'API credentials and the EOI template id, plus the in-app vs Documenso pathway choice.',
|
||||
autoCheckSettingKey: 'documenso_api_url',
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
href: 'settings',
|
||||
label: 'Tune business rules + recommender weights',
|
||||
description:
|
||||
'Pipeline weights, net-10 discount, berth recommender knobs (heat weights, fall-through policy).',
|
||||
autoCheckSettingKey: 'recommender_top_n_default',
|
||||
},
|
||||
{
|
||||
id: 'roles',
|
||||
href: 'roles',
|
||||
label: 'Create roles & assign users',
|
||||
description: 'Per-port roles inherit from system roles; override permissions here.',
|
||||
autoCheckListEndpoint: '/api/v1/admin/roles',
|
||||
},
|
||||
{
|
||||
id: 'users',
|
||||
href: 'users',
|
||||
label: 'Invite the rest of the team',
|
||||
description:
|
||||
'Invite users, assign roles, optionally grant residential access. Track pending vs accepted.',
|
||||
autoCheckListEndpoint: '/api/v1/admin/users',
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
href: 'tags',
|
||||
label: 'Define starter tags',
|
||||
description: 'Color-coded labels used across clients, yachts, companies, and interests.',
|
||||
autoCheckListEndpoint: '/api/v1/tags/options',
|
||||
},
|
||||
{
|
||||
id: 'storage',
|
||||
href: 'storage',
|
||||
label: 'Configure storage backend',
|
||||
description:
|
||||
'Verify S3/filesystem and run a test connection before going live so PDFs and avatars persist correctly.',
|
||||
autoCheckSettingKey: 'storage_backend',
|
||||
},
|
||||
{
|
||||
id: 'forms',
|
||||
href: '../',
|
||||
label: 'Wire the website intake forms',
|
||||
description:
|
||||
'Inquiry forms on the marketing site dual-write into the CRM via /api/public/website-inquiries. Manually mark complete when verified.',
|
||||
},
|
||||
];
|
||||
|
||||
interface SettingRow {
|
||||
key: string;
|
||||
value: unknown;
|
||||
portId: string | null;
|
||||
}
|
||||
interface SettingsResp {
|
||||
data: { portSettings: SettingRow[]; globalSettings: SettingRow[] };
|
||||
}
|
||||
|
||||
export function OnboardingChecklist() {
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const [autoChecks, setAutoChecks] = useState<Record<string, boolean>>({});
|
||||
const [manualChecks, setManualChecks] = useState<Record<string, boolean>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const settings = await apiFetch<SettingsResp>('/api/v1/admin/settings');
|
||||
const all = [...settings.data.portSettings, ...settings.data.globalSettings];
|
||||
const byKey = new Map(all.map((r) => [r.key, r.value]));
|
||||
|
||||
const checks: Record<string, boolean> = {};
|
||||
const listChecks = await Promise.all(
|
||||
STEPS.map(async (s) => {
|
||||
if (s.autoCheckSettingKey) {
|
||||
const v = byKey.get(s.autoCheckSettingKey);
|
||||
return [s.id, v !== undefined && v !== null && v !== '' && v !== false] as const;
|
||||
}
|
||||
if (s.autoCheckListEndpoint) {
|
||||
try {
|
||||
const res = await apiFetch<{ data: unknown[] }>(s.autoCheckListEndpoint);
|
||||
return [s.id, Array.isArray(res.data) && res.data.length > 0] as const;
|
||||
} catch {
|
||||
return [s.id, false] as const;
|
||||
}
|
||||
}
|
||||
return [s.id, false] as const;
|
||||
}),
|
||||
);
|
||||
for (const [id, done] of listChecks) checks[id] = done;
|
||||
setAutoChecks(checks);
|
||||
|
||||
// Pull the manual-checkbox state from system_settings.
|
||||
const manual = (byKey.get('onboarding_manual_status') ?? {}) as Record<string, boolean>;
|
||||
setManualChecks(manual);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleManual(id: string) {
|
||||
const next = { ...manualChecks, [id]: !manualChecks[id] };
|
||||
setManualChecks(next);
|
||||
setSaving(id);
|
||||
try {
|
||||
await apiFetch('/api/v1/admin/settings', {
|
||||
method: 'PUT',
|
||||
body: { key: 'onboarding_manual_status', value: next },
|
||||
});
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
}
|
||||
|
||||
const stepDone = (id: string) => Boolean(autoChecks[id]) || Boolean(manualChecks[id]);
|
||||
const completed = STEPS.filter((s) => stepDone(s.id)).length;
|
||||
const percent = Math.round((completed / STEPS.length) * 100);
|
||||
|
||||
return (
|
||||
<div className="mt-6 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Setup checklist</CardTitle>
|
||||
<CardDescription>
|
||||
{completed} of {STEPS.length} complete. Auto-checked steps update when you save the
|
||||
underlying setting; manual ones (like website-form integration) need the checkbox.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<Progress value={percent} className="h-2" />
|
||||
|
||||
<ol className="space-y-3">
|
||||
{STEPS.map((step, idx) => {
|
||||
const auto = Boolean(autoChecks[step.id]);
|
||||
const manual = Boolean(manualChecks[step.id]);
|
||||
const done = auto || manual;
|
||||
return (
|
||||
<li
|
||||
key={step.id}
|
||||
className={
|
||||
done
|
||||
? 'flex items-start gap-3 rounded-md border border-emerald-200 bg-emerald-50/50 p-3'
|
||||
: 'flex items-start gap-3 rounded-md border p-3'
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={
|
||||
done
|
||||
? 'mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-emerald-500 text-white'
|
||||
: 'mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground'
|
||||
}
|
||||
>
|
||||
{done ? (
|
||||
<Check className="h-4 w-4" />
|
||||
) : loading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Circle className="h-4 w-4" />
|
||||
)}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<Link
|
||||
href={`/${portSlug}/admin/${step.href}` as never}
|
||||
className="text-sm font-medium hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
{idx + 1}. {step.label}
|
||||
<ExternalLink className="h-3 w-3 opacity-50" />
|
||||
</Link>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">{step.description}</p>
|
||||
{auto && (
|
||||
<p className="mt-1 text-[11px] text-emerald-700">
|
||||
Auto-detected complete via{' '}
|
||||
<code className="text-[10px]">
|
||||
{step.autoCheckSettingKey ?? step.autoCheckListEndpoint}
|
||||
</code>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{!auto && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={manual ? 'secondary' : 'outline'}
|
||||
disabled={saving === step.id}
|
||||
onClick={() => toggleManual(step.id)}
|
||||
>
|
||||
{saving === step.id ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : manual ? (
|
||||
'Mark incomplete'
|
||||
) : (
|
||||
'Mark done'
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,9 +6,34 @@ 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 {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
|
||||
import { TimezoneCombobox } from '@/components/shared/timezone-combobox';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
// ISO-4217 currency shortlist for the port-currency dropdown.
|
||||
// Marina deals price in a small set; an admin who needs an exotic
|
||||
// currency can add it here without a schema change.
|
||||
const CURRENCY_OPTIONS: Array<{ value: string; label: string }> = [
|
||||
{ value: 'USD', label: 'USD — US Dollar' },
|
||||
{ value: 'EUR', label: 'EUR — Euro' },
|
||||
{ value: 'GBP', label: 'GBP — British Pound' },
|
||||
{ value: 'CHF', label: 'CHF — Swiss Franc' },
|
||||
{ value: 'AED', label: 'AED — UAE Dirham' },
|
||||
{ value: 'SAR', label: 'SAR — Saudi Riyal' },
|
||||
{ value: 'PLN', label: 'PLN — Polish Złoty' },
|
||||
{ value: 'AUD', label: 'AUD — Australian Dollar' },
|
||||
{ value: 'CAD', label: 'CAD — Canadian Dollar' },
|
||||
{ value: 'NZD', label: 'NZD — New Zealand Dollar' },
|
||||
{ value: 'JPY', label: 'JPY — Japanese Yen' },
|
||||
];
|
||||
|
||||
interface PortFormProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -154,25 +179,23 @@ export function PortForm({ open, onOpenChange, port, onSuccess }: PortFormProps)
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="port-currency">Currency</Label>
|
||||
<Input
|
||||
id="port-currency"
|
||||
value={defaultCurrency}
|
||||
onChange={(e) => setDefaultCurrency(e.target.value.toUpperCase())}
|
||||
placeholder="USD"
|
||||
maxLength={3}
|
||||
required
|
||||
/>
|
||||
<Select value={defaultCurrency} onValueChange={setDefaultCurrency}>
|
||||
<SelectTrigger id="port-currency">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CURRENCY_OPTIONS.map((c) => (
|
||||
<SelectItem key={c.value} value={c.value}>
|
||||
{c.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="port-timezone">Timezone</Label>
|
||||
<Input
|
||||
id="port-timezone"
|
||||
value={timezone}
|
||||
onChange={(e) => setTimezone(e.target.value)}
|
||||
placeholder="America/Anguilla"
|
||||
required
|
||||
/>
|
||||
<Label>Timezone</Label>
|
||||
<TimezoneCombobox value={timezone} onChange={(tz) => setTimezone(tz ?? '')} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
329
src/components/admin/residential-stages-admin.tsx
Normal file
329
src/components/admin/residential-stages-admin.tsx
Normal file
@@ -0,0 +1,329 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { GripVertical, Plus, Trash2, Loader2, Save, AlertTriangle } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
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';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface Stage {
|
||||
id: string;
|
||||
label: string;
|
||||
terminal: 'won' | 'lost' | null;
|
||||
}
|
||||
|
||||
interface Orphan {
|
||||
id: string;
|
||||
pipelineStage: string;
|
||||
}
|
||||
|
||||
interface Resp {
|
||||
data: { stages: Stage[]; orphans: Orphan[] };
|
||||
}
|
||||
|
||||
export function ResidentialStagesAdmin() {
|
||||
const [stages, setStages] = useState<Stage[]>([]);
|
||||
const [originalIds, setOriginalIds] = useState<Set<string>>(new Set());
|
||||
const [orphans, setOrphans] = useState<Orphan[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [reassignDialog, setReassignDialog] = useState<{
|
||||
affected: Orphan[];
|
||||
reassignments: Record<string, string>;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiFetch<Resp>('/api/v1/residential/stages');
|
||||
setStages(res.data.stages);
|
||||
setOriginalIds(new Set(res.data.stages.map((s) => s.id)));
|
||||
setOrphans(res.data.orphans);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function move(idx: number, dir: -1 | 1) {
|
||||
const next = [...stages];
|
||||
const swap = idx + dir;
|
||||
if (swap < 0 || swap >= next.length) return;
|
||||
[next[idx], next[swap]] = [next[swap]!, next[idx]!];
|
||||
setStages(next);
|
||||
}
|
||||
|
||||
function update(idx: number, patch: Partial<Stage>) {
|
||||
setStages((prev) => prev.map((s, i) => (i === idx ? { ...s, ...patch } : s)));
|
||||
}
|
||||
|
||||
function add() {
|
||||
setStages((prev) => [
|
||||
...prev,
|
||||
{ id: `stage_${prev.length + 1}`, label: 'New stage', terminal: null },
|
||||
]);
|
||||
}
|
||||
|
||||
function remove(idx: number) {
|
||||
setStages((prev) => prev.filter((_, i) => i !== idx));
|
||||
}
|
||||
|
||||
async function attemptSave(force: boolean, reassignments?: Record<string, string>) {
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch('/api/v1/residential/stages', {
|
||||
method: 'PUT',
|
||||
body: { stages, reassignments, force },
|
||||
});
|
||||
toast.success('Stages saved');
|
||||
setReassignDialog(null);
|
||||
await load();
|
||||
} catch (err: unknown) {
|
||||
// The service throws ConflictError when interests sit on a removed
|
||||
// stage. Open the reassignment dialog so the admin can fix it
|
||||
// before retrying.
|
||||
const msg = err instanceof Error ? err.message : '';
|
||||
if (/sit on a stage/.test(msg)) {
|
||||
// Build the affected list from the current orphan-snapshot
|
||||
// filtered to stages NOT in the new list.
|
||||
const newIds = new Set(stages.map((s) => s.id));
|
||||
const affected = orphans.filter((o) => !newIds.has(o.pipelineStage));
|
||||
setReassignDialog({ affected, reassignments: {} });
|
||||
} else {
|
||||
toastError(err);
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const stageIds = stages.map((s) => s.id);
|
||||
|
||||
const removedStageIds = Array.from(originalIds).filter((id) => !stageIds.includes(id));
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> Loading stages…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Stages</CardTitle>
|
||||
<CardDescription>
|
||||
Drag-style ordering via the up/down handles on the right. Stages with terminal
|
||||
“won” or “lost” mark the funnel ends and feed reports.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{stages.map((stage, idx) => (
|
||||
<div
|
||||
key={`${stage.id}-${idx}`}
|
||||
className="flex items-center gap-3 rounded-md border p-3"
|
||||
>
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex-1 grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
Id
|
||||
</Label>
|
||||
<Input
|
||||
value={stage.id}
|
||||
onChange={(e) => update(idx, { id: e.target.value })}
|
||||
className="font-mono text-xs h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
Label
|
||||
</Label>
|
||||
<Input
|
||||
value={stage.label}
|
||||
onChange={(e) => update(idx, { label: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
Terminal
|
||||
</Label>
|
||||
<Select
|
||||
value={stage.terminal ?? 'none'}
|
||||
onValueChange={(v) =>
|
||||
update(idx, {
|
||||
terminal: v === 'none' ? null : (v as 'won' | 'lost'),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">In-progress</SelectItem>
|
||||
<SelectItem value="won">Closed — won</SelectItem>
|
||||
<SelectItem value="lost">Closed — lost</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
onClick={() => move(idx, -1)}
|
||||
disabled={idx === 0}
|
||||
>
|
||||
↑
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
onClick={() => move(idx, 1)}
|
||||
disabled={idx === stages.length - 1}
|
||||
>
|
||||
↓
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => remove(idx)}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<Button type="button" variant="outline" size="sm" onClick={add}>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />
|
||||
Add stage
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{removedStageIds.length > 0 && (
|
||||
<div className="rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
|
||||
<AlertTriangle className="mr-2 inline h-4 w-4" />
|
||||
Removing: {removedStageIds.join(', ')}. Any interests parked on these stages will need to
|
||||
be reassigned before save.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button onClick={() => attemptSave(false)} disabled={saving}>
|
||||
{saving ? (
|
||||
<Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Save className="mr-1.5 h-4 w-4" />
|
||||
)}
|
||||
Save stages
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Dialog open={!!reassignDialog} onOpenChange={(o) => !o && setReassignDialog(null)}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reassign interests</DialogTitle>
|
||||
<DialogDescription>
|
||||
These residential interests sit on a stage you're removing. Pick a new stage for
|
||||
each before saving.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{reassignDialog && (
|
||||
<div className="space-y-3 max-h-80 overflow-y-auto">
|
||||
{reassignDialog.affected.map((o) => (
|
||||
<div key={o.id} className="flex items-center justify-between gap-3 text-sm">
|
||||
<div className="min-w-0">
|
||||
<code className="text-xs">{o.id.slice(0, 12)}…</code>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
currently: <code className="text-xs">{o.pipelineStage}</code>
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={reassignDialog.reassignments[o.id] ?? ''}
|
||||
onValueChange={(v) =>
|
||||
setReassignDialog((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
reassignments: { ...prev.reassignments, [o.id]: v },
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-44 h-8">
|
||||
<SelectValue placeholder="Choose stage…" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{stages.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>
|
||||
{s.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setReassignDialog(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!reassignDialog) return;
|
||||
const allAssigned = reassignDialog.affected.every(
|
||||
(o) => reassignDialog.reassignments[o.id],
|
||||
);
|
||||
if (!allAssigned) {
|
||||
toast.error('Pick a new stage for every listed interest first.');
|
||||
return;
|
||||
}
|
||||
void attemptSave(true, reassignDialog.reassignments);
|
||||
}}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
|
||||
Reassign + save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,9 +9,32 @@ import { PageHeader } from '@/components/shared/page-header';
|
||||
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { RoleForm } from './role-form';
|
||||
|
||||
/**
|
||||
* Display-normalize a stored role name. Roles are stored with whatever
|
||||
* key the admin entered (snake_case, kebab-case, free text). For UI
|
||||
* display we titlecase + space-separate so "super_admin" reads as
|
||||
* "Super Admin" and "Some role!" reads as "Some Role!" Display-only —
|
||||
* code paths that compare role names use the stored verbatim value.
|
||||
*/
|
||||
function prettifyRoleName(name: string): string {
|
||||
return name
|
||||
.replace(/[_-]+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -28,6 +51,7 @@ export function RoleList() {
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editingRole, setEditingRole] = useState<Role | null>(null);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
const [viewingPermissions, setViewingPermissions] = useState<Role | null>(null);
|
||||
|
||||
const fetchRoles = useCallback(async () => {
|
||||
setLoading(true);
|
||||
@@ -81,7 +105,11 @@ export function RoleList() {
|
||||
header: 'Name',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
{/* Display-normalize: snake_case → "Snake Case" so admin-
|
||||
created roles with arbitrary keys still read cleanly.
|
||||
The underlying name is stored verbatim and is what code
|
||||
checks against — display is purely cosmetic. */}
|
||||
<span className="font-medium">{prettifyRoleName(row.original.name)}</span>
|
||||
{row.original.isSystem && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
<Lock className="mr-1 h-3 w-3" />
|
||||
@@ -102,7 +130,19 @@ export function RoleList() {
|
||||
id: 'permissions',
|
||||
header: 'Permissions',
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="secondary">{countPermissions(row.original.permissions)}</Badge>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewingPermissions(row.original)}
|
||||
className="inline-flex"
|
||||
title="View permission breakdown"
|
||||
>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-pointer hover:bg-secondary/80 transition-colors"
|
||||
>
|
||||
{countPermissions(row.original.permissions)}
|
||||
</Badge>
|
||||
</button>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -171,6 +211,72 @@ export function RoleList() {
|
||||
role={editingRole}
|
||||
onSuccess={fetchRoles}
|
||||
/>
|
||||
|
||||
{/* Permissions inspector — opens when admin clicks the count
|
||||
badge in the table. Lists granted vs denied per resource so
|
||||
they can spot gaps before opening the editor. */}
|
||||
<Dialog open={!!viewingPermissions} onOpenChange={(o) => !o && setViewingPermissions(null)}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Permissions — {viewingPermissions ? prettifyRoleName(viewingPermissions.name) : ''}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Granted vs total per resource. Click Edit to change.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{viewingPermissions && (
|
||||
<div className="space-y-3">
|
||||
{Object.entries(viewingPermissions.permissions).map(([resource, actions]) => {
|
||||
const granted = Object.values(actions).filter(Boolean).length;
|
||||
const total = Object.keys(actions).length;
|
||||
return (
|
||||
<div key={resource} className="rounded-md border px-3 py-2">
|
||||
<div className="flex items-center justify-between mb-1.5">
|
||||
<span className="text-sm font-medium capitalize">
|
||||
{resource.replace(/_/g, ' ')}
|
||||
</span>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{granted}/{total}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{Object.entries(actions).map(([action, allowed]) => (
|
||||
<span
|
||||
key={action}
|
||||
className={
|
||||
allowed
|
||||
? 'inline-flex items-center rounded-full bg-emerald-50 text-emerald-900 px-2 py-0.5 text-[11px] font-medium'
|
||||
: 'inline-flex items-center rounded-full bg-muted text-muted-foreground px-2 py-0.5 text-[11px] font-medium line-through opacity-60'
|
||||
}
|
||||
>
|
||||
{action.replace(/_/g, ' ')}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setViewingPermissions(null)}>
|
||||
Close
|
||||
</Button>
|
||||
{viewingPermissions && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
const role = viewingPermissions;
|
||||
setViewingPermissions(null);
|
||||
handleEditRole(role);
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { VALID_MERGE_TOKENS } from '@/lib/templates/merge-fields';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
|
||||
interface SalesConfigResponse {
|
||||
@@ -308,7 +309,23 @@ export function SalesEmailConfigCard() {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Field label="Berth PDF body" id="sef-tmpl-berth">
|
||||
<details className="rounded-md border bg-muted/30 px-3 py-2 text-xs">
|
||||
<summary className="cursor-pointer font-medium text-foreground">
|
||||
Available tokens ({Array.from(VALID_MERGE_TOKENS).length})
|
||||
</summary>
|
||||
<div className="mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 font-mono text-[11px] text-muted-foreground sm:grid-cols-3">
|
||||
{Array.from(VALID_MERGE_TOKENS)
|
||||
.sort()
|
||||
.map((tok) => (
|
||||
<span key={tok}>{tok}</span>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
<Field
|
||||
label="Berth PDF body"
|
||||
id="sef-tmpl-berth"
|
||||
help="Sent when a rep emails a berth's PDF spec to a prospect. Markdown supported."
|
||||
>
|
||||
<Textarea
|
||||
id="sef-tmpl-berth"
|
||||
rows={6}
|
||||
@@ -317,7 +334,11 @@ export function SalesEmailConfigCard() {
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Brochure body" id="sef-tmpl-broc">
|
||||
<Field
|
||||
label="Brochure body"
|
||||
id="sef-tmpl-broc"
|
||||
help="Sent when a rep emails the port's master brochure to a prospect."
|
||||
>
|
||||
<Textarea
|
||||
id="sef-tmpl-broc"
|
||||
rows={6}
|
||||
@@ -337,7 +358,11 @@ export function SalesEmailConfigCard() {
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Attach-vs-link threshold (MB)" id="sef-attach">
|
||||
<Field
|
||||
label="Attach-vs-link threshold (MB)"
|
||||
id="sef-attach"
|
||||
help="Files smaller than this go in the email as an attachment. Larger files send a 24-hour signed download link instead so the message stays under SMTP size limits and doesn't bounce. Default 15 MB."
|
||||
>
|
||||
<Input
|
||||
id="sef-attach"
|
||||
type="number"
|
||||
@@ -372,10 +397,23 @@ export function SalesEmailConfigCard() {
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, id, children }: { label: string; id: string; children: React.ReactNode }) {
|
||||
function Field({
|
||||
label,
|
||||
id,
|
||||
children,
|
||||
help,
|
||||
}: {
|
||||
label: string;
|
||||
id: string;
|
||||
children: React.ReactNode;
|
||||
/** Plain-text caption rendered below the label. Use for any setting
|
||||
* whose meaning isn't immediately obvious from the label alone. */
|
||||
help?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
{help && <p className="text-xs text-muted-foreground">{help}</p>}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -11,6 +11,13 @@ import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
@@ -27,8 +34,9 @@ const KNOWN_SETTINGS: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
description: string;
|
||||
type: 'boolean' | 'number' | 'json' | 'string';
|
||||
type: 'boolean' | 'number' | 'json' | 'string' | 'select';
|
||||
defaultValue: unknown;
|
||||
options?: Array<{ value: string; label: string }>;
|
||||
}> = [
|
||||
{
|
||||
key: 'client_portal_enabled',
|
||||
@@ -137,10 +145,23 @@ const KNOWN_SETTINGS: Array<{
|
||||
{
|
||||
key: 'fallthrough_policy',
|
||||
label: 'Recommender — fall-through policy',
|
||||
description:
|
||||
'How berths re-enter the recommender after a lost deal. One of: immediate_with_heat, cooldown, never_auto_recommend.',
|
||||
type: 'string',
|
||||
description: 'How berths re-enter the recommender after a lost deal.',
|
||||
type: 'select',
|
||||
defaultValue: 'immediate_with_heat',
|
||||
options: [
|
||||
{
|
||||
value: 'immediate_with_heat',
|
||||
label: 'Immediate (with heat boost) — surface again right away',
|
||||
},
|
||||
{
|
||||
value: 'cooldown',
|
||||
label: 'Cooldown — wait N days (see below)',
|
||||
},
|
||||
{
|
||||
value: 'never_auto_recommend',
|
||||
label: 'Never — only re-surface via manual rep search',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'fallthrough_cooldown_days',
|
||||
@@ -303,52 +324,76 @@ export function SettingsManager() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* String Settings */}
|
||||
{KNOWN_SETTINGS.some((s) => s.type === 'string') && (
|
||||
{/* String + Select Settings — both render in the same card.
|
||||
'select' settings get a Select dropdown bound to setting.options;
|
||||
'string' settings get a free-text Input. */}
|
||||
{KNOWN_SETTINGS.some((s) => s.type === 'string' || s.type === 'select') && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Inquiry Settings</CardTitle>
|
||||
<CardDescription>Configure inquiry notification behavior</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{KNOWN_SETTINGS.filter((s) => s.type === 'string').map((setting) => (
|
||||
<div
|
||||
key={setting.key}
|
||||
// Stack label/description above the input on phone widths.
|
||||
// The previous flex row crushed the label column into a
|
||||
// narrow vertical stripe ("Inquiry / Contact / Email" wrapping
|
||||
// one word per line) while the input took the rest.
|
||||
className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4"
|
||||
>
|
||||
<div className="flex-1">
|
||||
<Label>{setting.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{setting.description}</p>
|
||||
{KNOWN_SETTINGS.filter((s) => s.type === 'string' || s.type === 'select').map(
|
||||
(setting) => (
|
||||
<div
|
||||
key={setting.key}
|
||||
// Stack label/description above the input on phone widths.
|
||||
// The previous flex row crushed the label column into a
|
||||
// narrow vertical stripe ("Inquiry / Contact / Email" wrapping
|
||||
// one word per line) while the input took the rest.
|
||||
className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4"
|
||||
>
|
||||
<div className="flex-1">
|
||||
<Label>{setting.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{setting.description}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{setting.type === 'select' && setting.options ? (
|
||||
<Select
|
||||
value={String(getEffectiveValue(setting.key, setting.defaultValue) ?? '')}
|
||||
onValueChange={(v) =>
|
||||
setValues((prev) => ({ ...prev, [setting.key]: v }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-72">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{setting.options.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Input
|
||||
type="text"
|
||||
className="w-full sm:w-64"
|
||||
value={String(getEffectiveValue(setting.key, setting.defaultValue) ?? '')}
|
||||
onChange={(e) =>
|
||||
setValues((prev) => ({
|
||||
...prev,
|
||||
[setting.key]: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={saving === setting.key}
|
||||
onClick={() =>
|
||||
saveSetting(setting.key, values[setting.key] ?? setting.defaultValue)
|
||||
}
|
||||
>
|
||||
<Save className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="w-full sm:w-64"
|
||||
value={String(getEffectiveValue(setting.key, setting.defaultValue) ?? '')}
|
||||
onChange={(e) =>
|
||||
setValues((prev) => ({
|
||||
...prev,
|
||||
[setting.key]: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={saving === setting.key}
|
||||
onClick={() =>
|
||||
saveSetting(setting.key, values[setting.key] ?? setting.defaultValue)
|
||||
}
|
||||
>
|
||||
<Save className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
),
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
@@ -450,7 +495,14 @@ export function SettingsManager() {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Custom Settings</CardTitle>
|
||||
<CardDescription>Additional key-value settings for this port</CardDescription>
|
||||
<CardDescription>
|
||||
Free-form key-value entries that aren't covered by the typed forms above. Use
|
||||
this for one-off feature flags, integration secrets, or experimental tunables that the
|
||||
platform reads at runtime via{' '}
|
||||
<code className="text-xs">getSystemSetting(portId, key)</code>. Values can be JSON
|
||||
objects, plain strings, numbers, or booleans. Most reps will never need this section —
|
||||
touch only if you know which key affects what.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{customSettings.map((setting) => (
|
||||
|
||||
@@ -10,6 +10,8 @@ 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 { TimezoneCombobox } from '@/components/shared/timezone-combobox';
|
||||
import { ImageCropperDialog } from '@/components/shared/image-cropper-dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -28,7 +30,9 @@ export type SettingFieldType =
|
||||
| 'textarea'
|
||||
| 'html'
|
||||
| 'select'
|
||||
| 'color';
|
||||
| 'color'
|
||||
| 'timezone'
|
||||
| 'image-upload';
|
||||
|
||||
export interface SettingFieldDef {
|
||||
key: string;
|
||||
@@ -38,6 +42,13 @@ export interface SettingFieldDef {
|
||||
placeholder?: string;
|
||||
defaultValue: unknown;
|
||||
options?: Array<{ value: string; label: string }>;
|
||||
/** For 'image-upload' fields: aspect ratio for the cropper (default 1).
|
||||
* For 'html' fields: when set, renders an "Insert default" button that
|
||||
* pastes this text into the textarea — used for email-template defaults
|
||||
* so admins can see the baseline before editing. */
|
||||
defaultTemplate?: string;
|
||||
/** For 'image-upload' fields: cropper aspect ratio. */
|
||||
imageAspect?: number;
|
||||
}
|
||||
|
||||
interface SettingsRowResponse {
|
||||
@@ -198,13 +209,26 @@ function FieldRow({
|
||||
case 'html':
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={id}>{field.label}</Label>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor={id}>{field.label}</Label>
|
||||
{field.defaultTemplate && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => onChange(field.defaultTemplate)}
|
||||
>
|
||||
Insert default
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{field.description && (
|
||||
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||
)}
|
||||
<Textarea
|
||||
id={id}
|
||||
rows={field.type === 'html' ? 6 : 3}
|
||||
rows={field.type === 'html' ? 8 : 3}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
placeholder={field.placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
@@ -213,6 +237,16 @@ function FieldRow({
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'image-upload':
|
||||
return (
|
||||
<ImageUploadField
|
||||
id={id}
|
||||
field={field}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'select':
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
@@ -255,6 +289,20 @@ function FieldRow({
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'timezone':
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={id}>{field.label}</Label>
|
||||
{field.description && (
|
||||
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||
)}
|
||||
<TimezoneCombobox
|
||||
value={typeof value === 'string' ? value : null}
|
||||
onChange={(tz) => onChange(tz)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'color':
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
@@ -315,3 +363,104 @@ function FieldRow({
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Image-upload sub-form: shows current image preview, lets admin pick
|
||||
* a file, opens the cropper, and on success replaces the setting value
|
||||
* with the resulting public URL. Used for branding logos.
|
||||
*/
|
||||
function ImageUploadField({
|
||||
id,
|
||||
field,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
id: string;
|
||||
field: SettingFieldDef;
|
||||
value: string;
|
||||
onChange: (next: unknown) => void;
|
||||
}) {
|
||||
const [pendingFile, setPendingFile] = useState<File | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
function handlePicked(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const f = e.target.files?.[0] ?? null;
|
||||
if (!f) return;
|
||||
setPendingFile(f);
|
||||
setOpen(true);
|
||||
if (inputRef.current) inputRef.current.value = '';
|
||||
}
|
||||
|
||||
async function uploadCropped(blob: Blob) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', new File([blob], 'image.jpg', { type: 'image/jpeg' }));
|
||||
const res = await fetch('/api/v1/admin/settings/image', { method: 'POST', body: fd });
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
|
||||
throw new Error(err.error?.message ?? 'Image upload failed');
|
||||
}
|
||||
const json = (await res.json()) as { data: { url: string } };
|
||||
onChange(json.data.url);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={id}>{field.label}</Label>
|
||||
{field.description && <p className="text-xs text-muted-foreground">{field.description}</p>}
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="h-20 w-20 shrink-0 rounded-md border bg-muted/30 flex items-center justify-center overflow-hidden">
|
||||
{}
|
||||
{value ? (
|
||||
<img src={value} alt="" className="h-full w-full object-contain" />
|
||||
) : (
|
||||
<span className="text-[10px] text-muted-foreground">No image</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
{value ? 'Replace image' : 'Upload image'}
|
||||
</Button>
|
||||
{value && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => onChange('')}>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="https://example.com/logo.png"
|
||||
className="text-xs"
|
||||
/>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Upload to use the platform's storage backend, or paste an external URL.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
onChange={handlePicked}
|
||||
className="hidden"
|
||||
/>
|
||||
<ImageCropperDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
file={pendingFile}
|
||||
aspect={field.imageAspect ?? 1}
|
||||
outputWidth={field.imageAspect && field.imageAspect > 1 ? 1024 : 512}
|
||||
title={`Crop ${field.label.toLowerCase()}`}
|
||||
onUpload={uploadCropped}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { CheckCircle2, HardDrive, Loader2, RefreshCw, ServerCog, XCircle } from 'lucide-react';
|
||||
import {
|
||||
AlertTriangle,
|
||||
CheckCircle2,
|
||||
HardDrive,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
ServerCog,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
@@ -16,6 +24,10 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
SettingsFormCard,
|
||||
type SettingFieldDef,
|
||||
} from '@/components/admin/shared/settings-form-card';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
|
||||
@@ -37,10 +49,78 @@ interface MigrationResult {
|
||||
dryRun: boolean;
|
||||
}
|
||||
|
||||
const S3_FIELDS: SettingFieldDef[] = [
|
||||
{
|
||||
key: 'storage_s3_endpoint',
|
||||
label: 'S3 endpoint URL',
|
||||
description:
|
||||
'For AWS use https://s3.<region>.amazonaws.com. For MinIO/Backblaze/R2/Wasabi/Tigris paste the provider-supplied URL.',
|
||||
type: 'string',
|
||||
placeholder: 'https://s3.us-east-1.amazonaws.com',
|
||||
defaultValue: '',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_region',
|
||||
label: 'S3 region',
|
||||
description: 'AWS region code (e.g. us-east-1, eu-west-1). Use "auto" for Cloudflare R2.',
|
||||
type: 'string',
|
||||
placeholder: 'us-east-1',
|
||||
defaultValue: 'us-east-1',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_bucket',
|
||||
label: 'S3 bucket name',
|
||||
description: 'Existing bucket the CRM should read/write to. Must already exist.',
|
||||
type: 'string',
|
||||
placeholder: 'port-nimara-storage',
|
||||
defaultValue: '',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_access_key',
|
||||
label: 'S3 access key',
|
||||
description: 'IAM access key id (or provider equivalent).',
|
||||
type: 'string',
|
||||
placeholder: 'AKIA…',
|
||||
defaultValue: '',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_secret_key_encrypted',
|
||||
label: 'S3 secret key',
|
||||
description:
|
||||
'Stored AES-encrypted at rest; the field shows blank after save and is replaced only when you type a new value.',
|
||||
type: 'password',
|
||||
placeholder: '(unchanged)',
|
||||
defaultValue: '',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_force_path_style',
|
||||
label: 'Force path-style URLs',
|
||||
description:
|
||||
'On for MinIO and most self-hosted S3-compatible servers. Off for AWS S3 (which uses virtual-hosted-style by default).',
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
},
|
||||
];
|
||||
|
||||
const FS_FIELDS: SettingFieldDef[] = [
|
||||
{
|
||||
key: 'storage_filesystem_root',
|
||||
label: 'Filesystem root path',
|
||||
description:
|
||||
'Absolute path on the server where files are stored. Must be writable by the CRM process. Single-node deployments only.',
|
||||
type: 'string',
|
||||
placeholder: '/var/lib/port-nimara/storage',
|
||||
defaultValue: '/var/lib/port-nimara/storage',
|
||||
},
|
||||
];
|
||||
|
||||
export function StorageAdminPanel() {
|
||||
const queryClient = useQueryClient();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [dryRun, setDryRun] = useState<MigrationResult | null>(null);
|
||||
const [confirmMode, setConfirmMode] = useState<'switch-only' | 'switch-and-migrate'>(
|
||||
'switch-and-migrate',
|
||||
);
|
||||
const [testResult, setTestResult] = useState<{ ok: boolean; error?: string } | null>(null);
|
||||
|
||||
const status = useQuery({
|
||||
@@ -62,7 +142,7 @@ export function StorageAdminPanel() {
|
||||
});
|
||||
|
||||
const migrateMutation = useMutation({
|
||||
mutationFn: async (opts: { from: BackendName; to: BackendName }) =>
|
||||
mutationFn: async (opts: { from: BackendName; to: BackendName; skipMigration: boolean }) =>
|
||||
apiFetch<{ data: MigrationResult }>('/api/v1/admin/storage/migrate', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...opts, dryRun: false }),
|
||||
@@ -71,7 +151,11 @@ export function StorageAdminPanel() {
|
||||
setConfirmOpen(false);
|
||||
setDryRun(null);
|
||||
const copied = result.data.rowsMigrated ?? 0;
|
||||
toast.success(`Storage migration complete (${copied} file${copied === 1 ? '' : 's'} copied)`);
|
||||
toast.success(
|
||||
copied > 0
|
||||
? `Storage migration complete (${copied} file${copied === 1 ? '' : 's'} copied)`
|
||||
: 'Storage backend switched (no migration performed)',
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ['admin', 'storage', 'status'] });
|
||||
},
|
||||
onError: (e) => toastError(e),
|
||||
@@ -99,70 +183,41 @@ export function StorageAdminPanel() {
|
||||
const s = status.data.data;
|
||||
const otherBackend: BackendName = s.backend === 's3' ? 'filesystem' : 's3';
|
||||
|
||||
function openConfirm(mode: 'switch-only' | 'switch-and-migrate') {
|
||||
setConfirmMode(mode);
|
||||
if (mode === 'switch-and-migrate') {
|
||||
// Dry run first so the dialog shows the exact rows + bytes.
|
||||
dryRunMutation.mutate({ from: s.backend, to: otherBackend });
|
||||
} else {
|
||||
// Switch-only — no dry run, just show the warning.
|
||||
setDryRun(null);
|
||||
setConfirmOpen(true);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="Storage Backend"
|
||||
description="Where the CRM stores per-berth PDFs, brochures, GDPR exports, and other binary files."
|
||||
description="Where the CRM stores per-berth PDFs, brochures, GDPR exports, profile photos, and other binary files."
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
<Card className="lg:col-span-2">
|
||||
<CardHeader className="flex flex-row items-start gap-3 space-y-0 pb-2">
|
||||
{s.backend === 's3' ? (
|
||||
<ServerCog className="mt-0.5 h-5 w-5 text-muted-foreground" />
|
||||
) : (
|
||||
<HardDrive className="mt-0.5 h-5 w-5 text-muted-foreground" />
|
||||
)}
|
||||
<div>
|
||||
<CardTitle className="text-base">Active backend: {s.backend}</CardTitle>
|
||||
<CardDescription>
|
||||
{s.backend === 's3'
|
||||
? 'Files stored in an S3-compatible object store (MinIO, AWS S3, Backblaze B2, Cloudflare R2, Wasabi, Tigris).'
|
||||
: 'Files stored on the local filesystem under storage_filesystem_root. Single-node deployments only.'}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<dl className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Tracked tables</dt>
|
||||
<dd>
|
||||
{s.tablesTracked.length === 0
|
||||
? '(none yet — Phase 6b)'
|
||||
: s.tablesTracked.join(', ')}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">File count</dt>
|
||||
<dd>{s.fileCount}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={dryRunMutation.isPending}
|
||||
onClick={() => dryRunMutation.mutate({ from: s.backend, to: otherBackend })}
|
||||
>
|
||||
{dryRunMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Switch to {otherBackend}
|
||||
</Button>
|
||||
{s.backend === 's3' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => testMutation.mutate()}
|
||||
disabled={testMutation.isPending}
|
||||
>
|
||||
{testMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Test connection
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" onClick={() => status.refetch()} disabled={status.isFetching}>
|
||||
<RefreshCw className="mr-2 h-4 w-4" /> Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* STEP 1: configure connection details for the OTHER backend so the
|
||||
admin can prep + test BEFORE attempting any switch. */}
|
||||
<SettingsFormCard
|
||||
title="S3 configuration"
|
||||
description="Provider connection details. Save these first, run Test connection, and only then switch the active backend below. You can edit S3 config while filesystem is active without touching live storage."
|
||||
fields={S3_FIELDS}
|
||||
extra={
|
||||
<div className="space-y-3 pt-2 border-t">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => testMutation.mutate()}
|
||||
disabled={testMutation.isPending}
|
||||
>
|
||||
{testMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Test S3 connection
|
||||
</Button>
|
||||
{testResult && (
|
||||
<div className="rounded-md border p-3 text-sm">
|
||||
{testResult.ok ? (
|
||||
@@ -176,6 +231,78 @@ export function StorageAdminPanel() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsFormCard
|
||||
title="Filesystem configuration"
|
||||
description="Used when the active backend is filesystem. Only single-node deployments — multi-node servers must use S3."
|
||||
fields={FS_FIELDS}
|
||||
/>
|
||||
|
||||
{/* STEP 2: visualize current state + switch options. Both options
|
||||
are gated behind a confirmation dialog. */}
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
<Card className="lg:col-span-2">
|
||||
<CardHeader className="flex flex-row items-start gap-3 space-y-0 pb-2">
|
||||
{s.backend === 's3' ? (
|
||||
<ServerCog className="mt-0.5 h-5 w-5 text-muted-foreground" />
|
||||
) : (
|
||||
<HardDrive className="mt-0.5 h-5 w-5 text-muted-foreground" />
|
||||
)}
|
||||
<div>
|
||||
<CardTitle className="text-base">Active backend: {s.backend}</CardTitle>
|
||||
<CardDescription>
|
||||
{s.backend === 's3'
|
||||
? 'Files stored in an S3-compatible object store (AWS, MinIO, R2, B2, Wasabi, Tigris).'
|
||||
: 'Files stored on the local filesystem under storage_filesystem_root. Single-node only.'}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<dl className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Tracked tables</dt>
|
||||
<dd>{s.tablesTracked.length === 0 ? '(none yet)' : s.tablesTracked.join(', ')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">File count</dt>
|
||||
<dd>{s.fileCount}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Switch active backend
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={dryRunMutation.isPending}
|
||||
onClick={() => openConfirm('switch-and-migrate')}
|
||||
>
|
||||
{dryRunMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Switch + migrate existing files to {otherBackend}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => openConfirm('switch-only')}>
|
||||
Switch only (new files only) → {otherBackend}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => status.refetch()}
|
||||
disabled={status.isFetching}
|
||||
>
|
||||
<RefreshCw className="mr-2 h-4 w-4" /> Refresh
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Switch + migrate</strong> copies every existing file to the new backend then
|
||||
flips the pointer atomically. Reversible with a follow-up reverse-migration.{' '}
|
||||
<strong>Switch only</strong> flips the pointer immediately — old files become
|
||||
inaccessible until you migrate them or revert the backend.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -208,13 +335,19 @@ export function StorageAdminPanel() {
|
||||
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Switch storage backend</DialogTitle>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-600" />
|
||||
{confirmMode === 'switch-and-migrate'
|
||||
? `Switch + migrate to ${otherBackend}?`
|
||||
: `Switch active backend to ${otherBackend}?`}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Move all tracked files from the current backend to the new backend, verify each file
|
||||
via sha256, then atomically flip the active backend.
|
||||
{confirmMode === 'switch-and-migrate'
|
||||
? 'Copy every existing file to the new backend, verify each via sha256, then atomically flip the active backend. The dry-run summary below shows what will move.'
|
||||
: 'Flip the pointer immediately. Existing files stay on the old backend and become inaccessible until you migrate them or revert. Use this when you intentionally want a fresh storage tier (rare).'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{dryRun && (
|
||||
{dryRun && confirmMode === 'switch-and-migrate' && (
|
||||
<div className="rounded-md border p-3 text-sm">
|
||||
<dl className="grid grid-cols-2 gap-2">
|
||||
<dt className="text-muted-foreground">Rows considered</dt>
|
||||
@@ -226,16 +359,30 @@ export function StorageAdminPanel() {
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
{confirmMode === 'switch-only' && (
|
||||
<div className="rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
|
||||
<strong>Warning:</strong> {s.fileCount} existing file
|
||||
{s.fileCount === 1 ? '' : 's'} on <code className="text-xs">{s.backend}</code> will
|
||||
not be reachable from the CRM after the switch unless you migrate them later. This is
|
||||
rarely the right choice — prefer Switch + migrate.
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setConfirmOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={migrateMutation.isPending}
|
||||
onClick={() => migrateMutation.mutate({ from: s.backend, to: otherBackend })}
|
||||
onClick={() =>
|
||||
migrateMutation.mutate({
|
||||
from: s.backend,
|
||||
to: otherBackend,
|
||||
skipMigration: confirmMode === 'switch-only',
|
||||
})
|
||||
}
|
||||
>
|
||||
{migrateMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Migrate now
|
||||
{confirmMode === 'switch-and-migrate' ? 'Migrate now' : 'Switch now'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -111,12 +111,22 @@ export function TagForm({ open, onOpenChange, tag, onSuccess }: TagFormProps) {
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<div className="h-7 w-7 rounded-full border" style={{ backgroundColor: color }} />
|
||||
{/* Native colour picker — clicking the swatch opens the
|
||||
* OS picker, and the chosen colour writes back as a
|
||||
* hex string. Keeps a manual hex input next to it for
|
||||
* pasting brand colours from spec sheets. */}
|
||||
<input
|
||||
type="color"
|
||||
value={color}
|
||||
onChange={(e) => setColor(e.target.value)}
|
||||
className="h-7 w-7 rounded-full border cursor-pointer"
|
||||
aria-label="Pick custom color"
|
||||
/>
|
||||
<Input
|
||||
value={color}
|
||||
onChange={(e) => setColor(e.target.value)}
|
||||
placeholder="#6B7280"
|
||||
className="w-28 font-mono text-sm"
|
||||
className="w-28 font-mono text-sm h-9"
|
||||
maxLength={7}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -263,7 +263,7 @@ export function DocumentsHub({ portSlug, initialTab = 'all' }: DocumentsHubProps
|
||||
placeholder="Search by title…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-xs"
|
||||
className="max-w-xs h-9"
|
||||
/>
|
||||
<Select value={typeFilter} onValueChange={setTypeFilter}>
|
||||
<SelectTrigger className="w-44">
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AlertTriangle, ExternalLink, FileSignature, Pencil } from 'lucide-react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
@@ -20,37 +22,10 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
/** Required for the EOI's top paragraph (Section 2) - without these the
|
||||
* document is unsignable, so generation is blocked. Yacht and berth fields
|
||||
* belong to Section 3 and may be left blank. */
|
||||
interface EoiPrerequisites {
|
||||
hasName: boolean;
|
||||
hasEmail: boolean;
|
||||
hasAddress: boolean;
|
||||
/** Optional - info-only checks. Generation proceeds without them. */
|
||||
hasYacht: boolean;
|
||||
hasBerth: boolean;
|
||||
}
|
||||
|
||||
interface EoiGenerateDialogProps {
|
||||
interestId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
prerequisites: EoiPrerequisites;
|
||||
}
|
||||
|
||||
const REQUIRED_LABELS: { key: keyof EoiPrerequisites; label: string }[] = [
|
||||
{ key: 'hasName', label: 'Client name' },
|
||||
{ key: 'hasAddress', label: 'Client address' },
|
||||
{ key: 'hasEmail', label: 'Client email' },
|
||||
];
|
||||
|
||||
const OPTIONAL_LABELS: { key: keyof EoiPrerequisites; label: string }[] = [
|
||||
{ key: 'hasYacht', label: 'Yacht linked (name + dimensions)' },
|
||||
{ key: 'hasBerth', label: 'Berth linked (mooring number)' },
|
||||
];
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useUIStore } from '@/stores/ui-store';
|
||||
|
||||
const DOCUMENSO_TEMPLATE_VALUE = 'documenso-template';
|
||||
|
||||
@@ -61,58 +36,171 @@ interface InAppTemplate {
|
||||
templateType: string;
|
||||
}
|
||||
|
||||
interface ListResponse {
|
||||
data: InAppTemplate[];
|
||||
interface EoiContextResponse {
|
||||
data: {
|
||||
client: {
|
||||
fullName: string;
|
||||
nationality: string | null;
|
||||
primaryEmail: string | null;
|
||||
primaryPhone: string | null;
|
||||
address: { street: string; city: string; country: string } | null;
|
||||
};
|
||||
yacht: {
|
||||
name: string;
|
||||
lengthFt: string | null;
|
||||
widthFt: string | null;
|
||||
draftFt: string | null;
|
||||
hullNumber: string | null;
|
||||
flag: string | null;
|
||||
} | null;
|
||||
berth: {
|
||||
mooringNumber: string;
|
||||
area: string | null;
|
||||
lengthFt: string | null;
|
||||
} | null;
|
||||
eoiBerthRange: string;
|
||||
port: { name: string };
|
||||
};
|
||||
}
|
||||
|
||||
interface EoiGenerateDialogProps {
|
||||
interestId: string;
|
||||
/** Used to wire the "Edit on client" deep-link inside the dialog. */
|
||||
clientId?: string | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-flight preview + generate dialog. Replaces the earlier ✓/✗
|
||||
* checklist with the actual values that will be auto-filled into the
|
||||
* EOI, so a sales rep can spot a wrong email or missing yacht
|
||||
* dimensions before sending the document for signing.
|
||||
*
|
||||
* Editing is deliberately routed back to the canonical client / yacht
|
||||
* detail pages (via "Edit on client" links) rather than allowing
|
||||
* inline edits inside the dialog. Why: the EOI's source-of-truth is
|
||||
* the underlying records, and forking the edit surface here would
|
||||
* silently bypass tag/audit-log/permission flows that the entity
|
||||
* detail pages enforce.
|
||||
*/
|
||||
export function EoiGenerateDialog({
|
||||
interestId,
|
||||
clientId,
|
||||
open,
|
||||
onOpenChange,
|
||||
prerequisites,
|
||||
}: EoiGenerateDialogProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const portSlug = useUIStore((s) => s.currentPortSlug);
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedTemplate, setSelectedTemplate] = useState<string>(DOCUMENSO_TEMPLATE_VALUE);
|
||||
|
||||
const requiredMet = REQUIRED_LABELS.every(({ key }) => prerequisites[key]);
|
||||
// Resolved EOI context — the actual values the document will be
|
||||
// auto-filled with. Loaded only while the dialog is open so we don't
|
||||
// pay for the join tree on every interest detail page render.
|
||||
const { data: ctxRes, isLoading: ctxLoading } = useQuery<EoiContextResponse>({
|
||||
queryKey: ['interests', interestId, 'eoi-context'],
|
||||
queryFn: () => apiFetch<EoiContextResponse>(`/api/v1/interests/${interestId}/eoi-context`),
|
||||
enabled: open,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
// Load in-app EOI templates so the operator can pick one as an alternative
|
||||
// to the Documenso external-signing flow.
|
||||
const { data: templatesRes } = useQuery<ListResponse>({
|
||||
const ctx = ctxRes?.data;
|
||||
|
||||
const { data: templatesRes } = useQuery<{ data: InAppTemplate[] }>({
|
||||
queryKey: ['document-templates', { templateType: 'eoi', isActive: true }],
|
||||
queryFn: () =>
|
||||
apiFetch<ListResponse>('/api/v1/document-templates?templateType=eoi&isActive=true'),
|
||||
apiFetch<{ data: InAppTemplate[] }>(
|
||||
'/api/v1/document-templates?templateType=eoi&isActive=true',
|
||||
),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const inAppTemplates = useMemo(() => templatesRes?.data ?? [], [templatesRes]);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!requiredMet) return;
|
||||
// Required for the EOI's top paragraph (Section 2). Without these
|
||||
// the document is unsignable, so generation is blocked.
|
||||
const required = ctx
|
||||
? [
|
||||
{
|
||||
key: 'name',
|
||||
label: 'Full name',
|
||||
value: ctx.client.fullName,
|
||||
present: !!ctx.client.fullName,
|
||||
},
|
||||
{
|
||||
key: 'email',
|
||||
label: 'Email address',
|
||||
value: ctx.client.primaryEmail ?? null,
|
||||
present: !!ctx.client.primaryEmail,
|
||||
},
|
||||
{
|
||||
key: 'address',
|
||||
label: 'Address',
|
||||
value: ctx.client.address
|
||||
? [ctx.client.address.street, ctx.client.address.city, ctx.client.address.country]
|
||||
.filter(Boolean)
|
||||
.join(', ')
|
||||
: null,
|
||||
present: !!ctx.client.address,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
// Optional — Section 3 of the EOI. Generation proceeds without them.
|
||||
const optional = ctx
|
||||
? [
|
||||
{
|
||||
key: 'yacht',
|
||||
label: 'Yacht name',
|
||||
value: ctx.yacht?.name ?? null,
|
||||
},
|
||||
{
|
||||
key: 'dimensions',
|
||||
label: 'Dimensions (L × W × D, ft)',
|
||||
value: ctx.yacht
|
||||
? [ctx.yacht.lengthFt, ctx.yacht.widthFt, ctx.yacht.draftFt]
|
||||
.map((v) => v ?? '—')
|
||||
.join(' × ')
|
||||
: null,
|
||||
},
|
||||
{
|
||||
key: 'berth',
|
||||
label: 'Berth (primary mooring)',
|
||||
value: ctx.berth?.mooringNumber ?? null,
|
||||
},
|
||||
{
|
||||
key: 'berthRange',
|
||||
label: 'Berth bundle range',
|
||||
value: ctx.eoiBerthRange || null,
|
||||
},
|
||||
{
|
||||
key: 'phone',
|
||||
label: 'Phone',
|
||||
value: ctx.client.primaryPhone ?? null,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
const requiredMet = required.length > 0 && required.every((r) => r.present);
|
||||
|
||||
async function handleGenerate() {
|
||||
if (!requiredMet) return;
|
||||
setIsGenerating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const isDocumensoPath = selectedTemplate === DOCUMENSO_TEMPLATE_VALUE;
|
||||
const isDocumenso = selectedTemplate === DOCUMENSO_TEMPLATE_VALUE;
|
||||
const url = `/api/v1/document-templates/${encodeURIComponent(selectedTemplate)}/generate-and-sign`;
|
||||
await apiFetch(url, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
interestId,
|
||||
pathway: isDocumensoPath ? 'documenso-template' : 'inapp',
|
||||
// Signers are derived server-side from EOI context for both pathways
|
||||
// when the template type is EOI, so the dialog doesn't collect them.
|
||||
pathway: isDocumenso ? 'documenso-template' : 'inapp',
|
||||
// Signers derived server-side from EOI context for both pathways.
|
||||
signers: [],
|
||||
},
|
||||
});
|
||||
|
||||
// Invalidate all document list queries (hub counts + per-interest lists).
|
||||
// The DocumentList component uses ['documents', { interestId, clientId }]
|
||||
// and the hub uses ['documents', 'hub', ...] / ['documents', 'hub-counts'].
|
||||
// Using a predicate avoids key-shape drift between callers.
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (q) => q.queryKey[0] === 'documents',
|
||||
});
|
||||
@@ -122,20 +210,23 @@ export function EoiGenerateDialog({
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Generate Expression of Interest</DialogTitle>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<FileSignature className="size-4" />
|
||||
Generate Expression of Interest
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick how to render the EOI. Documenso is the primary path; in-app templates use the same
|
||||
source PDF but render and store the PDF locally before sending for signing.
|
||||
Review the values that will be auto-filled into the EOI. Anything wrong? Edit it on the
|
||||
client's record before generating.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-4 py-1">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="eoi-template">Template</Label>
|
||||
<Select value={selectedTemplate} onValueChange={setSelectedTemplate}>
|
||||
@@ -155,69 +246,76 @@ export function EoiGenerateDialog({
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Required (Section 2 of the EOI)
|
||||
</p>
|
||||
{REQUIRED_LABELS.map(({ key, label }) => (
|
||||
<div key={key} className="flex items-center gap-3 text-sm">
|
||||
<span
|
||||
className={`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${
|
||||
prerequisites[key] ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
|
||||
}`}
|
||||
>
|
||||
{prerequisites[key] ? '✓' : '✗'}
|
||||
</span>
|
||||
<span
|
||||
className={prerequisites[key] ? 'text-foreground' : 'text-muted-foreground'}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{ctxLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Optional (Section 3 - left blank if absent)
|
||||
</p>
|
||||
{OPTIONAL_LABELS.map(({ key, label }) => (
|
||||
<div key={key} className="flex items-center gap-3 text-sm">
|
||||
<span
|
||||
className={`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${
|
||||
prerequisites[key]
|
||||
? 'bg-green-100 text-green-700'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
}`}
|
||||
) : ctx ? (
|
||||
<div className="space-y-3 rounded-md border bg-muted/20 p-3">
|
||||
<div className="space-y-1">
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Required (Section 2 of the EOI)
|
||||
</p>
|
||||
<dl className="space-y-1.5">
|
||||
{required.map((row) => (
|
||||
<PreviewRow
|
||||
key={row.key}
|
||||
label={row.label}
|
||||
value={row.value}
|
||||
missing={!row.present}
|
||||
/>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
<div className="space-y-1 border-t pt-2">
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Optional (Section 3 — left blank if absent)
|
||||
</p>
|
||||
<dl className="space-y-1.5">
|
||||
{optional.map((row) => (
|
||||
<PreviewRow key={row.key} label={row.label} value={row.value} />
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
{portSlug && clientId && (
|
||||
<div className="border-t pt-2">
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
href={`/${portSlug}/clients/${clientId}` as any}
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{prerequisites[key] ? '✓' : '–'}
|
||||
</span>
|
||||
<span
|
||||
className={prerequisites[key] ? 'text-foreground' : 'text-muted-foreground'}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<Pencil className="size-3" />
|
||||
Wrong details? Edit on the client's page
|
||||
<ExternalLink className="size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||
Couldn't load the EOI preview data. Try closing and reopening the dialog.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!requiredMet ? (
|
||||
<p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||
Add the missing required details on the client's record before generating the
|
||||
EOI.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{!ctxLoading && ctx && !requiredMet && (
|
||||
<p className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||
<AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
|
||||
Add the missing required details on the client's record before generating the
|
||||
EOI.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isGenerating}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleGenerate} disabled={!requiredMet || isGenerating}>
|
||||
<Button onClick={handleGenerate} disabled={!requiredMet || isGenerating || ctxLoading}>
|
||||
{isGenerating ? 'Generating…' : 'Generate EOI'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
@@ -225,3 +323,31 @@ export function EoiGenerateDialog({
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function PreviewRow({
|
||||
label,
|
||||
value,
|
||||
missing = false,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | null;
|
||||
missing?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-baseline gap-2 text-sm">
|
||||
<dt className="w-32 shrink-0 text-xs text-muted-foreground">{label}</dt>
|
||||
<dd
|
||||
className={cn(
|
||||
'flex-1 break-words',
|
||||
missing
|
||||
? 'text-rose-700 font-medium'
|
||||
: value
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground italic',
|
||||
)}
|
||||
>
|
||||
{value ?? (missing ? 'Missing — required' : 'Not set')}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
|
||||
import { Home } from 'lucide-react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
|
||||
interface Props {
|
||||
client: {
|
||||
id: string;
|
||||
fullName: string;
|
||||
status: string;
|
||||
placeOfResidence: string | null;
|
||||
};
|
||||
onSaveName: (next: string | null) => Promise<void>;
|
||||
}
|
||||
|
||||
const STATUS_TONE: Record<string, string> = {
|
||||
prospect: 'bg-blue-100 text-blue-900',
|
||||
active: 'bg-emerald-100 text-emerald-900',
|
||||
inactive: 'bg-muted text-muted-foreground',
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
prospect: 'Prospect',
|
||||
active: 'Active',
|
||||
inactive: 'Inactive',
|
||||
};
|
||||
|
||||
export function ResidentialClientDetailHeader({ client, onSaveName }: Props) {
|
||||
return (
|
||||
<DetailHeaderStrip>
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground inline-flex items-center gap-1.5">
|
||||
<Home className="h-3 w-3" /> Residential client
|
||||
</div>
|
||||
<h1 className="truncate text-2xl font-bold tracking-tight text-foreground">
|
||||
<InlineEditableField value={client.fullName} onSave={onSaveName} />
|
||||
</h1>
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
<Badge className={STATUS_TONE[client.status] ?? 'bg-muted'}>
|
||||
{STATUS_LABEL[client.status] ?? client.status}
|
||||
</Badge>
|
||||
{client.placeOfResidence && <span>{client.placeOfResidence}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</DetailHeaderStrip>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowLeft, Plus } 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 { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
import { InlineCountryField } from '@/components/shared/inline-country-field';
|
||||
import { InlineTimezoneField } from '@/components/shared/inline-timezone-field';
|
||||
import { InlinePhoneField } from '@/components/shared/inline-phone-field';
|
||||
import { SubdivisionCombobox } from '@/components/shared/subdivision-combobox';
|
||||
import { DetailLayout } from '@/components/shared/detail-layout';
|
||||
import { useMobileChrome } from '@/components/layout/mobile/mobile-layout-provider';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useBreadcrumbHint } from '@/hooks/use-breadcrumb-hint';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import type { CountryCode } from '@/lib/i18n/countries';
|
||||
import { ResidentialClientDetailHeader } from '@/components/residential/residential-client-detail-header';
|
||||
import { getResidentialClientTabs } from '@/components/residential/residential-client-tabs';
|
||||
|
||||
interface ResidentialInterestSummary {
|
||||
id: string;
|
||||
@@ -30,7 +21,7 @@ interface ResidentialInterestSummary {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface ResidentialClientDetail {
|
||||
interface ResidentialClient {
|
||||
id: string;
|
||||
fullName: string;
|
||||
email: string | null;
|
||||
@@ -49,45 +40,32 @@ interface ResidentialClientDetail {
|
||||
interests: ResidentialInterestSummary[];
|
||||
}
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'prospect', label: 'Prospect' },
|
||||
{ value: 'active', label: 'Active' },
|
||||
{ value: 'inactive', label: 'Inactive' },
|
||||
];
|
||||
interface Stage {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const CONTACT_OPTIONS = [
|
||||
{ value: 'email', label: 'Email' },
|
||||
{ value: 'phone', label: 'Phone' },
|
||||
];
|
||||
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'website', label: 'Website' },
|
||||
{ value: 'manual', label: 'Manual' },
|
||||
{ value: 'referral', label: 'Referral' },
|
||||
{ value: 'broker', label: 'Broker' },
|
||||
];
|
||||
|
||||
const STAGE_LABELS: Record<string, string> = {
|
||||
new: 'New',
|
||||
contacted: 'Contacted',
|
||||
viewing_scheduled: 'Viewing scheduled',
|
||||
offer_made: 'Offer made',
|
||||
offer_accepted: 'Offer accepted',
|
||||
closed_won: 'Closed - won',
|
||||
closed_lost: 'Closed - lost',
|
||||
};
|
||||
|
||||
export function ResidentialClientDetail({ clientId }: { clientId: string }) {
|
||||
export function ResidentialClientDetail({
|
||||
clientId,
|
||||
currentUserId,
|
||||
}: {
|
||||
clientId: string;
|
||||
currentUserId?: string;
|
||||
}) {
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const qc = useQueryClient();
|
||||
const [newInterestOpen, setNewInterestOpen] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery<{ data: ResidentialClientDetail }>({
|
||||
const { data, isLoading } = useQuery<{ data: ResidentialClient }>({
|
||||
queryKey: ['residential-client', clientId],
|
||||
queryFn: () => apiFetch(`/api/v1/residential/clients/${clientId}`),
|
||||
});
|
||||
|
||||
const { data: stagesData } = useQuery<{ data: { stages: Stage[] } }>({
|
||||
queryKey: ['residential-stages', portSlug],
|
||||
queryFn: () => apiFetch('/api/v1/residential/stages'),
|
||||
});
|
||||
|
||||
useRealtimeInvalidation({
|
||||
'residential_client:updated': [['residential-client', clientId]],
|
||||
'residential_interest:created': [['residential-client', clientId]],
|
||||
@@ -97,266 +75,51 @@ export function ResidentialClientDetail({ clientId }: { clientId: string }) {
|
||||
|
||||
const update = useMutation({
|
||||
mutationFn: (patch: Record<string, unknown>) =>
|
||||
apiFetch(`/api/v1/residential/clients/${clientId}`, {
|
||||
method: 'PATCH',
|
||||
body: patch,
|
||||
}),
|
||||
apiFetch(`/api/v1/residential/clients/${clientId}`, { method: 'PATCH', body: patch }),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['residential-client', clientId] }),
|
||||
});
|
||||
|
||||
const save = (field: string) => async (next: string | null) => {
|
||||
await update.mutateAsync({ [field]: next });
|
||||
};
|
||||
const { setChrome } = useMobileChrome();
|
||||
const titleForChrome = data?.data?.fullName ?? null;
|
||||
useEffect(() => {
|
||||
setChrome({ title: titleForChrome, showBackButton: true });
|
||||
return () => setChrome({ title: null, showBackButton: false });
|
||||
}, [titleForChrome, setChrome]);
|
||||
|
||||
if (isLoading || !data) {
|
||||
return <div className="text-sm text-muted-foreground">Loading…</div>;
|
||||
}
|
||||
const client = data.data;
|
||||
// Topbar breadcrumb hint — Residential › Clients › <name>
|
||||
useBreadcrumbHint(data ? { parents: [], current: data.data.fullName } : null);
|
||||
|
||||
const stageLabels = useMemo(() => {
|
||||
const map: Record<string, string> = {};
|
||||
for (const s of stagesData?.data.stages ?? []) map[s.id] = s.label;
|
||||
return map;
|
||||
}, [stagesData]);
|
||||
|
||||
const tabs = data
|
||||
? getResidentialClientTabs({
|
||||
clientId,
|
||||
client: data.data,
|
||||
portSlug,
|
||||
currentUserId,
|
||||
stageLabels,
|
||||
})
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Link
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
href={`/${portSlug}/residential/clients` as any}
|
||||
className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
|
||||
>
|
||||
<ArrowLeft className="h-3 w-3" /> All residential clients
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-slate-200 bg-gradient-brand-soft px-5 py-4 shadow-xs">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-brand">
|
||||
Residential Client
|
||||
</div>
|
||||
<h1 className="mt-1 truncate text-2xl font-bold tracking-tight text-foreground">
|
||||
<InlineEditableField value={client.fullName} onSave={save('fullName')} />
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Contact</h3>
|
||||
<Row label="Email">
|
||||
<InlineEditableField value={client.email} onSave={save('email')} />
|
||||
</Row>
|
||||
<Row label="Phone">
|
||||
<InlinePhoneField
|
||||
e164={client.phoneE164}
|
||||
country={client.phoneCountry}
|
||||
onSave={async ({ e164, country }) => {
|
||||
await update.mutateAsync({
|
||||
phone: e164,
|
||||
phoneE164: e164,
|
||||
phoneCountry: country,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Preferred contact">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={CONTACT_OPTIONS}
|
||||
value={client.preferredContactMethod}
|
||||
onSave={save('preferredContactMethod')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Nationality">
|
||||
<InlineCountryField
|
||||
value={client.nationalityIso}
|
||||
onSave={async (iso) => {
|
||||
await update.mutateAsync({ nationalityIso: iso });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Timezone">
|
||||
<InlineTimezoneField
|
||||
value={client.timezone}
|
||||
countryHint={(client.nationalityIso as CountryCode | null) ?? null}
|
||||
onSave={async (tz) => {
|
||||
await update.mutateAsync({ timezone: tz });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Place of residence">
|
||||
<InlineEditableField
|
||||
value={client.placeOfResidence}
|
||||
onSave={save('placeOfResidence')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Country of residence">
|
||||
<InlineCountryField
|
||||
value={client.placeOfResidenceCountryIso}
|
||||
onSave={async (iso) => {
|
||||
// When country flips, clear the subdivision - codes are country-scoped.
|
||||
await update.mutateAsync({
|
||||
placeOfResidenceCountryIso: iso,
|
||||
subdivisionIso: null,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Region">
|
||||
<SubdivisionCombobox
|
||||
value={client.subdivisionIso}
|
||||
onChange={(code) => {
|
||||
void update.mutateAsync({ subdivisionIso: code });
|
||||
}}
|
||||
country={(client.placeOfResidenceCountryIso as CountryCode | null) ?? null}
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Status</h3>
|
||||
<Row label="Status">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={STATUS_OPTIONS}
|
||||
value={client.status}
|
||||
onSave={save('status')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Source">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={SOURCE_OPTIONS}
|
||||
value={client.source}
|
||||
onSave={save('source')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Notes">
|
||||
<InlineEditableField value={client.notes} onSave={save('notes')} />
|
||||
</Row>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-card p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Interests</h2>
|
||||
<Button size="sm" onClick={() => setNewInterestOpen(true)}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1.5" />
|
||||
New interest
|
||||
</Button>
|
||||
</div>
|
||||
{client.interests.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No interests yet.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{client.interests.map((i) => (
|
||||
<li key={i.id} className="flex items-center gap-3 p-3 rounded-md border bg-muted/30">
|
||||
<span className="text-xs font-medium uppercase text-muted-foreground w-32 shrink-0">
|
||||
{STAGE_LABELS[i.pipelineStage] ?? i.pipelineStage}
|
||||
</span>
|
||||
<span className="flex-1 truncate text-sm">{i.preferences || i.notes || '-'}</span>
|
||||
<Link
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
href={`/${portSlug}/residential/interests/${i.id}` as any}
|
||||
className="text-xs text-primary hover:underline"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<NewInterestSheet
|
||||
clientId={clientId}
|
||||
open={newInterestOpen}
|
||||
onOpenChange={setNewInterestOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
|
||||
<dt className="w-40 shrink-0 text-sm text-muted-foreground">{label}</dt>
|
||||
<dd className="flex-1 min-w-0">{children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NewInterestSheet({
|
||||
clientId,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
clientId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [preferences, setPreferences] = useState('');
|
||||
const [notes, setNotes] = useState('');
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
apiFetch('/api/v1/residential/interests', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
residentialClientId: clientId,
|
||||
preferences: preferences || undefined,
|
||||
notes: notes || undefined,
|
||||
source: 'manual',
|
||||
},
|
||||
}),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['residential-client', clientId] });
|
||||
onOpenChange(false);
|
||||
setPreferences('');
|
||||
setNotes('');
|
||||
toast.success('Interest added');
|
||||
},
|
||||
onError: (err) => toastError(err),
|
||||
});
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetTitle>New interest</SheetTitle>
|
||||
</SheetHeader>
|
||||
<form
|
||||
className="mt-6 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
create.mutate();
|
||||
}}
|
||||
>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ri-prefs">Preferences</Label>
|
||||
<Input
|
||||
id="ri-prefs"
|
||||
value={preferences}
|
||||
onChange={(e) => setPreferences(e.target.value)}
|
||||
placeholder="Unit type, size, budget…"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ri-notes">Notes</Label>
|
||||
<Input id="ri-notes" value={notes} onChange={(e) => setNotes(e.target.value)} />
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={create.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={create.isPending}>
|
||||
{create.isPending ? 'Saving…' : 'Create'}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<DetailLayout
|
||||
header={
|
||||
data ? (
|
||||
<ResidentialClientDetailHeader
|
||||
client={data.data}
|
||||
onSaveName={async (next) => {
|
||||
await update.mutateAsync({ fullName: next });
|
||||
}}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
tabs={tabs}
|
||||
defaultTab="overview"
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
361
src/components/residential/residential-client-tabs.tsx
Normal file
361
src/components/residential/residential-client-tabs.tsx
Normal file
@@ -0,0 +1,361 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus } from 'lucide-react';
|
||||
|
||||
import type { DetailTab } from '@/components/shared/detail-layout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
import { InlineCountryField } from '@/components/shared/inline-country-field';
|
||||
import { InlineTimezoneField } from '@/components/shared/inline-timezone-field';
|
||||
import { InlinePhoneField } from '@/components/shared/inline-phone-field';
|
||||
import { SubdivisionCombobox } from '@/components/shared/subdivision-combobox';
|
||||
import { NotesList } from '@/components/shared/notes-list';
|
||||
import { EntityActivityFeed } from '@/components/shared/entity-activity-feed';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import type { CountryCode } from '@/lib/i18n/countries';
|
||||
|
||||
interface ResidentialInterestSummary {
|
||||
id: string;
|
||||
pipelineStage: string;
|
||||
source: string | null;
|
||||
notes: string | null;
|
||||
preferences: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface ResidentialClient {
|
||||
id: string;
|
||||
fullName: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
phoneE164: string | null;
|
||||
phoneCountry: string | null;
|
||||
nationalityIso: string | null;
|
||||
timezone: string | null;
|
||||
placeOfResidence: string | null;
|
||||
placeOfResidenceCountryIso: string | null;
|
||||
subdivisionIso: string | null;
|
||||
preferredContactMethod: string | null;
|
||||
status: string;
|
||||
source: string | null;
|
||||
notes: string | null;
|
||||
interests: ResidentialInterestSummary[];
|
||||
}
|
||||
|
||||
interface Args {
|
||||
clientId: string;
|
||||
client: ResidentialClient;
|
||||
portSlug: string;
|
||||
currentUserId?: string;
|
||||
stageLabels: Record<string, string>;
|
||||
}
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'prospect', label: 'Prospect' },
|
||||
{ value: 'active', label: 'Active' },
|
||||
{ value: 'inactive', label: 'Inactive' },
|
||||
];
|
||||
const CONTACT_OPTIONS = [
|
||||
{ value: 'email', label: 'Email' },
|
||||
{ value: 'phone', label: 'Phone' },
|
||||
];
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'website', label: 'Website' },
|
||||
{ value: 'manual', label: 'Manual' },
|
||||
{ value: 'referral', label: 'Referral' },
|
||||
{ value: 'broker', label: 'Broker' },
|
||||
{ value: 'other', label: 'Other' },
|
||||
];
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
|
||||
<dt className="w-44 shrink-0 text-sm text-muted-foreground">{label}</dt>
|
||||
<dd className="flex-1 min-w-0">{children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function getResidentialClientTabs({
|
||||
clientId,
|
||||
client,
|
||||
portSlug,
|
||||
currentUserId,
|
||||
stageLabels,
|
||||
}: Args): DetailTab[] {
|
||||
return [
|
||||
{
|
||||
id: 'overview',
|
||||
label: 'Overview',
|
||||
content: (
|
||||
<OverviewTab
|
||||
clientId={clientId}
|
||||
client={client}
|
||||
portSlug={portSlug}
|
||||
stageLabels={stageLabels}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'interests',
|
||||
label: 'Interests',
|
||||
badge: client.interests.length || undefined,
|
||||
content: (
|
||||
<InterestsTab
|
||||
clientId={clientId}
|
||||
client={client}
|
||||
portSlug={portSlug}
|
||||
stageLabels={stageLabels}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'notes',
|
||||
label: 'Notes',
|
||||
content: (
|
||||
<NotesList
|
||||
entityType="residential_clients"
|
||||
entityId={clientId}
|
||||
currentUserId={currentUserId}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'activity',
|
||||
label: 'Activity',
|
||||
content: (
|
||||
<EntityActivityFeed
|
||||
endpoint={`/api/v1/residential/clients/${clientId}/activity`}
|
||||
emptyText="No activity recorded for this residential client yet."
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function useClientPatch(clientId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (patch: Record<string, unknown>) =>
|
||||
apiFetch(`/api/v1/residential/clients/${clientId}`, { method: 'PATCH', body: patch }),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['residential-client', clientId] }),
|
||||
});
|
||||
}
|
||||
|
||||
function OverviewTab({
|
||||
clientId,
|
||||
client,
|
||||
}: {
|
||||
clientId: string;
|
||||
client: ResidentialClient;
|
||||
portSlug: string;
|
||||
stageLabels: Record<string, string>;
|
||||
}) {
|
||||
const update = useClientPatch(clientId);
|
||||
const save = (field: string) => async (next: string | null) => {
|
||||
await update.mutateAsync({ [field]: next });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6 space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Contact</h3>
|
||||
<Row label="Email">
|
||||
<InlineEditableField value={client.email} onSave={save('email')} />
|
||||
</Row>
|
||||
<Row label="Phone">
|
||||
<InlinePhoneField
|
||||
e164={client.phoneE164}
|
||||
country={client.phoneCountry}
|
||||
onSave={async ({ e164, country }) => {
|
||||
await update.mutateAsync({ phone: e164, phoneE164: e164, phoneCountry: country });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Preferred contact">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={CONTACT_OPTIONS}
|
||||
value={client.preferredContactMethod}
|
||||
onSave={save('preferredContactMethod')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Country">
|
||||
<InlineCountryField
|
||||
value={client.nationalityIso}
|
||||
onSave={async (iso) => {
|
||||
await update.mutateAsync({ nationalityIso: iso });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Timezone">
|
||||
<InlineTimezoneField
|
||||
value={client.timezone}
|
||||
countryHint={(client.nationalityIso as CountryCode | null) ?? null}
|
||||
onSave={async (tz) => {
|
||||
await update.mutateAsync({ timezone: tz });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Place of residence">
|
||||
<InlineEditableField
|
||||
value={client.placeOfResidence}
|
||||
onSave={save('placeOfResidence')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Country of residence">
|
||||
<InlineCountryField
|
||||
value={client.placeOfResidenceCountryIso}
|
||||
onSave={async (iso) => {
|
||||
await update.mutateAsync({ placeOfResidenceCountryIso: iso, subdivisionIso: null });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Region">
|
||||
<SubdivisionCombobox
|
||||
value={client.subdivisionIso}
|
||||
onChange={(code) => {
|
||||
void update.mutateAsync({ subdivisionIso: code });
|
||||
}}
|
||||
country={(client.placeOfResidenceCountryIso as CountryCode | null) ?? null}
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Status</h3>
|
||||
<Row label="Status">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={STATUS_OPTIONS}
|
||||
value={client.status}
|
||||
onSave={save('status')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Source">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={SOURCE_OPTIONS}
|
||||
value={client.source}
|
||||
onSave={save('source')}
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InterestsTab({
|
||||
clientId,
|
||||
client,
|
||||
portSlug,
|
||||
stageLabels,
|
||||
}: {
|
||||
clientId: string;
|
||||
client: ResidentialClient;
|
||||
portSlug: string;
|
||||
stageLabels: Record<string, string>;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Interests</h2>
|
||||
<Button size="sm" onClick={() => setOpen(true)}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1.5" />
|
||||
New interest
|
||||
</Button>
|
||||
</div>
|
||||
{client.interests.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No interests yet.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{client.interests.map((i) => (
|
||||
<li key={i.id} className="flex items-center gap-3 p-3 rounded-md border bg-muted/30">
|
||||
<span className="text-xs font-medium uppercase text-muted-foreground w-32 shrink-0">
|
||||
{stageLabels[i.pipelineStage] ?? i.pipelineStage}
|
||||
</span>
|
||||
<span className="flex-1 truncate text-sm">{i.preferences || i.notes || '-'}</span>
|
||||
<Link
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
href={`/${portSlug}/residential/interests/${i.id}` as any}
|
||||
className="text-xs text-primary hover:underline"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{open && <NewInterestDialog clientId={clientId} open={open} onOpenChange={setOpen} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NewInterestDialog({
|
||||
clientId,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
clientId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [preferences, setPreferences] = useState('');
|
||||
const [notes, setNotes] = useState('');
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
apiFetch('/api/v1/residential/interests', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
residentialClientId: clientId,
|
||||
preferences: preferences || undefined,
|
||||
notes: notes || undefined,
|
||||
source: 'manual',
|
||||
},
|
||||
}),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['residential-client', clientId] });
|
||||
onOpenChange(false);
|
||||
setPreferences('');
|
||||
setNotes('');
|
||||
},
|
||||
});
|
||||
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4">
|
||||
<div className="w-full max-w-md rounded-lg border bg-card p-6 shadow-lg space-y-3">
|
||||
<h3 className="text-sm font-medium">New residential interest</h3>
|
||||
<textarea
|
||||
className="w-full rounded-md border px-3 py-2 text-sm"
|
||||
rows={3}
|
||||
placeholder="Preferences (unit type / size / budget / floor)"
|
||||
value={preferences}
|
||||
onChange={(e) => setPreferences(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
className="w-full rounded-md border px-3 py-2 text-sm"
|
||||
rows={3}
|
||||
placeholder="Initial notes"
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => create.mutate()} disabled={create.isPending}>
|
||||
{create.isPending ? 'Creating…' : 'Create'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -130,8 +130,44 @@ export function ResidentialClientsList() {
|
||||
{c.fullName}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">{c.email ?? '-'}</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">{c.phone ?? '-'}</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">
|
||||
{c.email ? (
|
||||
<a
|
||||
href={`mailto:${c.email}`}
|
||||
className="text-primary hover:underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{c.email}
|
||||
</a>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">
|
||||
{c.phone ? (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<a
|
||||
href={`tel:${c.phone}`}
|
||||
className="text-primary hover:underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{c.phone}
|
||||
</a>
|
||||
<a
|
||||
href={`https://wa.me/${c.phone.replace(/[^\d+]/g, '')}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title="WhatsApp"
|
||||
className="text-emerald-600 hover:text-emerald-700"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
WA
|
||||
</a>
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">{c.placeOfResidence ?? '-'}</td>
|
||||
<td className="px-3 py-2">{STATUS_LABELS[c.status] ?? c.status}</td>
|
||||
<td className="px-3 py-2 capitalize text-muted-foreground">{c.source ?? '-'}</td>
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { DetailLayout } from '@/components/shared/detail-layout';
|
||||
import { DetailHeaderStrip } from '@/components/shared/detail-header-strip';
|
||||
import { useMobileChrome } from '@/components/layout/mobile/mobile-layout-provider';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useBreadcrumbHint } from '@/hooks/use-breadcrumb-hint';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { PIPELINE_STAGES } from '@/lib/validators/residential';
|
||||
import { getResidentialInterestTabs } from '@/components/residential/residential-interest-tabs';
|
||||
|
||||
interface ResidentialInterestDetail {
|
||||
interface ResidentialInterest {
|
||||
id: string;
|
||||
residentialClientId: string;
|
||||
pipelineStage: string;
|
||||
@@ -21,38 +24,33 @@ interface ResidentialInterestDetail {
|
||||
client: { id: string; fullName: string } | null;
|
||||
}
|
||||
|
||||
const STAGE_LABELS: Record<string, string> = {
|
||||
new: 'New',
|
||||
contacted: 'Contacted',
|
||||
viewing_scheduled: 'Viewing scheduled',
|
||||
offer_made: 'Offer made',
|
||||
offer_accepted: 'Offer accepted',
|
||||
closed_won: 'Closed - won',
|
||||
closed_lost: 'Closed - lost',
|
||||
};
|
||||
interface Stage {
|
||||
id: string;
|
||||
label: string;
|
||||
terminal: 'won' | 'lost' | null;
|
||||
}
|
||||
|
||||
const STAGE_OPTIONS = PIPELINE_STAGES.map((s) => ({
|
||||
value: s,
|
||||
label: STAGE_LABELS[s] ?? s,
|
||||
}));
|
||||
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'website', label: 'Website' },
|
||||
{ value: 'manual', label: 'Manual' },
|
||||
{ value: 'referral', label: 'Referral' },
|
||||
{ value: 'broker', label: 'Broker' },
|
||||
];
|
||||
|
||||
export function ResidentialInterestDetail({ interestId }: { interestId: string }) {
|
||||
export function ResidentialInterestDetail({
|
||||
interestId,
|
||||
currentUserId,
|
||||
}: {
|
||||
interestId: string;
|
||||
currentUserId?: string;
|
||||
}) {
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const qc = useQueryClient();
|
||||
|
||||
const { data, isLoading } = useQuery<{ data: ResidentialInterestDetail }>({
|
||||
const { data, isLoading } = useQuery<{ data: ResidentialInterest }>({
|
||||
queryKey: ['residential-interest', interestId],
|
||||
queryFn: () => apiFetch(`/api/v1/residential/interests/${interestId}`),
|
||||
});
|
||||
|
||||
const { data: stagesData } = useQuery<{ data: { stages: Stage[] } }>({
|
||||
queryKey: ['residential-stages', portSlug],
|
||||
queryFn: () => apiFetch('/api/v1/residential/stages'),
|
||||
});
|
||||
|
||||
useRealtimeInvalidation({
|
||||
'residential_interest:updated': [['residential-interest', interestId]],
|
||||
});
|
||||
@@ -65,94 +63,75 @@ export function ResidentialInterestDetail({ interestId }: { interestId: string }
|
||||
}),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['residential-interest', interestId] }),
|
||||
});
|
||||
void update;
|
||||
|
||||
const save = (field: string) => async (next: string | null) => {
|
||||
await update.mutateAsync({ [field]: next });
|
||||
};
|
||||
const { setChrome } = useMobileChrome();
|
||||
const titleForChrome = data?.data?.client?.fullName ?? null;
|
||||
useEffect(() => {
|
||||
setChrome({ title: titleForChrome, showBackButton: true });
|
||||
return () => setChrome({ title: null, showBackButton: false });
|
||||
}, [titleForChrome, setChrome]);
|
||||
|
||||
if (isLoading || !data) {
|
||||
return <div className="text-sm text-muted-foreground">Loading…</div>;
|
||||
}
|
||||
const interest = data.data;
|
||||
// Breadcrumb: Residential › Interests › <client> › <stage>
|
||||
useBreadcrumbHint(
|
||||
data
|
||||
? {
|
||||
parents:
|
||||
data.data.client && data.data.residentialClientId
|
||||
? [
|
||||
{
|
||||
label: data.data.client.fullName,
|
||||
href: `/${portSlug}/residential/clients/${data.data.residentialClientId}`,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
current: 'Interest',
|
||||
}
|
||||
: null,
|
||||
);
|
||||
|
||||
const stageOptions = useMemo(
|
||||
() =>
|
||||
(stagesData?.data.stages ?? []).map((s) => ({
|
||||
value: s.id,
|
||||
label: s.label,
|
||||
})),
|
||||
[stagesData],
|
||||
);
|
||||
const stageLabel = useMemo(() => {
|
||||
const s = stagesData?.data.stages.find((x) => x.id === data?.data.pipelineStage);
|
||||
return s?.label ?? data?.data.pipelineStage ?? '';
|
||||
}, [stagesData, data]);
|
||||
|
||||
const tabs = data
|
||||
? getResidentialInterestTabs({
|
||||
interestId,
|
||||
interest: data.data,
|
||||
currentUserId,
|
||||
stageOptions,
|
||||
})
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Link
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
href={`/${portSlug}/residential/interests` as any}
|
||||
className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
|
||||
>
|
||||
<ArrowLeft className="h-3 w-3" /> All residential interests
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-border bg-gradient-brand-soft px-5 py-4 shadow-xs">
|
||||
<p className="text-xs uppercase font-semibold tracking-wide text-brand">
|
||||
Residential interest
|
||||
</p>
|
||||
{interest.client && (
|
||||
<h1 className="mt-1 truncate text-2xl font-bold tracking-tight text-foreground">
|
||||
<Link
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
href={`/${portSlug}/residential/clients/${interest.client.id}` as any}
|
||||
className="hover:underline"
|
||||
>
|
||||
{interest.client.fullName}
|
||||
</Link>
|
||||
</h1>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Pipeline</h3>
|
||||
<Row label="Stage">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={STAGE_OPTIONS}
|
||||
value={interest.pipelineStage}
|
||||
onSave={save('pipelineStage')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Source">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={SOURCE_OPTIONS}
|
||||
value={interest.source}
|
||||
onSave={save('source')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Assigned to">
|
||||
<InlineEditableField
|
||||
value={interest.assignedTo}
|
||||
onSave={save('assignedTo')}
|
||||
placeholder="user id"
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Details</h3>
|
||||
<Row label="Preferences">
|
||||
<InlineEditableField value={interest.preferences} onSave={save('preferences')} />
|
||||
</Row>
|
||||
<Row label="Notes">
|
||||
<InlineEditableField value={interest.notes} onSave={save('notes')} />
|
||||
</Row>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
|
||||
<dt className="w-40 shrink-0 text-sm text-muted-foreground">{label}</dt>
|
||||
<dd className="flex-1 min-w-0">{children}</dd>
|
||||
</div>
|
||||
<DetailLayout
|
||||
header={
|
||||
data ? (
|
||||
<DetailHeaderStrip>
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Residential interest
|
||||
</div>
|
||||
<h1 className="truncate text-2xl font-bold tracking-tight text-foreground">
|
||||
{data.data.client?.fullName ?? 'Unknown client'}
|
||||
</h1>
|
||||
<Badge variant="outline">{stageLabel}</Badge>
|
||||
</div>
|
||||
</DetailHeaderStrip>
|
||||
) : null
|
||||
}
|
||||
tabs={tabs}
|
||||
defaultTab="overview"
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
171
src/components/residential/residential-interest-tabs.tsx
Normal file
171
src/components/residential/residential-interest-tabs.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
'use client';
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import type { DetailTab } from '@/components/shared/detail-layout';
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
import { NotesList } from '@/components/shared/notes-list';
|
||||
import { EntityActivityFeed } from '@/components/shared/entity-activity-feed';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
interface ResidentialInterest {
|
||||
id: string;
|
||||
residentialClientId: string;
|
||||
pipelineStage: string;
|
||||
source: string | null;
|
||||
notes: string | null;
|
||||
preferences: string | null;
|
||||
assignedTo: string | null;
|
||||
}
|
||||
|
||||
interface Args {
|
||||
interestId: string;
|
||||
interest: ResidentialInterest;
|
||||
currentUserId?: string;
|
||||
stageOptions: Array<{ value: string; label: string }>;
|
||||
}
|
||||
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'website', label: 'Website' },
|
||||
{ value: 'manual', label: 'Manual' },
|
||||
{ value: 'referral', label: 'Referral' },
|
||||
{ value: 'broker', label: 'Broker' },
|
||||
{ value: 'other', label: 'Other' },
|
||||
];
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex gap-2 py-1.5 border-b last:border-0 items-center">
|
||||
<dt className="w-44 shrink-0 text-sm text-muted-foreground">{label}</dt>
|
||||
<dd className="flex-1 min-w-0">{children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function getResidentialInterestTabs({
|
||||
interestId,
|
||||
interest,
|
||||
currentUserId,
|
||||
stageOptions,
|
||||
}: Args): DetailTab[] {
|
||||
return [
|
||||
{
|
||||
id: 'overview',
|
||||
label: 'Overview',
|
||||
content: (
|
||||
<OverviewTab interestId={interestId} interest={interest} stageOptions={stageOptions} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'notes',
|
||||
label: 'Notes',
|
||||
content: (
|
||||
<NotesList
|
||||
entityType="residential_interests"
|
||||
entityId={interestId}
|
||||
currentUserId={currentUserId}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'activity',
|
||||
label: 'Activity',
|
||||
content: (
|
||||
<EntityActivityFeed
|
||||
endpoint={`/api/v1/residential/interests/${interestId}/activity`}
|
||||
emptyText="No activity recorded for this residential interest yet."
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function useInterestPatch(interestId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (patch: Record<string, unknown>) =>
|
||||
apiFetch(`/api/v1/residential/interests/${interestId}`, { method: 'PATCH', body: patch }),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['residential-interest', interestId] }),
|
||||
});
|
||||
}
|
||||
|
||||
function OverviewTab({
|
||||
interestId,
|
||||
interest,
|
||||
stageOptions,
|
||||
}: {
|
||||
interestId: string;
|
||||
interest: ResidentialInterest;
|
||||
stageOptions: Array<{ value: string; label: string }>;
|
||||
}) {
|
||||
const update = useInterestPatch(interestId);
|
||||
const save = (field: string) => async (next: string | null) => {
|
||||
await update.mutateAsync({ [field]: next });
|
||||
};
|
||||
|
||||
// Pull users with residential access for the Assigned-to dropdown.
|
||||
const { data: assignableUsers } = useQuery<{
|
||||
data: Array<{ id: string; name: string; email: string }>;
|
||||
}>({
|
||||
queryKey: ['residential-assignable-users'],
|
||||
queryFn: () => apiFetch('/api/v1/residential/assignable-users'),
|
||||
});
|
||||
const assigneeOptions = (assignableUsers?.data ?? []).map((u) => ({
|
||||
value: u.id,
|
||||
label: u.name || u.email,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6 space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Pipeline</h3>
|
||||
<Row label="Stage">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={stageOptions}
|
||||
value={interest.pipelineStage}
|
||||
onSave={save('pipelineStage')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Source">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={SOURCE_OPTIONS}
|
||||
value={interest.source}
|
||||
onSave={save('source')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Assigned to">
|
||||
<InlineEditableField
|
||||
variant="select"
|
||||
options={assigneeOptions}
|
||||
value={interest.assignedTo}
|
||||
onSave={save('assignedTo')}
|
||||
placeholder="Unassigned"
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium mb-2">Details</h3>
|
||||
<Row label="Preferences">
|
||||
<InlineEditableField
|
||||
variant="textarea"
|
||||
value={interest.preferences}
|
||||
onSave={save('preferences')}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Initial brief">
|
||||
<InlineEditableField
|
||||
variant="textarea"
|
||||
value={interest.notes}
|
||||
onSave={save('notes')}
|
||||
emptyText="-"
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export function ResidentialInterestsList() {
|
||||
placeholder="Search notes / preferences…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm"
|
||||
className="max-w-sm h-9"
|
||||
/>
|
||||
<Select value={stage} onValueChange={setStage}>
|
||||
<SelectTrigger className="w-52">
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Save } from 'lucide-react';
|
||||
import { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import { Save, KeyRound, Globe, Upload } from 'lucide-react';
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { CountryCombobox } from '@/components/shared/country-combobox';
|
||||
import { TimezoneCombobox } from '@/components/shared/timezone-combobox';
|
||||
import { ImageCropperDialog } from '@/components/shared/image-cropper-dialog';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { primaryTimezoneFor } from '@/lib/i18n/timezones';
|
||||
import type { CountryCode } from '@/lib/i18n/countries';
|
||||
|
||||
interface NotificationPrefs {
|
||||
reminder_due: boolean;
|
||||
@@ -21,13 +27,41 @@ interface NotificationPrefs {
|
||||
[key: string]: boolean;
|
||||
}
|
||||
|
||||
interface MeResponse {
|
||||
user?: { name: string; email: string };
|
||||
preferences?: { country?: string; timezone?: string };
|
||||
profile?: { avatarFileId?: string | null };
|
||||
}
|
||||
|
||||
export function UserSettings() {
|
||||
const [notifPrefs, setNotifPrefs] = useState<NotificationPrefs | null>(null);
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [timezone, setTimezone] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [originalEmail, setOriginalEmail] = useState('');
|
||||
const [country, setCountry] = useState<string | null>(null);
|
||||
const [timezone, setTimezone] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [resetMsg, setResetMsg] = useState<string | null>(null);
|
||||
const [emailMsg, setEmailMsg] = useState<string | null>(null);
|
||||
const [avatarFileId, setAvatarFileId] = useState<string | null>(null);
|
||||
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
||||
const [pendingAvatarFile, setPendingAvatarFile] = useState<File | null>(null);
|
||||
const [cropperOpen, setCropperOpen] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Browser-detected timezone — surfaces a banner when the rep is
|
||||
// travelling and the saved value no longer matches their device's
|
||||
// locale. Quietly absent in SSR; the picker still works without it.
|
||||
const detectedTz = useMemo(() => {
|
||||
if (typeof Intl === 'undefined') return null;
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadProfile();
|
||||
@@ -35,10 +69,35 @@ export function UserSettings() {
|
||||
}, []);
|
||||
|
||||
async function loadProfile() {
|
||||
const res = await apiFetch<{ data: { user?: { name: string } } }>('/api/v1/me', {
|
||||
method: 'GET',
|
||||
});
|
||||
const res = await apiFetch<{ data: MeResponse }>('/api/v1/me', { method: 'GET' });
|
||||
setDisplayName(res.data.user?.name ?? '');
|
||||
setEmail(res.data.user?.email ?? '');
|
||||
setOriginalEmail(res.data.user?.email ?? '');
|
||||
setCountry(res.data.preferences?.country ?? null);
|
||||
setTimezone(res.data.preferences?.timezone ?? null);
|
||||
const fid = res.data.profile?.avatarFileId ?? null;
|
||||
setAvatarFileId(fid);
|
||||
setAvatarUrl(fid ? `/api/v1/files/${fid}/preview` : null);
|
||||
}
|
||||
|
||||
function handleAvatarPicked(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0] ?? null;
|
||||
if (!file) return;
|
||||
setPendingAvatarFile(file);
|
||||
setCropperOpen(true);
|
||||
// Reset so picking the same file twice still triggers onChange.
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
}
|
||||
|
||||
async function uploadAvatar(blob: Blob) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', new File([blob], 'avatar.jpg', { type: 'image/jpeg' }));
|
||||
const res = await fetch('/api/v1/me/avatar', { method: 'POST', body: fd });
|
||||
if (!res.ok) throw new Error('Avatar upload failed');
|
||||
const json = (await res.json()) as { data: { avatarFileId: string } };
|
||||
setAvatarFileId(json.data.avatarFileId);
|
||||
// Cache-bust the preview URL with a query so the new image renders.
|
||||
setAvatarUrl(`/api/v1/files/${json.data.avatarFileId}/preview?t=${Date.now()}`);
|
||||
}
|
||||
|
||||
async function loadNotificationPrefs() {
|
||||
@@ -46,7 +105,6 @@ export function UserSettings() {
|
||||
const res = await apiFetch<{ data: NotificationPrefs }>('/api/v1/notifications/preferences');
|
||||
setNotifPrefs(res.data);
|
||||
} catch {
|
||||
// Preferences may not exist yet
|
||||
setNotifPrefs({
|
||||
reminder_due: true,
|
||||
reminder_overdue: true,
|
||||
@@ -58,6 +116,16 @@ export function UserSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleCountryChange(iso: string | null) {
|
||||
setCountry(iso);
|
||||
// Auto-default timezone when the rep picks a country and hasn't
|
||||
// explicitly set a timezone yet. Same trick as the client overview.
|
||||
if (iso && !timezone) {
|
||||
const tz = primaryTimezoneFor(iso as CountryCode);
|
||||
if (tz) setTimezone(tz);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveProfile() {
|
||||
setSaving('profile');
|
||||
setMessage(null);
|
||||
@@ -67,7 +135,10 @@ export function UserSettings() {
|
||||
body: {
|
||||
displayName: displayName || undefined,
|
||||
phone: phone || null,
|
||||
preferences: { timezone: timezone || undefined },
|
||||
preferences: {
|
||||
country: country ?? undefined,
|
||||
timezone: timezone ?? undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
setMessage('Profile saved');
|
||||
@@ -78,6 +149,34 @@ export function UserSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
async function saveEmail() {
|
||||
if (email === originalEmail) return;
|
||||
setSaving('email');
|
||||
setEmailMsg(null);
|
||||
try {
|
||||
await apiFetch('/api/v1/me/email', { method: 'PATCH', body: { email } });
|
||||
setOriginalEmail(email);
|
||||
setEmailMsg('Email updated. Use the new address next time you sign in.');
|
||||
} catch (err: unknown) {
|
||||
setEmailMsg(err instanceof Error ? err.message : 'Failed to update email');
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestPasswordReset() {
|
||||
setSaving('password');
|
||||
setResetMsg(null);
|
||||
try {
|
||||
await apiFetch('/api/v1/me/password-reset', { method: 'POST' });
|
||||
setResetMsg('Password-reset email sent. Check your inbox.');
|
||||
} catch (err: unknown) {
|
||||
setResetMsg(err instanceof Error ? err.message : 'Failed to send reset email');
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleNotifPref(key: string, value: boolean) {
|
||||
setSaving(key);
|
||||
try {
|
||||
@@ -91,6 +190,10 @@ export function UserSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
function adoptDetectedTz() {
|
||||
if (detectedTz) setTimezone(detectedTz);
|
||||
}
|
||||
|
||||
const NOTIF_LABELS: Record<string, string> = {
|
||||
reminder_due: 'Reminder due',
|
||||
reminder_overdue: 'Reminder overdue',
|
||||
@@ -100,6 +203,8 @@ export function UserSettings() {
|
||||
duplicate_alert: 'Duplicate client detected',
|
||||
};
|
||||
|
||||
const tzMismatch = detectedTz && timezone && detectedTz !== timezone;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader title="Settings" description="Manage your profile and notification preferences" />
|
||||
@@ -111,8 +216,42 @@ export function UserSettings() {
|
||||
<CardDescription>Update your display name and contact info</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Avatar — click the photo to pick a file, which opens the
|
||||
cropper. Cropped result uploads via /api/v1/me/avatar. */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Avatar className="h-16 w-16">
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt="Profile photo" /> : null}
|
||||
<AvatarFallback>
|
||||
{(displayName || email || 'U').slice(0, 1).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-sm">Profile photo</Label>
|
||||
<div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="mr-1.5 h-3.5 w-3.5" />
|
||||
{avatarFileId ? 'Replace photo' : 'Upload photo'}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
onChange={handleAvatarPicked}
|
||||
className="hidden"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
PNG, JPG, or WebP up to 2 MB. You'll be able to crop after picking.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="settings-name">Display Name</Label>
|
||||
<Label htmlFor="settings-name">Display name</Label>
|
||||
<Input
|
||||
id="settings-name"
|
||||
value={displayName}
|
||||
@@ -131,24 +270,97 @@ export function UserSettings() {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="settings-tz">Timezone</Label>
|
||||
<Input
|
||||
id="settings-tz"
|
||||
<Label>Country</Label>
|
||||
<CountryCombobox value={country} onChange={handleCountryChange} />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Sets the default timezone when you pick a country and haven't chosen one
|
||||
explicitly.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Timezone</Label>
|
||||
<TimezoneCombobox
|
||||
value={timezone}
|
||||
onChange={(e) => setTimezone(e.target.value)}
|
||||
placeholder="America/Anguilla"
|
||||
onChange={setTimezone}
|
||||
countryHint={(country as CountryCode | null) ?? undefined}
|
||||
/>
|
||||
{tzMismatch && (
|
||||
<div className="flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||
<Globe className="h-3.5 w-3.5 shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
Looks like you're in <strong>{detectedTz}</strong> right now (saved:{' '}
|
||||
{timezone}).
|
||||
<button
|
||||
type="button"
|
||||
onClick={adoptDetectedTz}
|
||||
className="ml-1 underline underline-offset-2 hover:no-underline"
|
||||
>
|
||||
Update?
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button onClick={saveProfile} disabled={saving === 'profile'}>
|
||||
<Save className="mr-1.5 h-4 w-4" />
|
||||
{saving === 'profile' ? 'Saving...' : 'Save Profile'}
|
||||
{saving === 'profile' ? 'Saving…' : 'Save profile'}
|
||||
</Button>
|
||||
{message && <span className="text-sm text-muted-foreground">{message}</span>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Account</CardTitle>
|
||||
<CardDescription>Sign-in email and password</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="settings-email">Email</Label>
|
||||
<Input
|
||||
id="settings-email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={saveEmail}
|
||||
disabled={saving === 'email' || email === originalEmail || !email}
|
||||
>
|
||||
{saving === 'email' ? 'Updating…' : 'Update email'}
|
||||
</Button>
|
||||
{emailMsg && <span className="text-xs text-muted-foreground">{emailMsg}</span>}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Changing your email also changes the address you use to sign in.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2 pt-2 border-t">
|
||||
<Label>Password</Label>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={requestPasswordReset}
|
||||
disabled={saving === 'password'}
|
||||
>
|
||||
<KeyRound className="mr-1.5 h-3.5 w-3.5" />
|
||||
{saving === 'password' ? 'Sending…' : 'Send reset email'}
|
||||
</Button>
|
||||
{resetMsg && <span className="text-xs text-muted-foreground">{resetMsg}</span>}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
We'll email you a link to set a new password.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Notifications</CardTitle>
|
||||
@@ -169,6 +381,16 @@ export function UserSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<ImageCropperDialog
|
||||
open={cropperOpen}
|
||||
onOpenChange={setCropperOpen}
|
||||
file={pendingAvatarFile}
|
||||
aspect={1}
|
||||
outputWidth={256}
|
||||
title="Crop profile photo"
|
||||
onUpload={uploadAvatar}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
194
src/components/shared/image-cropper-dialog.tsx
Normal file
194
src/components/shared/image-cropper-dialog.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import Cropper, { type Area } from 'react-easy-crop';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
|
||||
export interface ImageCropperDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** The picked file (raw, pre-crop). Cropper renders an object URL. */
|
||||
file: File | null;
|
||||
/** Aspect ratio for the crop frame. 1 = square (avatars), 4 = wide
|
||||
* banners. Defaults to 1. */
|
||||
aspect?: number;
|
||||
/** Output JPEG quality 0-1. Default 0.85. */
|
||||
outputQuality?: number;
|
||||
/** Output width in pixels (height derived from aspect). Default 512. */
|
||||
outputWidth?: number;
|
||||
/** Async upload handler — receives the cropped Blob. Cropper closes on
|
||||
* success; toasts on error. */
|
||||
onUpload: (blob: Blob) => Promise<void>;
|
||||
/** Dialog title. Default "Crop image". */
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable crop-then-upload modal. Renders a draggable/zoomable crop
|
||||
* frame over the picked file, then writes the cropped pixels to a
|
||||
* Canvas, exports as JPEG, and hands the Blob to the caller.
|
||||
*
|
||||
* Used for: profile avatars, port logos, brochure covers — anywhere a
|
||||
* square or fixed-aspect image needs to land in storage.
|
||||
*/
|
||||
export function ImageCropperDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
file,
|
||||
aspect = 1,
|
||||
outputQuality = 0.85,
|
||||
outputWidth = 512,
|
||||
onUpload,
|
||||
title = 'Crop image',
|
||||
}: ImageCropperDialogProps) {
|
||||
const [crop, setCrop] = useState({ x: 0, y: 0 });
|
||||
const [zoom, setZoom] = useState(1);
|
||||
const [pixels, setPixels] = useState<Area | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const objectUrl = file ? URL.createObjectURL(file) : null;
|
||||
|
||||
const onCropComplete = useCallback((_area: Area, areaPixels: Area) => {
|
||||
setPixels(areaPixels);
|
||||
}, []);
|
||||
|
||||
async function handleUpload() {
|
||||
if (!objectUrl || !pixels) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const blob = await renderCrop(objectUrl, pixels, aspect, outputWidth, outputQuality);
|
||||
await onUpload(blob);
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
toastError(err);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose(o: boolean) {
|
||||
if (!o && objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
onOpenChange(o);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{objectUrl && (
|
||||
<>
|
||||
<div className="relative h-72 w-full bg-muted rounded-md overflow-hidden">
|
||||
<Cropper
|
||||
image={objectUrl}
|
||||
crop={crop}
|
||||
zoom={zoom}
|
||||
aspect={aspect}
|
||||
onCropChange={setCrop}
|
||||
onZoomChange={setZoom}
|
||||
onCropComplete={onCropComplete}
|
||||
cropShape={aspect === 1 ? 'round' : 'rect'}
|
||||
showGrid={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 pt-2">
|
||||
<Label htmlFor="cropper-zoom" className="text-xs text-muted-foreground">
|
||||
Zoom
|
||||
</Label>
|
||||
<input
|
||||
id="cropper-zoom"
|
||||
type="range"
|
||||
min={1}
|
||||
max={3}
|
||||
step={0.05}
|
||||
value={zoom}
|
||||
onChange={(e) => setZoom(Number(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => handleClose(false)} disabled={uploading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleUpload} disabled={uploading || !pixels}>
|
||||
{uploading ? (
|
||||
<>
|
||||
<Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
|
||||
Uploading…
|
||||
</>
|
||||
) : (
|
||||
'Save'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Crop the source image at `pixels`, resize to `outputWidth`×
|
||||
* (outputWidth/aspect), and return as a JPEG Blob. Async because
|
||||
* <img> needs an onload event before we can drawImage.
|
||||
*/
|
||||
async function renderCrop(
|
||||
src: string,
|
||||
pixels: Area,
|
||||
aspect: number,
|
||||
outputWidth: number,
|
||||
quality: number,
|
||||
): Promise<Blob> {
|
||||
const image = await loadImage(src);
|
||||
const canvas = document.createElement('canvas');
|
||||
const outputHeight = Math.round(outputWidth / aspect);
|
||||
canvas.width = outputWidth;
|
||||
canvas.height = outputHeight;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas 2d context unavailable');
|
||||
ctx.drawImage(
|
||||
image,
|
||||
pixels.x,
|
||||
pixels.y,
|
||||
pixels.width,
|
||||
pixels.height,
|
||||
0,
|
||||
0,
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
);
|
||||
return await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(b) => (b ? resolve(b) : reject(new Error('Canvas toBlob returned null'))),
|
||||
'image/jpeg',
|
||||
quality,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function loadImage(src: string): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = (e) => reject(e);
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
@@ -4,11 +4,7 @@ import { useState } from 'react';
|
||||
import { Check, ChevronsUpDown, X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
@@ -62,8 +58,9 @@ export function TagPicker({
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
size="sm"
|
||||
aria-expanded={open}
|
||||
className="w-full justify-between font-normal"
|
||||
className="w-full justify-between font-normal h-8"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
{selectedIds.length > 0
|
||||
@@ -77,15 +74,10 @@ export function TagPicker({
|
||||
<Command>
|
||||
<CommandInput placeholder="Search tags..." />
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{isLoading ? 'Loading...' : 'No tags found.'}
|
||||
</CommandEmpty>
|
||||
<CommandEmpty>{isLoading ? 'Loading...' : 'No tags found.'}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{tagOptions.map((tag) => (
|
||||
<CommandItem
|
||||
key={tag.value}
|
||||
onSelect={() => toggleTag(tag.value)}
|
||||
>
|
||||
<CommandItem key={tag.value} onSelect={() => toggleTag(tag.value)}>
|
||||
<Check
|
||||
className={`mr-2 h-4 w-4 ${
|
||||
selectedIds.includes(tag.value) ? 'opacity-100' : 'opacity-0'
|
||||
|
||||
Reference in New Issue
Block a user