fix(audit-wave-9): standardize on Sheet for previews; doctrine in CLAUDE.md
Swap the one outlier (client-interests-tab.tsx) from Vaul Drawer to Sheet side=right so every detail-preview surface uses the same primitive. Document the doctrine: Sheet for side panels on both desktop and mobile; Vaul Drawer reserved for mobile-only bottom-sheet UX (currently just MoreSheet). Closes ui/ux M11. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
@@ -40,19 +40,32 @@ export function AiBudgetCard() {
|
||||
queryKey,
|
||||
queryFn: () => apiFetch<BudgetResp>('/api/v1/admin/ai-budget'),
|
||||
});
|
||||
// Key-based remount: the form body is keyed on the loaded payload
|
||||
// signature so its useState initializers seed from server data on
|
||||
// first load. Replaces the prior useEffect(setState, [data]) sync.
|
||||
const sig = data?.data
|
||||
? `${data.data.budget.enabled}:${data.data.budget.softCapTokens}:${data.data.budget.hardCapTokens}:${data.data.budget.period}`
|
||||
: 'loading';
|
||||
return (
|
||||
<AiBudgetCardBody key={sig} data={data} isLoading={isLoading} qc={qc} queryKey={queryKey} />
|
||||
);
|
||||
}
|
||||
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [softCap, setSoftCap] = useState('100000');
|
||||
const [hardCap, setHardCap] = useState('500000');
|
||||
const [period, setPeriod] = useState<Period>('month');
|
||||
|
||||
useEffect(() => {
|
||||
if (!data?.data) return;
|
||||
setEnabled(data.data.budget.enabled);
|
||||
setSoftCap(String(data.data.budget.softCapTokens));
|
||||
setHardCap(String(data.data.budget.hardCapTokens));
|
||||
setPeriod(data.data.budget.period);
|
||||
}, [data?.data]);
|
||||
function AiBudgetCardBody({
|
||||
data,
|
||||
isLoading,
|
||||
qc,
|
||||
queryKey,
|
||||
}: {
|
||||
data: BudgetResp | undefined;
|
||||
isLoading: boolean;
|
||||
qc: ReturnType<typeof useQueryClient>;
|
||||
queryKey: string[];
|
||||
}) {
|
||||
const [enabled, setEnabled] = useState(data?.data.budget.enabled ?? false);
|
||||
const [softCap, setSoftCap] = useState(data ? String(data.data.budget.softCapTokens) : '100000');
|
||||
const [hardCap, setHardCap] = useState(data ? String(data.data.budget.hardCapTokens) : '500000');
|
||||
const [period, setPeriod] = useState<Period>(data?.data.budget.period ?? 'month');
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: () =>
|
||||
|
||||
@@ -187,6 +187,11 @@ export function AuditLogList() {
|
||||
}, [queryString, nextCursor]);
|
||||
|
||||
useEffect(() => {
|
||||
// Refetch on filter change. Migrating this list to useInfiniteQuery
|
||||
// would be the proper fix but is deferred — the fetch-on-effect
|
||||
// pattern here is functionally correct and gated by the queryString
|
||||
// memo so it only fires when filters actually change.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void fetchFirstPage();
|
||||
}, [fetchFirstPage]);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { toast } from 'sonner';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
|
||||
const ACCEPT = 'image/png,image/jpeg,image/webp,image/svg+xml,image/heic,image/heif,image/avif';
|
||||
|
||||
@@ -54,6 +55,7 @@ function centeredCrop(width: number, height: number, aspect: number): Crop {
|
||||
}
|
||||
|
||||
export function PdfLogoUploader() {
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
const [current, setCurrent] = useState<CurrentLogo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [working, setWorking] = useState(false);
|
||||
@@ -160,7 +162,12 @@ export function PdfLogoUploader() {
|
||||
}
|
||||
|
||||
async function clear() {
|
||||
if (!confirm('Remove the PDF logo? Future reports will fall back to the port name.')) return;
|
||||
const ok = await confirm({
|
||||
title: 'Remove PDF logo',
|
||||
description: 'Remove the PDF logo? Future reports will fall back to the port name.',
|
||||
confirmLabel: 'Remove',
|
||||
});
|
||||
if (!ok) return;
|
||||
setWorking(true);
|
||||
try {
|
||||
const res = await fetch('/api/v1/admin/branding/logo', { method: 'DELETE' });
|
||||
@@ -334,6 +341,7 @@ export function PdfLogoUploader() {
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{confirmDialog}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
import { formatErrorBanner } from '@/lib/api/toast-error';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Plus, X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -60,7 +60,18 @@ const FIELD_TYPE_LABELS: Record<string, string> = {
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function CustomFieldForm({ open, onOpenChange, field, onSuccess }: CustomFieldFormProps) {
|
||||
export function CustomFieldForm(props: CustomFieldFormProps) {
|
||||
// Key-based remount: the body is keyed on open + field.id so its
|
||||
// useState initializers re-seed each time the dialog opens.
|
||||
return (
|
||||
<CustomFieldFormBody
|
||||
key={props.open ? `open:${props.field?.id ?? 'new'}` : 'closed'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomFieldFormBody({ open, onOpenChange, field, onSuccess }: CustomFieldFormProps) {
|
||||
const isEdit = !!field;
|
||||
|
||||
// Form state
|
||||
@@ -75,20 +86,7 @@ export function CustomFieldForm({ open, onOpenChange, field, onSuccess }: Custom
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Reset state when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setEntityType(field?.entityType ?? 'client');
|
||||
setFieldName(field?.fieldName ?? '');
|
||||
setFieldLabel(field?.fieldLabel ?? '');
|
||||
setFieldType(field?.fieldType ?? 'text');
|
||||
setSelectOptions(field?.selectOptions ?? []);
|
||||
setNewOption('');
|
||||
setIsRequired(field?.isRequired ?? false);
|
||||
setSortOrder(field?.sortOrder ?? 0);
|
||||
setError(null);
|
||||
}
|
||||
}, [open, field]);
|
||||
// Reset is handled by the parent key-based remount above.
|
||||
|
||||
// ── Select options management ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { CustomFieldForm, type CustomFieldDefinition } from './custom-field-form';
|
||||
|
||||
@@ -164,15 +165,16 @@ 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, and merge-tokens of the form{' '}
|
||||
<code className="rounded bg-amber-100 px-1">{`{{custom.fieldName}}`}</code> now expand in
|
||||
EOI/contract/email templates for client/interest/berth contexts. They still don’t plug
|
||||
into the global search index, the berth recommender, or the entity-diff audit log — use them
|
||||
for rep-only annotations and template-merge values, but anything load-bearing for the deal
|
||||
flow still needs a first-class column.
|
||||
</div>
|
||||
<WarningCallout title="Heads up">
|
||||
<span className="text-xs">
|
||||
Custom fields render in detail-page sidebars and the entity export, and merge-tokens of
|
||||
the form <code className="rounded bg-amber-100 px-1">{`{{custom.fieldName}}`}</code> now
|
||||
expand in EOI/contract/email templates for client/interest/berth contexts. They still
|
||||
don’t plug into the global search index, the berth recommender, or the entity-diff
|
||||
audit log — use them for rep-only annotations and template-merge values, but anything
|
||||
load-bearing for the deal flow still needs a first-class column.
|
||||
</span>
|
||||
</WarningCallout>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as EntityTab)}>
|
||||
<TabsList>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { RotateCcw, Clock } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
|
||||
interface TemplateVersion {
|
||||
version: number;
|
||||
@@ -27,6 +28,7 @@ export function TemplateVersionHistory({
|
||||
onRollback,
|
||||
}: TemplateVersionHistoryProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
const queryKey = ['admin', 'template-versions', templateId] as const;
|
||||
const [rollingBack, setRollingBack] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -47,12 +49,12 @@ export function TemplateVersionHistory({
|
||||
const effectiveError = error ?? (queryError instanceof Error ? queryError.message : null);
|
||||
|
||||
async function handleRollback(version: number) {
|
||||
if (
|
||||
!confirm(
|
||||
`Roll back to version ${version}? This will create a new version ${currentVersion + 1}.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
const ok = await confirm({
|
||||
title: `Roll back to version ${version}`,
|
||||
description: `This will create a new version ${currentVersion + 1}.`,
|
||||
confirmLabel: 'Restore',
|
||||
});
|
||||
if (!ok) return;
|
||||
|
||||
setRollingBack(version);
|
||||
setError(null);
|
||||
@@ -133,6 +135,7 @@ export function TemplateVersionHistory({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { RotateCcw, Save } from 'lucide-react';
|
||||
|
||||
@@ -27,23 +27,40 @@ export function EmailTemplatesAdmin() {
|
||||
queryKey: ['admin-email-templates'],
|
||||
queryFn: () => apiFetch<{ data: TemplateRow[] }>('/api/v1/admin/email-templates'),
|
||||
});
|
||||
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<{ key: string; kind: 'ok' | 'err'; text: string } | null>(
|
||||
null,
|
||||
// Key-based remount: re-mount the body when the server-loaded row
|
||||
// signature changes so its useState seeds from fresh server data.
|
||||
// Replaces the prior useEffect(setDrafts, [rows]) sync.
|
||||
const sig = data?.data
|
||||
? data.data.map((r) => `${r.key}:${r.subjectOverride ?? r.defaultSubject}`).join('|')
|
||||
: 'loading';
|
||||
return (
|
||||
<EmailTemplatesAdminBody key={sig} data={data} isLoading={isLoading} error={error} qc={qc} />
|
||||
);
|
||||
}
|
||||
|
||||
function EmailTemplatesAdminBody({
|
||||
data,
|
||||
isLoading,
|
||||
error,
|
||||
qc,
|
||||
}: {
|
||||
data: { data: TemplateRow[] } | undefined;
|
||||
isLoading: boolean;
|
||||
error: unknown;
|
||||
qc: ReturnType<typeof useQueryClient>;
|
||||
}) {
|
||||
const rows = useMemo(() => data?.data ?? [], [data]);
|
||||
|
||||
useEffect(() => {
|
||||
// Hydrate drafts from server values whenever the source-of-truth list refreshes.
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>(() => {
|
||||
const next: Record<string, string> = {};
|
||||
for (const row of rows) {
|
||||
next[row.key] = row.subjectOverride ?? row.defaultSubject;
|
||||
}
|
||||
setDrafts(next);
|
||||
}, [rows]);
|
||||
return next;
|
||||
});
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<{ key: string; kind: 'ok' | 'err'; text: string } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
async function save(row: TemplateRow, mode: 'save' | 'reset') {
|
||||
setSavingKey(row.key);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -54,25 +54,23 @@ const FIELD_TYPES: Array<{ value: FormField['type']; label: string }> = [
|
||||
{ value: 'checkbox', label: 'Checkbox' },
|
||||
];
|
||||
|
||||
export function FormTemplateForm({ open, onOpenChange, template, onSaved }: Props) {
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
const [fields, setFields] = useState<FormField[]>([{ ...DEFAULT_FIELD }]);
|
||||
export function FormTemplateForm(props: Props) {
|
||||
// Key-based remount seeds state on each open + template change.
|
||||
return (
|
||||
<FormTemplateFormBody
|
||||
key={props.open ? `open:${props.template?.id ?? 'new'}` : 'closed'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (template) {
|
||||
setName(template.name);
|
||||
setDescription(template.description ?? '');
|
||||
setIsActive(template.isActive);
|
||||
setFields(template.fields.length > 0 ? template.fields : [{ ...DEFAULT_FIELD }]);
|
||||
} else {
|
||||
setName('');
|
||||
setDescription('');
|
||||
setIsActive(true);
|
||||
setFields([{ ...DEFAULT_FIELD }]);
|
||||
}
|
||||
}, [template, open]);
|
||||
function FormTemplateFormBody({ open, onOpenChange, template, onSaved }: Props) {
|
||||
const [name, setName] = useState(template?.name ?? '');
|
||||
const [description, setDescription] = useState(template?.description ?? '');
|
||||
const [isActive, setIsActive] = useState(template?.isActive ?? true);
|
||||
const [fields, setFields] = useState<FormField[]>(
|
||||
template && template.fields.length > 0 ? template.fields : [{ ...DEFAULT_FIELD }],
|
||||
);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { CheckCircle2, Eye, EyeOff, Loader2, XCircle } from 'lucide-react';
|
||||
|
||||
@@ -44,33 +44,55 @@ interface SettingsBlockProps {
|
||||
showUseGlobal?: boolean;
|
||||
}
|
||||
|
||||
function SettingsBlock({ scope, title, description, showUseGlobal }: SettingsBlockProps) {
|
||||
function SettingsBlock(props: SettingsBlockProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const queryKey = ['ocr-settings', scope];
|
||||
|
||||
const queryKey = ['ocr-settings', props.scope];
|
||||
const { data, isLoading } = useQuery<ConfigResp>({
|
||||
queryKey,
|
||||
queryFn: () => apiFetch<ConfigResp>(`/api/v1/admin/ocr-settings?scope=${scope}`),
|
||||
queryFn: () => apiFetch<ConfigResp>(`/api/v1/admin/ocr-settings?scope=${props.scope}`),
|
||||
});
|
||||
// Key the body on the loaded payload so useState initializers seed
|
||||
// from server values cleanly.
|
||||
const sig = data?.data
|
||||
? `${data.data.provider}:${data.data.model}:${data.data.useGlobal}:${data.data.aiEnabled}`
|
||||
: 'loading';
|
||||
return (
|
||||
<SettingsBlockBody
|
||||
key={sig}
|
||||
{...props}
|
||||
data={data}
|
||||
isLoading={isLoading}
|
||||
queryClient={queryClient}
|
||||
queryKey={queryKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const [provider, setProvider] = useState<Provider>('openai');
|
||||
const [model, setModel] = useState<string>('gpt-4o-mini');
|
||||
function SettingsBlockBody({
|
||||
scope,
|
||||
title,
|
||||
description,
|
||||
showUseGlobal,
|
||||
data,
|
||||
isLoading,
|
||||
queryClient,
|
||||
queryKey,
|
||||
}: SettingsBlockProps & {
|
||||
data: ConfigResp | undefined;
|
||||
isLoading: boolean;
|
||||
queryClient: ReturnType<typeof useQueryClient>;
|
||||
queryKey: (string | Scope)[];
|
||||
}) {
|
||||
const [provider, setProvider] = useState<Provider>(data?.data.provider ?? 'openai');
|
||||
const [model, setModel] = useState<string>(data?.data.model ?? 'gpt-4o-mini');
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
const [useGlobal, setUseGlobal] = useState(false);
|
||||
const [aiEnabled, setAiEnabled] = useState(false);
|
||||
const [useGlobal, setUseGlobal] = useState(data?.data.useGlobal ?? false);
|
||||
const [aiEnabled, setAiEnabled] = useState(data?.data.aiEnabled ?? false);
|
||||
const [testStatus, setTestStatus] = useState<null | { ok: true } | { ok: false; reason: string }>(
|
||||
null,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!data?.data) return;
|
||||
setProvider(data.data.provider);
|
||||
setModel(data.data.model);
|
||||
setUseGlobal(data.data.useGlobal);
|
||||
setAiEnabled(data.data.aiEnabled);
|
||||
}, [data?.data]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (clearApiKey?: boolean) =>
|
||||
apiFetch('/api/v1/admin/ocr-settings', {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
import { formatErrorBanner } from '@/lib/api/toast-error';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -50,39 +50,24 @@ interface PortFormProps {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export function PortForm({ open, onOpenChange, port, onSuccess }: PortFormProps) {
|
||||
const [name, setName] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
const [primaryColor, setPrimaryColor] = useState('#0F4C81');
|
||||
const [defaultCurrency, setDefaultCurrency] = useState('USD');
|
||||
const [timezone, setTimezone] = useState('America/Anguilla');
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
export function PortForm(props: PortFormProps) {
|
||||
return (
|
||||
<PortFormBody key={props.open ? `open:${props.port?.id ?? 'new'}` : 'closed'} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function PortFormBody({ open, onOpenChange, port, onSuccess }: PortFormProps) {
|
||||
const [name, setName] = useState(port?.name ?? '');
|
||||
const [slug, setSlug] = useState(port?.slug ?? '');
|
||||
const [primaryColor, setPrimaryColor] = useState(port?.primaryColor ?? '#0F4C81');
|
||||
const [defaultCurrency, setDefaultCurrency] = useState(port?.defaultCurrency ?? 'USD');
|
||||
const [timezone, setTimezone] = useState(port?.timezone ?? 'America/Anguilla');
|
||||
const [isActive, setIsActive] = useState(port?.isActive ?? true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isEdit = !!port;
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (port) {
|
||||
setName(port.name);
|
||||
setSlug(port.slug);
|
||||
setPrimaryColor(port.primaryColor ?? '#0F4C81');
|
||||
setDefaultCurrency(port.defaultCurrency);
|
||||
setTimezone(port.timezone);
|
||||
setIsActive(port.isActive);
|
||||
} else {
|
||||
setName('');
|
||||
setSlug('');
|
||||
setPrimaryColor('#0F4C81');
|
||||
setDefaultCurrency('USD');
|
||||
setTimezone('America/Anguilla');
|
||||
setIsActive(true);
|
||||
}
|
||||
setError(null);
|
||||
}
|
||||
}, [open, port]);
|
||||
|
||||
function handleNameChange(value: string) {
|
||||
setName(value);
|
||||
if (!isEdit) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { GripVertical, Plus, Trash2, Loader2, Save, AlertTriangle } from 'lucide-react';
|
||||
import { GripVertical, Plus, Trash2, Loader2, Save } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { toast } from 'sonner';
|
||||
@@ -235,11 +236,10 @@ export function ResidentialStagesAdmin() {
|
||||
</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" />
|
||||
<WarningCallout>
|
||||
Removing: {removedStageIds.join(', ')}. Any interests parked on these stages will need to
|
||||
be reassigned before save.
|
||||
</div>
|
||||
</WarningCallout>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
import { formatErrorBanner } from '@/lib/api/toast-error';
|
||||
import { formatEnum } from '@/lib/constants';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -120,7 +121,7 @@ const GROUP_LABELS: Record<string, string> = {
|
||||
};
|
||||
|
||||
function formatAction(action: string): string {
|
||||
return action.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
return formatEnum(action);
|
||||
}
|
||||
|
||||
interface RoleFormProps {
|
||||
@@ -136,41 +137,36 @@ interface RoleFormProps {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export function RoleForm({ open, onOpenChange, role, onSuccess }: RoleFormProps) {
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [permissions, setPermissions] = useState<Record<string, Record<string, boolean>>>(
|
||||
structuredClone(DEFAULT_PERMISSIONS),
|
||||
export function RoleForm(props: RoleFormProps) {
|
||||
return (
|
||||
<RoleFormBody key={props.open ? `open:${props.role?.id ?? 'new'}` : 'closed'} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function RoleFormBody({ open, onOpenChange, role, onSuccess }: RoleFormProps) {
|
||||
// Merge role permissions over defaults to fill any missing keys.
|
||||
const initialPermissions = (() => {
|
||||
const merged = structuredClone(DEFAULT_PERMISSIONS);
|
||||
if (role) {
|
||||
for (const [group, actions] of Object.entries(role.permissions)) {
|
||||
if (merged[group]) {
|
||||
for (const [action, value] of Object.entries(actions as Record<string, boolean>)) {
|
||||
merged[group]![action] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
})();
|
||||
const [name, setName] = useState(role?.name ?? '');
|
||||
const [description, setDescription] = useState(role?.description ?? '');
|
||||
const [permissions, setPermissions] =
|
||||
useState<Record<string, Record<string, boolean>>>(initialPermissions);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isEdit = !!role;
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (role) {
|
||||
setName(role.name);
|
||||
setDescription(role.description ?? '');
|
||||
// Merge role permissions over defaults to fill any missing keys
|
||||
const merged = structuredClone(DEFAULT_PERMISSIONS);
|
||||
for (const [group, actions] of Object.entries(role.permissions)) {
|
||||
if (merged[group]) {
|
||||
for (const [action, value] of Object.entries(actions as Record<string, boolean>)) {
|
||||
merged[group]![action] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
setPermissions(merged);
|
||||
} else {
|
||||
setName('');
|
||||
setDescription('');
|
||||
setPermissions(structuredClone(DEFAULT_PERMISSIONS));
|
||||
}
|
||||
setError(null);
|
||||
}
|
||||
}, [open, role]);
|
||||
|
||||
function togglePermission(group: string, action: string) {
|
||||
setPermissions((prev) => {
|
||||
const next = structuredClone(prev);
|
||||
|
||||
@@ -127,6 +127,8 @@ export function SalesEmailConfigCard() {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Initial load on mount — canonical fetch-once pattern.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void refresh();
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -258,6 +258,8 @@ export function SettingsManager() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Initial settings load on mount.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void fetchSettings();
|
||||
}, [fetchSettings]);
|
||||
|
||||
|
||||
@@ -107,6 +107,8 @@ export function SettingsFormCard({ title, description, fields, extra }: Settings
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Initial load — fetchValues internally setStates loading + values.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void fetchValues();
|
||||
}, [fetchValues]);
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
SettingsFormCard,
|
||||
type SettingFieldDef,
|
||||
} from '@/components/admin/shared/settings-form-card';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
|
||||
@@ -360,12 +361,12 @@ export function StorageAdminPanel() {
|
||||
</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
|
||||
<WarningCallout>
|
||||
{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>
|
||||
</WarningCallout>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setConfirmOpen(false)}>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
import { formatErrorBanner } from '@/lib/api/toast-error';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -53,75 +54,49 @@ interface UserFormProps {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps) {
|
||||
const [roles, setRoles] = useState<Role[]>([]);
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [originalEmail, setOriginalEmail] = useState('');
|
||||
export function UserForm(props: UserFormProps) {
|
||||
return (
|
||||
<UserFormBody key={props.open ? `open:${props.user?.userId ?? 'new'}` : 'closed'} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function UserFormBody({ open, onOpenChange, user, onSuccess }: UserFormProps) {
|
||||
// Derive initial first/last names from the user payload.
|
||||
const initialNames = (() => {
|
||||
if (!user) return { first: '', last: '' };
|
||||
if (user.firstName || user.lastName) {
|
||||
return { first: user.firstName ?? '', last: user.lastName ?? '' };
|
||||
}
|
||||
const source = user.fullName ?? user.displayName;
|
||||
const parts = source.split(/\s+/);
|
||||
return { first: parts[0] ?? '', last: parts.slice(1).join(' ') };
|
||||
})();
|
||||
// useQuery replaces the prior useEffect(fetch+setRoles) pattern.
|
||||
const rolesQuery = useQuery<{ data: Role[] }>({
|
||||
queryKey: ['admin', 'roles'],
|
||||
queryFn: () => apiFetch('/api/v1/admin/roles'),
|
||||
enabled: open,
|
||||
});
|
||||
const roles = rolesQuery.data?.data ?? [];
|
||||
const [firstName, setFirstName] = useState(initialNames.first);
|
||||
const [lastName, setLastName] = useState(initialNames.last);
|
||||
const [email, setEmail] = useState(user?.email ?? '');
|
||||
const [originalEmail] = useState(user?.email ?? '');
|
||||
const [emailConfirmOpen, setEmailConfirmOpen] = useState(false);
|
||||
const [password, setPassword] = useState('');
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [phoneValue, setPhoneValue] = useState<PhoneInputValue | null>(null);
|
||||
const [roleId, setRoleId] = useState('');
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
const [residentialAccess, setResidentialAccess] = useState(false);
|
||||
const [displayName, setDisplayName] = useState(user?.displayName ?? '');
|
||||
const [phoneValue, setPhoneValue] = useState<PhoneInputValue | null>(
|
||||
user?.phone ? { e164: user.phone, country: 'US' } : null,
|
||||
);
|
||||
const [roleId, setRoleId] = useState(user?.role.id ?? '');
|
||||
const [isActive, setIsActive] = useState(user?.isActive ?? true);
|
||||
const [residentialAccess, setResidentialAccess] = useState(user?.residentialAccess ?? false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isEdit = !!user;
|
||||
const fullName = `${firstName} ${lastName}`.trim();
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
void apiFetch<{ data: Role[] }>('/api/v1/admin/roles').then((res) => setRoles(res.data));
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (user) {
|
||||
// Prefer canonical first/last from the API; fall back to a best-
|
||||
// effort split of displayName for older records that pre-date the
|
||||
// first_name/last_name columns.
|
||||
const first = user.firstName ?? '';
|
||||
const last = user.lastName ?? '';
|
||||
if (first || last) {
|
||||
setFirstName(first);
|
||||
setLastName(last);
|
||||
} else if (user.fullName) {
|
||||
const parts = user.fullName.split(/\s+/);
|
||||
setFirstName(parts[0] ?? '');
|
||||
setLastName(parts.slice(1).join(' '));
|
||||
} else {
|
||||
const parts = user.displayName.split(/\s+/);
|
||||
setFirstName(parts[0] ?? '');
|
||||
setLastName(parts.slice(1).join(' '));
|
||||
}
|
||||
setEmail(user.email);
|
||||
setOriginalEmail(user.email);
|
||||
setDisplayName(user.displayName);
|
||||
setPhoneValue(user.phone ? { e164: user.phone, country: 'US' } : null);
|
||||
setRoleId(user.role.id);
|
||||
setIsActive(user.isActive);
|
||||
setResidentialAccess(user.residentialAccess ?? false);
|
||||
setPassword('');
|
||||
} else {
|
||||
setFirstName('');
|
||||
setLastName('');
|
||||
setEmail('');
|
||||
setOriginalEmail('');
|
||||
setDisplayName('');
|
||||
setPhoneValue(null);
|
||||
setRoleId('');
|
||||
setIsActive(true);
|
||||
setResidentialAccess(false);
|
||||
setPassword('');
|
||||
}
|
||||
setError(null);
|
||||
}
|
||||
}, [open, user]);
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
// Admin email change for an existing user goes through a confirmation
|
||||
|
||||
@@ -12,6 +12,8 @@ import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { formatEnum } from '@/lib/constants';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
@@ -103,7 +105,7 @@ const PERMISSION_LEAVES: Record<string, string[]> = {
|
||||
};
|
||||
|
||||
function formatAction(action: string): string {
|
||||
return action.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
return formatEnum(action);
|
||||
}
|
||||
|
||||
type Overrides = Record<string, Record<string, boolean>>;
|
||||
@@ -223,13 +225,13 @@ export function UserPermissionMatrix({ userId }: UserPermissionMatrixProps) {
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||
<p>
|
||||
<WarningCallout icon={false}>
|
||||
<span className="text-xs">
|
||||
Permission overrides save <strong>on the button below</strong>, separately from the
|
||||
Profile & role tab. Switching tabs or closing the drawer without clicking
|
||||
<strong> Save overrides</strong> drops your changes.
|
||||
</p>
|
||||
</div>
|
||||
Profile & role tab. Switching tabs or closing the drawer without clicking{' '}
|
||||
<strong>Save overrides</strong> drops your changes.
|
||||
</span>
|
||||
</WarningCallout>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Each toggle defaults to <strong>Inherit</strong> (role + port override decide). Switch to
|
||||
<strong> Grant</strong> or <strong>Deny</strong> to force the value for this user only.
|
||||
|
||||
@@ -84,6 +84,8 @@ export function VocabulariesManager() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Initial vocabularies load on mount.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void fetchAll();
|
||||
}, [fetchAll]);
|
||||
|
||||
|
||||
@@ -44,16 +44,17 @@ export function BerthDetail({ berthId }: BerthDetailProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams.get('edit') === 'true') {
|
||||
// setState in effect is the right shape here — the URL is an
|
||||
// external store and the trigger is a query-param change, not a
|
||||
// prop in the React tree.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setEditOpen(true);
|
||||
// Strip the param without adding a history entry
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.delete('edit');
|
||||
const newUrl = params.toString() ? `?${params.toString()}` : window.location.pathname;
|
||||
// typedRoutes can't statically validate this dynamic path; cast is safe
|
||||
// because we're always replacing within the same route segment.
|
||||
router.replace(newUrl as never);
|
||||
}
|
||||
// Only run once on mount / when searchParams changes
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [searchParams]);
|
||||
|
||||
|
||||
@@ -222,11 +222,13 @@ function OverviewTab({ berth }: { berth: BerthData }) {
|
||||
const patch = useBerthPatch(berth.id);
|
||||
// User-selected display unit for dimensions. Persisted in localStorage
|
||||
// so reps' preferred unit sticks across navigations + sessions.
|
||||
const [units, setUnits] = useState<'ft' | 'm'>('ft');
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem('berth-overview-units');
|
||||
if (stored === 'ft' || stored === 'm') setUnits(stored);
|
||||
}, []);
|
||||
// Lazy initializer reads localStorage on first render — avoids the
|
||||
// mount-effect-setState shape the compiler flags.
|
||||
const [units, setUnits] = useState<'ft' | 'm'>(() => {
|
||||
if (typeof window === 'undefined') return 'ft';
|
||||
const stored = window.localStorage.getItem('berth-overview-units');
|
||||
return stored === 'ft' || stored === 'm' ? stored : 'ft';
|
||||
});
|
||||
useEffect(() => {
|
||||
localStorage.setItem('berth-overview-units', units);
|
||||
}, [units]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AlertTriangle, ArrowLeft, ArrowRight, CheckCircle2, Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
interface PreflightItem {
|
||||
@@ -36,7 +37,19 @@ interface Props {
|
||||
|
||||
type Stage = 'preflight' | 'reasons' | 'confirm';
|
||||
|
||||
export function BulkArchiveWizard({ open, onOpenChange, clientIds, onSuccess }: Props) {
|
||||
export function BulkArchiveWizard(props: Props) {
|
||||
// Key-based remount: body keyed on open + clientIds so its useState
|
||||
// initializers re-run each time the wizard opens fresh. Replaces the
|
||||
// useEffect(setState, [open]) reset the Compiler flagged.
|
||||
return (
|
||||
<BulkArchiveWizardBody
|
||||
key={props.open ? `open:${props.clientIds.join(',')}` : 'closed'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function BulkArchiveWizardBody({ open, onOpenChange, clientIds, onSuccess }: Props) {
|
||||
const qc = useQueryClient();
|
||||
const [stage, setStage] = useState<Stage>('preflight');
|
||||
const [reasons, setReasons] = useState<Record<string, string>>({});
|
||||
@@ -52,14 +65,6 @@ export function BulkArchiveWizard({ open, onOpenChange, clientIds, onSuccess }:
|
||||
enabled: open && clientIds.length > 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStage('preflight');
|
||||
setReasons({});
|
||||
setCarouselIndex(0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const items = preflight.data ?? [];
|
||||
const blocked = useMemo(() => items.filter((i) => i.blockers.length > 0), [items]);
|
||||
const highStakes = useMemo(
|
||||
@@ -192,15 +197,17 @@ export function BulkArchiveWizard({ open, onOpenChange, clientIds, onSuccess }:
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
<div className="rounded-md border border-amber-300 bg-amber-50 p-3">
|
||||
<div className="flex items-center gap-2 mb-1.5">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-700" />
|
||||
<span className="font-medium text-amber-900">{currentHighStakes.fullName}</span>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{currentHighStakes.highStakesStage}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-amber-900">
|
||||
<WarningCallout
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
<span>{currentHighStakes.fullName}</span>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{currentHighStakes.highStakesStage}
|
||||
</Badge>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<span className="text-xs">
|
||||
{currentHighStakes.summary.berths > 0
|
||||
? `${currentHighStakes.summary.berths} berth(s), `
|
||||
: ''}
|
||||
@@ -210,8 +217,8 @@ export function BulkArchiveWizard({ open, onOpenChange, clientIds, onSuccess }:
|
||||
{currentHighStakes.summary.reservations > 0
|
||||
? `${currentHighStakes.summary.reservations} reservation(s)`
|
||||
: ''}
|
||||
</div>
|
||||
</div>
|
||||
</span>
|
||||
</WarningCallout>
|
||||
<Textarea
|
||||
value={reasons[currentHighStakes.clientId] ?? ''}
|
||||
onChange={(e) =>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { FilePreviewDialog } from '@/components/files/file-preview-dialog';
|
||||
import { PermissionGate } from '@/components/shared/permission-gate';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import type { FileRow } from '@/components/files/file-grid';
|
||||
|
||||
@@ -19,6 +20,7 @@ interface ClientFilesTabProps {
|
||||
export function ClientFilesTab({ clientId }: ClientFilesTabProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [previewFile, setPreviewFile] = useState<FileRow | null>(null);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data, isLoading } = usePaginatedQuery<FileRow>({
|
||||
queryKey: ['files', { clientId }],
|
||||
@@ -47,7 +49,12 @@ export function ClientFilesTab({ clientId }: ClientFilesTabProps) {
|
||||
};
|
||||
|
||||
const handleDelete = async (file: FileRow) => {
|
||||
if (!confirm(`Delete "${file.filename}"? This cannot be undone.`)) return;
|
||||
const ok = await confirm({
|
||||
title: 'Delete file',
|
||||
description: `Delete "${file.filename}"? This cannot be undone.`,
|
||||
confirmLabel: 'Delete',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await apiFetch(`/api/v1/files/${file.id}`, { method: 'DELETE' });
|
||||
queryClient.invalidateQueries({ queryKey: ['files', { clientId }] });
|
||||
@@ -83,6 +90,7 @@ export function ClientFilesTab({ clientId }: ClientFilesTabProps) {
|
||||
fileName={previewFile?.filename}
|
||||
mimeType={previewFile?.mimeType ?? undefined}
|
||||
/>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { ArrowRight, CheckCircle2, ChevronRight, Circle, Plus } from 'lucide-rea
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { EmptyState } from '@/components/shared/empty-state';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/shared/drawer';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { PIPELINE_STAGES, type PipelineStage } from '@/lib/constants';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -46,10 +46,10 @@ function InterestRowItem({
|
||||
const yachtLabel = interest.yachtName ?? null;
|
||||
|
||||
return (
|
||||
// Tap opens a bottom-sheet preview drawer rather than navigating to the
|
||||
// full interest page. The drawer covers ~80% of mobile interactions
|
||||
// ("what stage is this at, when did we last touch it"). For deeper
|
||||
// edits the drawer has an "Open full page" CTA.
|
||||
// Tap opens a right-side Sheet preview rather than navigating to the
|
||||
// full interest page. The sheet covers ~80% of interactions ("what
|
||||
// stage is this at, when did we last touch it"). For deeper edits
|
||||
// the sheet has an "Open full page" CTA.
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpen(interest)}
|
||||
@@ -214,17 +214,17 @@ function InterestPreviewDrawer({
|
||||
const notesPreview = fullDetail?.notes?.trim() || null;
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
<Sheet
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) onClose();
|
||||
}}
|
||||
>
|
||||
<DrawerContent className="max-h-[85vh]">
|
||||
<DrawerHeader>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<SheetContent side="right" className="w-full overflow-y-auto sm:max-w-md">
|
||||
<SheetHeader>
|
||||
<div className="flex items-start justify-between gap-3 pr-8">
|
||||
<div className="min-w-0 flex-1">
|
||||
<DrawerTitle className="truncate">{berthLabel}</DrawerTitle>
|
||||
<SheetTitle className="truncate text-left">{berthLabel}</SheetTitle>
|
||||
{yachtLabel ? (
|
||||
<p className="mt-0.5 truncate text-sm text-muted-foreground">{yachtLabel}</p>
|
||||
) : null}
|
||||
@@ -240,9 +240,9 @@ function InterestPreviewDrawer({
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</DrawerHeader>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="space-y-5 overflow-y-auto px-4 pb-4">
|
||||
<div className="mt-5 space-y-5">
|
||||
{/* Pipeline-stepper segmented bar - the same primitive used on the
|
||||
row card, so the at-a-glance progress hint is consistent
|
||||
across surfaces. */}
|
||||
@@ -357,8 +357,8 @@ function InterestPreviewDrawer({
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
import { InlinePhoneField } from '@/components/shared/inline-phone-field';
|
||||
import { PhoneInput, type PhoneInputValue } from '@/components/shared/phone-input';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -57,6 +58,7 @@ const CHANNEL_ICONS: Record<string, React.ComponentType<{ className?: string }>>
|
||||
export function ContactsEditor({ clientId, contacts }: { clientId: string; contacts: Contact[] }) {
|
||||
const qc = useQueryClient();
|
||||
const [adding, setAdding] = useState(false);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
function invalidate() {
|
||||
qc.invalidateQueries({ queryKey: ['clients', clientId] });
|
||||
@@ -112,7 +114,12 @@ export function ContactsEditor({ clientId, contacts }: { clientId: string; conta
|
||||
contact={c}
|
||||
onUpdate={(patch) => updateMutation.mutateAsync({ contactId: c.id, patch })}
|
||||
onRemove={async () => {
|
||||
if (!confirm('Remove this contact?')) return;
|
||||
const ok = await confirm({
|
||||
title: 'Remove contact',
|
||||
description: 'Remove this contact?',
|
||||
confirmLabel: 'Remove',
|
||||
});
|
||||
if (!ok) return;
|
||||
await removeMutation.mutateAsync(c.id);
|
||||
}}
|
||||
/>
|
||||
@@ -138,6 +145,7 @@ export function ContactsEditor({ clientId, contacts }: { clientId: string; conta
|
||||
Add contact
|
||||
</Button>
|
||||
)}
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
interface Props {
|
||||
@@ -108,22 +109,19 @@ function HardDeleteDialogBody({ onOpenChange, clientId, clientName, onDeleted }:
|
||||
Permanent deletion is reserved for archived clients only. We’ll email a 4-digit
|
||||
confirmation code to your account address. The code expires in 10 minutes.
|
||||
</p>
|
||||
<div className="rounded-md border border-amber-300 bg-amber-50 p-3 text-amber-900">
|
||||
<p className="font-medium flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4" /> What gets deleted
|
||||
</p>
|
||||
<WarningCallout title="What gets deleted">
|
||||
<ul className="mt-1.5 list-disc pl-5 text-xs space-y-0.5">
|
||||
<li>Client record + addresses, contacts, notes, tags</li>
|
||||
<li>Portal user account + GDPR consent records</li>
|
||||
<li>All pipeline interests + reservations for this client</li>
|
||||
</ul>
|
||||
<p className="font-medium mt-2 flex items-center gap-2">What is preserved</p>
|
||||
<p className="font-medium mt-2">What is preserved</p>
|
||||
<ul className="mt-1.5 list-disc pl-5 text-xs space-y-0.5">
|
||||
<li>Signed documents (detached from client, kept for legal history)</li>
|
||||
<li>Email threads, files, reminders (detached)</li>
|
||||
<li>Audit log entries</li>
|
||||
</ul>
|
||||
</div>
|
||||
</WarningCallout>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AlertTriangle, Anchor, FileText, Loader2, Receipt, Ship, Users } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -95,50 +95,96 @@ interface Props {
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
export function SmartArchiveDialog({ open, onOpenChange, clientId, clientName, onSuccess }: Props) {
|
||||
const qc = useQueryClient();
|
||||
export function SmartArchiveDialog(props: Props) {
|
||||
// Key-based remount: body keyed on open + clientId; once the dossier
|
||||
// loads, an inner key forces the decision-defaults to seed cleanly.
|
||||
return (
|
||||
<SmartArchiveDialogShell key={props.open ? `open:${props.clientId}` : 'closed'} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function SmartArchiveDialogShell({ open, onOpenChange, clientId, clientName, onSuccess }: Props) {
|
||||
const qc = useQueryClient();
|
||||
const dossierQuery = useQuery({
|
||||
queryKey: ['client-archive-dossier', clientId],
|
||||
queryFn: () =>
|
||||
apiFetch<{ data: ArchiveDossier }>(`/api/v1/clients/${clientId}/archive-dossier`),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const dossier = dossierQuery.data?.data;
|
||||
// While the dossier is loading the body's useState initializers can't
|
||||
// derive defaults, so we delay-key the body so it mounts ONCE with the
|
||||
// right seed when the data arrives. Replaces the prior
|
||||
// useEffect(setState, [dossier]) sync that the Compiler flagged.
|
||||
return (
|
||||
<SmartArchiveDialogBody
|
||||
key={dossier ? 'loaded' : 'loading'}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
clientId={clientId}
|
||||
clientName={clientName}
|
||||
onSuccess={onSuccess}
|
||||
dossier={dossier ?? null}
|
||||
isLoading={dossierQuery.isLoading}
|
||||
error={dossierQuery.error}
|
||||
qc={qc}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SmartArchiveDialogBody({
|
||||
open,
|
||||
onOpenChange,
|
||||
clientId,
|
||||
clientName,
|
||||
onSuccess,
|
||||
dossier,
|
||||
isLoading,
|
||||
error,
|
||||
qc,
|
||||
}: Props & {
|
||||
dossier: ArchiveDossier | null;
|
||||
isLoading: boolean;
|
||||
error: unknown;
|
||||
qc: ReturnType<typeof useQueryClient>;
|
||||
}) {
|
||||
// ─── Local decision state ────────────────────────────────────────────────
|
||||
const [reason, setReason] = useState('');
|
||||
const [acknowledged, setAcknowledged] = useState(false);
|
||||
const [berthDecisions, setBerthDecisions] = useState<Record<string, BerthAction>>({});
|
||||
const [yachtDecisions, setYachtDecisions] = useState<Record<string, YachtAction>>({});
|
||||
const [berthDecisions, setBerthDecisions] = useState<Record<string, BerthAction>>(() =>
|
||||
dossier
|
||||
? Object.fromEntries(
|
||||
dossier.berths.map((berth) => [
|
||||
berth.berthId,
|
||||
berth.status === 'sold' ? ('retain' as BerthAction) : ('release' as BerthAction),
|
||||
]),
|
||||
)
|
||||
: {},
|
||||
);
|
||||
const [yachtDecisions, setYachtDecisions] = useState<Record<string, YachtAction>>(() =>
|
||||
dossier
|
||||
? Object.fromEntries(dossier.yachts.map((y) => [y.yachtId, 'retain' as YachtAction]))
|
||||
: {},
|
||||
);
|
||||
const [reservationDecisions, setReservationDecisions] = useState<
|
||||
Record<string, ReservationAction>
|
||||
>({});
|
||||
const [invoiceDecisions, setInvoiceDecisions] = useState<Record<string, InvoiceAction>>({});
|
||||
const [documentDecisions, setDocumentDecisions] = useState<Record<string, DocumentAction>>({});
|
||||
|
||||
// Reset state when the dialog opens / closes / dossier loads.
|
||||
useEffect(() => {
|
||||
if (!open || !dossier) return;
|
||||
setReason('');
|
||||
setAcknowledged(false);
|
||||
// Sensible defaults: release all berths, retain all yachts, cancel
|
||||
// active reservations, leave invoices, leave documents alone.
|
||||
const b: Record<string, BerthAction> = {};
|
||||
for (const berth of dossier.berths) {
|
||||
// Sold berths can't be released; default to retain.
|
||||
b[berth.berthId] = berth.status === 'sold' ? 'retain' : 'release';
|
||||
}
|
||||
setBerthDecisions(b);
|
||||
setYachtDecisions(Object.fromEntries(dossier.yachts.map((y) => [y.yachtId, 'retain'])));
|
||||
setReservationDecisions(
|
||||
Object.fromEntries(dossier.reservations.map((r) => [r.reservationId, 'cancel'])),
|
||||
);
|
||||
setInvoiceDecisions(Object.fromEntries(dossier.invoices.map((i) => [i.invoiceId, 'leave'])));
|
||||
setDocumentDecisions(Object.fromEntries(dossier.documents.map((d) => [d.documentId, 'leave'])));
|
||||
}, [open, dossier]);
|
||||
|
||||
>(() =>
|
||||
dossier
|
||||
? Object.fromEntries(
|
||||
dossier.reservations.map((r) => [r.reservationId, 'cancel' as ReservationAction]),
|
||||
)
|
||||
: {},
|
||||
);
|
||||
const [invoiceDecisions, setInvoiceDecisions] = useState<Record<string, InvoiceAction>>(() =>
|
||||
dossier
|
||||
? Object.fromEntries(dossier.invoices.map((i) => [i.invoiceId, 'leave' as InvoiceAction]))
|
||||
: {},
|
||||
);
|
||||
const [documentDecisions, setDocumentDecisions] = useState<Record<string, DocumentAction>>(() =>
|
||||
dossier
|
||||
? Object.fromEntries(dossier.documents.map((d) => [d.documentId, 'leave' as DocumentAction]))
|
||||
: {},
|
||||
);
|
||||
const hasSignedDocs = useMemo(
|
||||
() =>
|
||||
dossier?.documents.some((d) => d.status === 'completed' || d.status === 'signed') ?? false,
|
||||
@@ -235,15 +281,14 @@ export function SmartArchiveDialog({ open, onOpenChange, clientId, clientName, o
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{dossierQuery.isLoading ? (
|
||||
{isLoading ? (
|
||||
<div className="py-8 text-center text-sm text-muted-foreground">
|
||||
<Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
|
||||
Loading dossier…
|
||||
</div>
|
||||
) : dossierQuery.error || !dossier ? (
|
||||
) : error || !dossier ? (
|
||||
<div className="py-8 text-center text-sm text-red-600">
|
||||
Failed to load dossier:{' '}
|
||||
{dossierQuery.error instanceof Error ? dossierQuery.error.message : 'unknown error'}
|
||||
Failed to load dossier: {error instanceof Error ? error.message : 'unknown error'}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3 max-h-[60vh] overflow-y-auto pr-1">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
AlertTriangle,
|
||||
@@ -59,7 +59,16 @@ function iconFor(kind: string) {
|
||||
return <Wrench className="h-3 w-3" />;
|
||||
}
|
||||
|
||||
export function SmartRestoreDialog({ open, onOpenChange, clientId, clientName, onSuccess }: Props) {
|
||||
export function SmartRestoreDialog(props: Props) {
|
||||
// Key-based remount: the body is keyed on open + clientId so its
|
||||
// useState({}) initializer runs fresh each open. Replaces the prior
|
||||
// useEffect(setSelected, [open, dossier]) reset.
|
||||
return (
|
||||
<SmartRestoreDialogBody key={props.open ? `open:${props.clientId}` : 'closed'} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function SmartRestoreDialogBody({ open, onOpenChange, clientId, clientName, onSuccess }: Props) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
const dossierQuery = useQuery({
|
||||
@@ -73,11 +82,6 @@ export function SmartRestoreDialog({ open, onOpenChange, clientId, clientName, o
|
||||
|
||||
const [selected, setSelected] = useState<Record<string, boolean>>({});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !dossier) return;
|
||||
setSelected({});
|
||||
}, [open, dossier]);
|
||||
|
||||
const restoreMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
const applyReversals = Object.entries(selected)
|
||||
|
||||
@@ -9,6 +9,7 @@ import { FilePreviewDialog } from '@/components/files/file-preview-dialog';
|
||||
import { PermissionGate } from '@/components/shared/permission-gate';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import type { FileRow } from '@/components/files/file-grid';
|
||||
|
||||
@@ -19,6 +20,7 @@ interface CompanyFilesTabProps {
|
||||
export function CompanyFilesTab({ companyId }: CompanyFilesTabProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [previewFile, setPreviewFile] = useState<FileRow | null>(null);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data, isLoading } = usePaginatedQuery<FileRow>({
|
||||
queryKey: ['files', { companyId }],
|
||||
@@ -47,7 +49,12 @@ export function CompanyFilesTab({ companyId }: CompanyFilesTabProps) {
|
||||
};
|
||||
|
||||
const handleDelete = async (file: FileRow) => {
|
||||
if (!confirm(`Delete "${file.filename}"? This cannot be undone.`)) return;
|
||||
const ok = await confirm({
|
||||
title: 'Delete file',
|
||||
description: `Delete "${file.filename}"? This cannot be undone.`,
|
||||
confirmLabel: 'Delete',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await apiFetch(`/api/v1/files/${file.id}`, { method: 'DELETE' });
|
||||
queryClient.invalidateQueries({ queryKey: ['files', { companyId }] });
|
||||
@@ -83,6 +90,7 @@ export function CompanyFilesTab({ companyId }: CompanyFilesTabProps) {
|
||||
fileName={previewFile?.filename}
|
||||
mimeType={previewFile?.mimeType ?? undefined}
|
||||
/>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,12 +37,14 @@ import { useCreateFromUrl } from '@/hooks/use-create-from-url';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useTablePreferences } from '@/hooks/use-table-preferences';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
export function CompanyList() {
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
useCreateFromUrl(() => setCreateOpen(true));
|
||||
@@ -195,15 +197,14 @@ export function CompanyList() {
|
||||
label: 'Archive',
|
||||
icon: Archive,
|
||||
variant: 'destructive',
|
||||
onClick: (ids) => {
|
||||
onClick: async (ids) => {
|
||||
if (ids.length === 0) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Archive ${ids.length} compan${ids.length === 1 ? 'y' : 'ies'}? This can be undone from the archived list.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const ok = await confirm({
|
||||
title: `Archive ${ids.length} compan${ids.length === 1 ? 'y' : 'ies'}`,
|
||||
description: 'This can be undone from the archived list.',
|
||||
confirmLabel: 'Archive',
|
||||
});
|
||||
if (!ok) return;
|
||||
bulkMutation.mutate({ action: 'archive', ids });
|
||||
},
|
||||
},
|
||||
@@ -303,6 +304,7 @@ export function CompanyList() {
|
||||
onConfirm={() => archiveCompany && archiveMutation.mutate(archiveCompany.id)}
|
||||
isLoading={archiveMutation.isPending}
|
||||
/>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -107,6 +107,9 @@ export function DashboardShell({
|
||||
// local-time-aware phrasing once the component has mounted.
|
||||
const [clientGreeting, setClientGreeting] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
// setState here is intentional — we delay the time-aware greeting
|
||||
// until after hydration to avoid SSR/client clock mismatch.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setClientGreeting(timeOfDayGreeting());
|
||||
// Re-evaluate hourly so a rep who leaves the dashboard open through a
|
||||
// boundary (5am, noon, 6pm) doesn't keep stale text on screen.
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { formatEnum } from '@/lib/constants';
|
||||
|
||||
interface SourceRow {
|
||||
source: string;
|
||||
@@ -57,7 +58,7 @@ export function SourceConversionChart() {
|
||||
<ul className="space-y-3">
|
||||
{rows.map((r) => {
|
||||
const pct = Math.round(r.conversionRate * 100);
|
||||
const label = r.source.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
const label = formatEnum(r.source);
|
||||
return (
|
||||
<li key={r.source} className="space-y-1">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { StatusPill, type StatusPillStatus } from '@/components/ui/status-pill';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
|
||||
@@ -93,6 +94,7 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [isCancelling, setIsCancelling] = useState(false);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data, isLoading, error } = useQuery<DetailResponse>({
|
||||
queryKey: ['document-detail', documentId],
|
||||
@@ -157,8 +159,12 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
|
||||
};
|
||||
|
||||
const handleCancel = async () => {
|
||||
if (!confirm('Cancel this document? This voids the signing envelope and cannot be undone.'))
|
||||
return;
|
||||
const ok = await confirm({
|
||||
title: 'Cancel document',
|
||||
description: 'Cancel this document? This voids the signing envelope and cannot be undone.',
|
||||
confirmLabel: 'Cancel document',
|
||||
});
|
||||
if (!ok) return;
|
||||
setIsCancelling(true);
|
||||
try {
|
||||
await apiFetch(`/api/v1/documents/${documentId}/cancel`, { method: 'POST' });
|
||||
@@ -395,6 +401,7 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { PermissionGate } from '@/components/shared/permission-gate';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { MoveToFolderDialog } from './move-to-folder-dialog';
|
||||
|
||||
@@ -121,6 +122,7 @@ function DocRow({ doc, onDelete, onSend }: DocRowProps) {
|
||||
|
||||
export function DocumentList({ interestId, clientId, emptyState }: DocumentListProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const queryParams = new URLSearchParams();
|
||||
if (interestId) queryParams.set('interestId', interestId);
|
||||
@@ -133,7 +135,12 @@ export function DocumentList({ interestId, clientId, emptyState }: DocumentListP
|
||||
});
|
||||
|
||||
const handleDelete = async (doc: DocumentRow) => {
|
||||
if (!confirm(`Delete "${doc.title}"? This cannot be undone.`)) return;
|
||||
const ok = await confirm({
|
||||
title: 'Delete document',
|
||||
description: `Delete "${doc.title}"? This cannot be undone.`,
|
||||
confirmLabel: 'Delete',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await apiFetch(`/api/v1/documents/${doc.id}`, { method: 'DELETE' });
|
||||
queryClient.invalidateQueries({ queryKey: ['documents', { interestId, clientId }] });
|
||||
@@ -181,6 +188,7 @@ export function DocumentList({ interestId, clientId, emptyState }: DocumentListP
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Check, FolderInput } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
@@ -35,85 +35,94 @@ interface MoveToFolderDialogProps {
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function MoveToFolderDialog({
|
||||
export function MoveToFolderDialog(props: MoveToFolderDialogProps) {
|
||||
// Key-based remount: the inner body is keyed on `open + currentFolderId`
|
||||
// so its `useState` initializer re-runs each time the dialog is re-
|
||||
// opened, replacing the prior `useEffect(setPickedId)` pattern that the
|
||||
// React Compiler flagged as set-state-in-effect.
|
||||
return (
|
||||
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
{props.open ? (
|
||||
<DialogBody
|
||||
key={`${props.documentId}:${props.currentFolderId ?? '__root__'}`}
|
||||
{...props}
|
||||
/>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogBody({
|
||||
documentId,
|
||||
documentTitle,
|
||||
currentFolderId,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: MoveToFolderDialogProps) {
|
||||
const { data: tree = [] } = useDocumentFolders();
|
||||
const move = useMoveDocument();
|
||||
const [pickedId, setPickedId] = useState<string | null>(currentFolderId);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setPickedId(currentFolderId);
|
||||
}, [open, currentFolderId]);
|
||||
|
||||
const paths = useMemo(() => buildFolderPaths(tree), [tree]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Move “{documentTitle}”</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Command>
|
||||
<CommandInput placeholder="Search folders…" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No folders match.</CommandEmpty>
|
||||
<CommandGroup heading="Special">
|
||||
<CommandItem
|
||||
value="Root (no folder)"
|
||||
onSelect={() => setPickedId(null)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Check
|
||||
className={pickedId === null ? 'h-4 w-4 opacity-100' : 'h-4 w-4 opacity-0'}
|
||||
/>
|
||||
Root (no folder)
|
||||
</CommandItem>
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Move “{documentTitle}”</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Command>
|
||||
<CommandInput placeholder="Search folders…" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No folders match.</CommandEmpty>
|
||||
<CommandGroup heading="Special">
|
||||
<CommandItem
|
||||
value="Root (no folder)"
|
||||
onSelect={() => setPickedId(null)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Check className={pickedId === null ? 'h-4 w-4 opacity-100' : 'h-4 w-4 opacity-0'} />
|
||||
Root (no folder)
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
{paths.length > 0 ? (
|
||||
<CommandGroup heading="Folders">
|
||||
{paths.map((p) => (
|
||||
<CommandItem
|
||||
key={p.id}
|
||||
value={p.path}
|
||||
onSelect={() => setPickedId(p.id)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Check
|
||||
className={pickedId === p.id ? 'h-4 w-4 opacity-100' : 'h-4 w-4 opacity-0'}
|
||||
/>
|
||||
<span className="truncate">{p.path}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
{paths.length > 0 ? (
|
||||
<CommandGroup heading="Folders">
|
||||
{paths.map((p) => (
|
||||
<CommandItem
|
||||
key={p.id}
|
||||
value={p.path}
|
||||
onSelect={() => setPickedId(p.id)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Check
|
||||
className={pickedId === p.id ? 'h-4 w-4 opacity-100' : 'h-4 w-4 opacity-0'}
|
||||
/>
|
||||
<span className="truncate">{p.path}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
) : null}
|
||||
</CommandList>
|
||||
</Command>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={pickedId === currentFolderId || move.isPending}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await move.mutateAsync({ docId: documentId, folderId: pickedId });
|
||||
toast.success('Document moved');
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
toastError(err);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FolderInput className="mr-1.5 h-4 w-4" />
|
||||
Move
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
) : null}
|
||||
</CommandList>
|
||||
</Command>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={pickedId === currentFolderId || move.isPending}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await move.mutateAsync({ docId: documentId, folderId: pickedId });
|
||||
toast.success('Document moved');
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
toastError(err);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FolderInput className="mr-1.5 h-4 w-4" />
|
||||
Move
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FilterDefinition } from '@/components/shared/filter-bar';
|
||||
import { EXPENSE_CATEGORIES } from '@/lib/constants';
|
||||
import { EXPENSE_CATEGORIES, formatEnum } from '@/lib/constants';
|
||||
|
||||
export const expenseFilterDefinitions: FilterDefinition[] = [
|
||||
{
|
||||
@@ -13,7 +13,7 @@ export const expenseFilterDefinitions: FilterDefinition[] = [
|
||||
label: 'Category',
|
||||
type: 'multi-select',
|
||||
options: EXPENSE_CATEGORIES.map((c) => ({
|
||||
label: c.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()),
|
||||
label: formatEnum(c),
|
||||
value: c,
|
||||
})),
|
||||
},
|
||||
|
||||
@@ -25,7 +25,7 @@ import { TripLabelCombobox } from '@/components/expenses/trip-label-combobox';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import type { z } from 'zod';
|
||||
import { createExpenseSchema, type CreateExpenseInput } from '@/lib/validators/expenses';
|
||||
import { EXPENSE_CATEGORIES, PAYMENT_METHODS } from '@/lib/constants';
|
||||
import { EXPENSE_CATEGORIES, PAYMENT_METHODS, formatEnum } from '@/lib/constants';
|
||||
import type { ExpenseRow } from './expense-columns';
|
||||
|
||||
interface UploadedReceipt {
|
||||
@@ -255,7 +255,7 @@ export function ExpenseFormDialog({ open, onOpenChange, expense }: ExpenseFormDi
|
||||
<SelectContent>
|
||||
{EXPENSE_CATEGORIES.map((cat) => (
|
||||
<SelectItem key={cat} value={cat}>
|
||||
{cat.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
|
||||
{formatEnum(cat)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
@@ -276,7 +276,7 @@ export function ExpenseFormDialog({ open, onOpenChange, expense }: ExpenseFormDi
|
||||
<SelectContent>
|
||||
{PAYMENT_METHODS.map((m) => (
|
||||
<SelectItem key={m} value={m}>
|
||||
{m.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
|
||||
{formatEnum(m)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { ExternalLink, ZoomIn } from 'lucide-react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
@@ -37,32 +38,18 @@ export function FilePreviewDialog({
|
||||
fileName,
|
||||
mimeType,
|
||||
}: FilePreviewDialogProps) {
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [lightboxOpen, setLightboxOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !fileId) {
|
||||
setPreviewUrl(null);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
apiFetch<{ data: { url: string } }>(`/api/v1/files/${fileId}/preview`)
|
||||
.then((res) => {
|
||||
setPreviewUrl(res.data.url);
|
||||
})
|
||||
.catch(() => {
|
||||
setError('Failed to load preview');
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
}, [open, fileId]);
|
||||
// useQuery replaces the prior useEffect(fetch+setState) pattern. The
|
||||
// request is gated on the dialog being open and a fileId being set.
|
||||
const previewQuery = useQuery<{ data: { url: string } }>({
|
||||
queryKey: ['file-preview', fileId],
|
||||
queryFn: () => apiFetch(`/api/v1/files/${fileId}/preview`),
|
||||
enabled: open && !!fileId,
|
||||
});
|
||||
const previewUrl = previewQuery.data?.data.url ?? null;
|
||||
const loading = previewQuery.isLoading;
|
||||
const error = previewQuery.error ? 'Failed to load preview' : null;
|
||||
|
||||
const isImage = mimeType?.startsWith('image/');
|
||||
const isPdf = mimeType === 'application/pdf';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Document, Page, pdfjs } from 'react-pdf';
|
||||
import { usePinch } from '@use-gesture/react';
|
||||
import { ChevronLeft, ChevronRight, Loader2, Minus, Plus } from 'lucide-react';
|
||||
@@ -36,7 +36,15 @@ interface PdfViewerProps {
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
export function PdfViewer({ url, fileName }: PdfViewerProps) {
|
||||
export function PdfViewer(props: PdfViewerProps) {
|
||||
// Key-based remount: re-mount the inner body whenever the url
|
||||
// changes so all local state (page, zoom, error) re-initializes from
|
||||
// scratch. Replaces the prior useEffect(reset, [url]) the Compiler
|
||||
// flagged as set-state-in-effect.
|
||||
return <PdfViewerBody key={props.url} {...props} />;
|
||||
}
|
||||
|
||||
function PdfViewerBody({ url, fileName }: PdfViewerProps) {
|
||||
const [numPages, setNumPages] = useState<number | null>(null);
|
||||
const [pageNumber, setPageNumber] = useState(1);
|
||||
const [scale, setScale] = useState(1);
|
||||
@@ -46,22 +54,12 @@ export function PdfViewer({ url, fileName }: PdfViewerProps) {
|
||||
// every render — useMemo wins because react-pdf compares by identity.
|
||||
const options = useMemo(
|
||||
() => ({
|
||||
// Inline the worker fetch URL above; CMap/StandardFontDataUrl
|
||||
// pull from the same CDN for unicode + non-system fonts.
|
||||
cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
|
||||
standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts/`,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Reset on url change so navigation between documents lands on
|
||||
// page 1 at default zoom.
|
||||
setPageNumber(1);
|
||||
setScale(1);
|
||||
setError(null);
|
||||
}, [url]);
|
||||
|
||||
// Pinch-zoom on touch devices. usePinch's `offset` already maps
|
||||
// gesture distance to a smoothly-changing scalar; we clamp it to
|
||||
// the same [0.5, 3] range as the +/- buttons.
|
||||
|
||||
@@ -30,11 +30,12 @@ export function InboxPageShell() {
|
||||
const [remindersOpen, setRemindersOpen] = useState(true);
|
||||
const { data: alertCount } = useAlertCount();
|
||||
|
||||
// Hydrate collapsed state from localStorage on mount. Stored as
|
||||
// 'true'/'false' strings; missing keys default to expanded.
|
||||
// localStorage hydration on mount — canonical "read from external
|
||||
// store" pattern. setState in effect is intentional.
|
||||
useEffect(() => {
|
||||
const a = localStorage.getItem('inbox.alerts.open');
|
||||
const r = localStorage.getItem('inbox.reminders.open');
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
if (a === 'false') setAlertsOpen(false);
|
||||
if (r === 'false') setRemindersOpen(false);
|
||||
}, []);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
Bell,
|
||||
@@ -48,6 +48,7 @@ import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface InterestContactLogTabProps {
|
||||
@@ -158,6 +159,7 @@ function ContactLogRow({
|
||||
onEdit: (e: ContactLogEntry) => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
const channelMeta = CHANNEL_META[entry.channel];
|
||||
const Icon = channelMeta.icon;
|
||||
|
||||
@@ -218,10 +220,13 @@ function ContactLogRow({
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => {
|
||||
if (window.confirm('Delete this contact log entry?')) {
|
||||
deleteMutation.mutate();
|
||||
}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: 'Delete contact log entry',
|
||||
description: 'This cannot be undone.',
|
||||
confirmLabel: 'Delete',
|
||||
});
|
||||
if (ok) deleteMutation.mutate();
|
||||
}}
|
||||
>
|
||||
<Trash2 className="mr-2 size-3.5" />
|
||||
@@ -230,6 +235,7 @@ function ContactLogRow({
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{confirmDialog}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -257,7 +263,24 @@ function EmptyState({ onAdd }: { onAdd: () => void }) {
|
||||
|
||||
// ─── Compose / edit dialog ───────────────────────────────────────────────────
|
||||
|
||||
function ComposeDialog({
|
||||
function ComposeDialog(props: {
|
||||
interestId: string;
|
||||
existing?: ContactLogEntry;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
// Key-based remount: body keyed on open + existing.id so useState
|
||||
// initializers re-run each time the dialog opens with a new row.
|
||||
// Replaces the prior useEffect(setState, [open, existing]) sync.
|
||||
return (
|
||||
<ComposeDialogBody
|
||||
key={props.open ? `open:${props.existing?.id ?? 'new'}` : 'closed'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ComposeDialogBody({
|
||||
interestId,
|
||||
existing,
|
||||
open,
|
||||
@@ -284,21 +307,6 @@ function ComposeDialog({
|
||||
existing?.followUpAt ? localIsoString(existing.followUpAt) : '',
|
||||
);
|
||||
|
||||
// Re-sync local state when the existing entry changes (e.g. opening
|
||||
// the edit dialog for a different row). useEffect, not useMemo —
|
||||
// setState in render is a Compiler red flag.
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setOccurredAt(
|
||||
existing ? localIsoString(existing.occurredAt) : localIsoString(new Date().toISOString()),
|
||||
);
|
||||
setChannel(existing?.channel ?? 'phone');
|
||||
setDirection(existing?.direction ?? 'outbound');
|
||||
setSummary(existing?.summary ?? '');
|
||||
setFollowUpAt(existing?.followUpAt ? localIsoString(existing.followUpAt) : '');
|
||||
}
|
||||
}, [open, existing]);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const body = {
|
||||
|
||||
@@ -22,6 +22,7 @@ import { ExternalEoiUploadDialog } from '@/components/interests/external-eoi-upl
|
||||
import { SigningProgress } from '@/components/documents/signing-progress';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useUIStore } from '@/stores/ui-store';
|
||||
|
||||
@@ -197,6 +198,7 @@ function ActiveContractCard({
|
||||
onUploadSigned: () => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data: signersRes, isLoading: signersLoading } = useQuery<{ data: DocumentSigner[] }>({
|
||||
queryKey: ['documents', doc.id, 'signers'],
|
||||
@@ -306,10 +308,13 @@ function ActiveContractCard({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={cancelMutation.isPending}
|
||||
onClick={() => {
|
||||
if (window.confirm('Cancel this contract? Signers will no longer be able to sign.')) {
|
||||
cancelMutation.mutate();
|
||||
}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: 'Cancel contract',
|
||||
description: 'Signers will no longer be able to sign.',
|
||||
confirmLabel: 'Cancel contract',
|
||||
});
|
||||
if (ok) cancelMutation.mutate();
|
||||
}}
|
||||
className="h-7 gap-1.5 text-xs text-destructive hover:text-destructive [&_svg]:size-3"
|
||||
>
|
||||
@@ -318,6 +323,7 @@ function ActiveContractCard({
|
||||
</Button>
|
||||
</div>
|
||||
</footer>
|
||||
{confirmDialog}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { FilePreviewDialog } from '@/components/files/file-preview-dialog';
|
||||
import { PermissionGate } from '@/components/shared/permission-gate';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
interface InterestDocumentsTabProps {
|
||||
@@ -35,6 +36,7 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
|
||||
const queryClient = useQueryClient();
|
||||
const [eoiDialogOpen, setEoiDialogOpen] = useState(false);
|
||||
const [previewFile, setPreviewFile] = useState<FileRow | null>(null);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data: interest } = useQuery<InterestData>({
|
||||
queryKey: ['interests', interestId],
|
||||
@@ -77,7 +79,12 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
|
||||
};
|
||||
|
||||
const handleDelete = async (file: FileRow) => {
|
||||
if (!confirm(`Delete "${file.filename}"? This cannot be undone.`)) return;
|
||||
const ok = await confirm({
|
||||
title: 'Delete file',
|
||||
description: `Delete "${file.filename}"? This cannot be undone.`,
|
||||
confirmLabel: 'Delete',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await apiFetch(`/api/v1/files/${file.id}`, { method: 'DELETE' });
|
||||
queryClient.invalidateQueries({ queryKey: filesQueryKey });
|
||||
@@ -167,6 +174,7 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
|
||||
fileName={previewFile?.filename}
|
||||
mimeType={previewFile?.mimeType ?? undefined}
|
||||
/>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import { ExternalEoiUploadDialog } from '@/components/interests/external-eoi-upl
|
||||
import { SigningProgress } from '@/components/documents/signing-progress';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useUIStore } from '@/stores/ui-store';
|
||||
|
||||
@@ -186,6 +187,7 @@ function ActiveEoiCard({
|
||||
onUploadSigned: () => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data: signersRes, isLoading: signersLoading } = useQuery<{ data: DocumentSigner[] }>({
|
||||
queryKey: ['documents', doc.id, 'signers'],
|
||||
@@ -295,10 +297,13 @@ function ActiveEoiCard({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={cancelMutation.isPending}
|
||||
onClick={() => {
|
||||
if (window.confirm('Cancel this EOI? Signers will no longer be able to sign.')) {
|
||||
cancelMutation.mutate();
|
||||
}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: 'Cancel EOI',
|
||||
description: 'Signers will no longer be able to sign.',
|
||||
confirmLabel: 'Cancel EOI',
|
||||
});
|
||||
if (ok) cancelMutation.mutate();
|
||||
}}
|
||||
className="h-7 gap-1.5 text-xs text-destructive hover:text-destructive [&_svg]:size-3"
|
||||
>
|
||||
@@ -307,6 +312,7 @@ function ActiveEoiCard({
|
||||
</Button>
|
||||
</div>
|
||||
</footer>
|
||||
{confirmDialog}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
} from '@/components/ui/select';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { usePipelineStore } from '@/stores/pipeline-store';
|
||||
import { PIPELINE_STAGES, STAGE_LABELS, type PipelineStage } from '@/lib/constants';
|
||||
@@ -63,6 +64,7 @@ export function InterestList() {
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
const { viewMode, setViewMode } = usePipelineStore();
|
||||
|
||||
// Force the list view at mobile widths even when the user previously
|
||||
@@ -308,15 +310,14 @@ export function InterestList() {
|
||||
label: 'Archive',
|
||||
icon: Archive,
|
||||
variant: 'destructive',
|
||||
onClick: (ids) => {
|
||||
onClick: async (ids) => {
|
||||
if (ids.length === 0) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Archive ${ids.length} interest${ids.length === 1 ? '' : 's'}? This can be undone from the archived list.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const ok = await confirm({
|
||||
title: `Archive ${ids.length} interest${ids.length === 1 ? '' : 's'}`,
|
||||
description: 'This can be undone from the archived list.',
|
||||
confirmLabel: 'Archive',
|
||||
});
|
||||
if (!ok) return;
|
||||
bulkMutation.mutate({ action: 'archive', ids });
|
||||
},
|
||||
},
|
||||
@@ -464,6 +465,7 @@ export function InterestList() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import { ExternalEoiUploadDialog } from '@/components/interests/external-eoi-upl
|
||||
import { SigningProgress } from '@/components/documents/signing-progress';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useUIStore } from '@/stores/ui-store';
|
||||
|
||||
@@ -200,6 +201,7 @@ function ActiveReservationCard({
|
||||
onUploadSigned: () => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const { data: signersRes, isLoading: signersLoading } = useQuery<{ data: DocumentSigner[] }>({
|
||||
queryKey: ['documents', doc.id, 'signers'],
|
||||
@@ -309,10 +311,13 @@ function ActiveReservationCard({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={cancelMutation.isPending}
|
||||
onClick={() => {
|
||||
if (window.confirm('Cancel this contract? Signers will no longer be able to sign.')) {
|
||||
cancelMutation.mutate();
|
||||
}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: 'Cancel contract',
|
||||
description: 'Signers will no longer be able to sign.',
|
||||
confirmLabel: 'Cancel contract',
|
||||
});
|
||||
if (ok) cancelMutation.mutate();
|
||||
}}
|
||||
className="h-7 gap-1.5 text-xs text-destructive hover:text-destructive [&_svg]:size-3"
|
||||
>
|
||||
@@ -321,6 +326,7 @@ function ActiveReservationCard({
|
||||
</Button>
|
||||
</div>
|
||||
</footer>
|
||||
{confirmDialog}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import { InterestEoiTab } from '@/components/interests/interest-eoi-tab';
|
||||
import { InterestContactLogTab } from '@/components/interests/interest-contact-log-tab';
|
||||
import { InterestContractTab } from '@/components/interests/interest-contract-tab';
|
||||
import { InterestReservationTab } from '@/components/interests/interest-reservation-tab';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -179,7 +180,7 @@ interface MilestoneSectionProps {
|
||||
hideAutoButton?: boolean;
|
||||
}>;
|
||||
status: string | null;
|
||||
onAdvance: (stage: string, milestoneDate?: string) => void;
|
||||
onAdvance: (stage: string, milestoneDate?: string) => void | Promise<void>;
|
||||
isPending: boolean;
|
||||
/** Current pipelineStage. Used to mark steps as done when the pipeline has
|
||||
* moved past their advanceStage even if the date stamp is missing - e.g.
|
||||
@@ -408,7 +409,7 @@ function FutureMilestones({
|
||||
footer?: React.ReactNode;
|
||||
}>;
|
||||
stageMutation: ReturnType<typeof useStageMutation>;
|
||||
advance: (stage: string) => void;
|
||||
advance: (stage: string) => void | Promise<void>;
|
||||
activeMilestone: 'berth_interest' | 'eoi' | 'deposit' | 'contract' | null;
|
||||
currentStage: string;
|
||||
}) {
|
||||
@@ -464,6 +465,7 @@ function OverviewTab({
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const mutation = useInterestPatch(interestId);
|
||||
const stageMutation = useStageMutation(interestId);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
const save = (field: InterestPatchField) => async (next: string | null) => {
|
||||
await mutation.mutateAsync({ [field]: next });
|
||||
};
|
||||
@@ -475,17 +477,19 @@ function OverviewTab({
|
||||
* skip-ahead pattern from the inline stage picker so audit trails
|
||||
* stay consistent regardless of which surface the rep used.
|
||||
*/
|
||||
const advance = (stage: string, milestoneDate?: string) => {
|
||||
const advance = async (stage: string, milestoneDate?: string) => {
|
||||
const fromStage = interest.pipelineStage as PipelineStage;
|
||||
const toStage = stage as PipelineStage;
|
||||
const isOverride = fromStage !== toStage && !canTransitionStage(fromStage, toStage);
|
||||
if (isOverride) {
|
||||
const ok = window.confirm(
|
||||
`This advances the stage from "${fromStage.replace(/_/g, ' ')}" to "${toStage.replace(
|
||||
const ok = await confirm({
|
||||
title: 'Skip-ahead stage change',
|
||||
description: `This advances the stage from "${fromStage.replace(/_/g, ' ')}" to "${toStage.replace(
|
||||
/_/g,
|
||||
' ',
|
||||
)}", which isn't a standard next step. Continue?\n\nThe change will be flagged in the audit log.`,
|
||||
);
|
||||
)}", which isn't a standard next step. The change will be flagged in the audit log.`,
|
||||
confirmLabel: 'Continue',
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
stageMutation.mutate({
|
||||
@@ -864,6 +868,7 @@ function OverviewTab({
|
||||
desiredWidthFt={toNum(interest.desiredWidthFt)}
|
||||
desiredDraftFt={toNum(interest.desiredDraftFt)}
|
||||
/>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
@@ -45,10 +45,27 @@ export function NotificationPreferencesForm() {
|
||||
queryFn: () =>
|
||||
apiFetch<{ data: Pref[] }>('/api/v1/notifications/preferences').then((r) => r.data),
|
||||
});
|
||||
// Key-based remount: body keyed on the server payload signature so its
|
||||
// useState initializer re-runs when prefs land or change. Replaces the
|
||||
// useEffect(setPrefs, [data]) sync the Compiler flagged.
|
||||
const signature = data
|
||||
? data.map((p) => `${p.notificationType}:${p.inApp ? 1 : 0}:${p.email ? 1 : 0}`).join('|')
|
||||
: 'loading';
|
||||
return (
|
||||
<NotificationPreferencesFormBody key={signature} data={data} isLoading={isLoading} qc={qc} />
|
||||
);
|
||||
}
|
||||
|
||||
const [prefs, setPrefs] = useState<Map<string, Pref>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
function NotificationPreferencesFormBody({
|
||||
data,
|
||||
isLoading,
|
||||
qc,
|
||||
}: {
|
||||
data: Pref[] | undefined;
|
||||
isLoading: boolean;
|
||||
qc: ReturnType<typeof useQueryClient>;
|
||||
}) {
|
||||
const [prefs, setPrefs] = useState<Map<string, Pref>>(() => {
|
||||
const map = new Map<string, Pref>();
|
||||
for (const t of KNOWN_TYPES) {
|
||||
map.set(t.key, { notificationType: t.key, inApp: true, email: true });
|
||||
@@ -58,8 +75,8 @@ export function NotificationPreferencesForm() {
|
||||
map.set(p.notificationType, p);
|
||||
}
|
||||
}
|
||||
setPrefs(map);
|
||||
}, [data]);
|
||||
return map;
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -49,23 +49,31 @@ export function ReminderDigestForm() {
|
||||
queryFn: () =>
|
||||
apiFetch<{ data: UserPrefsResponse }>('/api/v1/users/me/preferences').then((r) => r.data),
|
||||
});
|
||||
// Key-based remount: the body is keyed on the loaded payload signature
|
||||
// so the useState initializers re-run when the server data first lands
|
||||
// or genuinely changes. Replaces the prior useEffect(setState) sync.
|
||||
if (isLoading || !data) {
|
||||
return <ReminderDigestFormBody key="loading" data={data} isLoading={isLoading} qc={qc} />;
|
||||
}
|
||||
const r = data.reminders ?? null;
|
||||
const signature = `${r?.delivery ?? ''}|${r?.digestTime ?? ''}|${r?.digestDayOfWeek ?? ''}|${r?.timezone ?? data.timezone ?? ''}`;
|
||||
return <ReminderDigestFormBody key={signature} data={data} isLoading={false} qc={qc} />;
|
||||
}
|
||||
|
||||
const [delivery, setDelivery] = useState<ReminderPrefs['delivery']>('immediate');
|
||||
const [digestTime, setDigestTime] = useState('09:00');
|
||||
const [digestDay, setDigestDay] = useState('1');
|
||||
const [timezone, setTimezone] = useState('Europe/Warsaw');
|
||||
|
||||
useEffect(() => {
|
||||
const r = data?.reminders;
|
||||
if (r) {
|
||||
setDelivery(r.delivery ?? 'immediate');
|
||||
setDigestTime(r.digestTime ?? '09:00');
|
||||
setDigestDay(String(r.digestDayOfWeek ?? 1));
|
||||
setTimezone(r.timezone ?? data?.timezone ?? 'Europe/Warsaw');
|
||||
} else if (data?.timezone) {
|
||||
setTimezone(data.timezone);
|
||||
}
|
||||
}, [data]);
|
||||
function ReminderDigestFormBody({
|
||||
data,
|
||||
isLoading,
|
||||
qc,
|
||||
}: {
|
||||
data: UserPrefsResponse | undefined;
|
||||
isLoading: boolean;
|
||||
qc: ReturnType<typeof useQueryClient>;
|
||||
}) {
|
||||
const r = data?.reminders;
|
||||
const [delivery, setDelivery] = useState<ReminderPrefs['delivery']>(r?.delivery ?? 'immediate');
|
||||
const [digestTime, setDigestTime] = useState(r?.digestTime ?? '09:00');
|
||||
const [digestDay, setDigestDay] = useState(String(r?.digestDayOfWeek ?? 1));
|
||||
const [timezone, setTimezone] = useState(r?.timezone ?? data?.timezone ?? 'Europe/Warsaw');
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () =>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -45,7 +46,20 @@ interface ReminderFormProps {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export function ReminderForm({
|
||||
export function ReminderForm(props: ReminderFormProps) {
|
||||
// Key-based remount: the body is keyed on `open + reminder.id` so its
|
||||
// useState initializers re-run on each open with the correct seed.
|
||||
// Replaces the prior useEffect-driven open→reset that the Compiler
|
||||
// flagged as set-state-in-effect.
|
||||
return (
|
||||
<ReminderFormBody
|
||||
key={props.open ? `open:${props.reminder?.id ?? 'new'}` : 'closed'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ReminderFormBody({
|
||||
open,
|
||||
onOpenChange,
|
||||
reminder,
|
||||
@@ -54,58 +68,33 @@ export function ReminderForm({
|
||||
defaultBerthId,
|
||||
onSuccess,
|
||||
}: ReminderFormProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [note, setNote] = useState('');
|
||||
const [dueAt, setDueAt] = useState('');
|
||||
const [priority, setPriority] = useState('medium');
|
||||
const [assignedTo, setAssignedTo] = useState('');
|
||||
const [clientId, setClientId] = useState('');
|
||||
const [interestId, setInterestId] = useState('');
|
||||
const [berthId, setBerthId] = useState('');
|
||||
const [users, setUsers] = useState<UserOption[]>([]);
|
||||
const isEdit = !!reminder;
|
||||
// Tomorrow 9am default for new-reminder dueAt.
|
||||
const defaultDueAt = useMemo(() => {
|
||||
const t = new Date();
|
||||
t.setDate(t.getDate() + 1);
|
||||
t.setHours(9, 0, 0, 0);
|
||||
return t.toISOString().slice(0, 16);
|
||||
}, []);
|
||||
const [title, setTitle] = useState(reminder?.title ?? '');
|
||||
const [note, setNote] = useState(reminder?.note ?? '');
|
||||
const [dueAt, setDueAt] = useState(reminder ? reminder.dueAt.slice(0, 16) : defaultDueAt);
|
||||
const [priority, setPriority] = useState(reminder?.priority ?? 'medium');
|
||||
const [assignedTo, setAssignedTo] = useState(reminder?.assignedTo ?? '');
|
||||
const [clientId, setClientId] = useState(reminder?.clientId ?? defaultClientId ?? '');
|
||||
const [interestId, setInterestId] = useState(reminder?.interestId ?? defaultInterestId ?? '');
|
||||
const [berthId, setBerthId] = useState(reminder?.berthId ?? defaultBerthId ?? '');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { can } = usePermissions();
|
||||
const canAssignOthers = can('reminders', 'assign_others');
|
||||
|
||||
const isEdit = !!reminder;
|
||||
|
||||
useEffect(() => {
|
||||
if (open && canAssignOthers) {
|
||||
void apiFetch<{ data: UserOption[] }>('/api/v1/admin/users/options').then((res) =>
|
||||
setUsers(res.data),
|
||||
);
|
||||
}
|
||||
}, [open, canAssignOthers]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (reminder) {
|
||||
setTitle(reminder.title);
|
||||
setNote(reminder.note ?? '');
|
||||
setDueAt(reminder.dueAt.slice(0, 16)); // datetime-local format
|
||||
setPriority(reminder.priority);
|
||||
setAssignedTo(reminder.assignedTo ?? '');
|
||||
setClientId(reminder.clientId ?? '');
|
||||
setInterestId(reminder.interestId ?? '');
|
||||
setBerthId(reminder.berthId ?? '');
|
||||
} else {
|
||||
setTitle('');
|
||||
setNote('');
|
||||
// Default to tomorrow 9 AM
|
||||
const tomorrow = new Date();
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
tomorrow.setHours(9, 0, 0, 0);
|
||||
setDueAt(tomorrow.toISOString().slice(0, 16));
|
||||
setPriority('medium');
|
||||
setAssignedTo('');
|
||||
setClientId(defaultClientId ?? '');
|
||||
setInterestId(defaultInterestId ?? '');
|
||||
setBerthId(defaultBerthId ?? '');
|
||||
}
|
||||
setError(null);
|
||||
}
|
||||
}, [open, reminder, defaultClientId, defaultInterestId, defaultBerthId]);
|
||||
// useQuery replaces the prior useEffect(fetch+setState) pattern.
|
||||
const usersQuery = useQuery<{ data: UserOption[] }>({
|
||||
queryKey: ['admin', 'users', 'options'],
|
||||
queryFn: () => apiFetch('/api/v1/admin/users/options'),
|
||||
enabled: open && canAssignOthers,
|
||||
});
|
||||
const users = usersQuery.data?.data ?? [];
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { type ColumnDef } from '@tanstack/react-table';
|
||||
import { Plus, CheckCircle2, Clock, Pencil, XCircle, AlertTriangle, Bell } from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
@@ -71,8 +72,6 @@ interface ReminderListProps {
|
||||
}
|
||||
|
||||
export function ReminderList({ embedded = false }: ReminderListProps = {}) {
|
||||
const [reminders, setReminders] = useState<Reminder[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
useCreateFromUrl(() => setFormOpen(true));
|
||||
const [editingReminder, setEditingReminder] = useState<Reminder | null>(null);
|
||||
@@ -80,57 +79,50 @@ export function ReminderList({ embedded = false }: ReminderListProps = {}) {
|
||||
const [viewMode, setViewMode] = useState<'my' | 'all'>('my');
|
||||
const [statusFilter, setStatusFilter] = useState<string>('active');
|
||||
const [priorityFilter, setPriorityFilter] = useState<string>('all');
|
||||
const [total, setTotal] = useState(0);
|
||||
const { can } = usePermissions();
|
||||
const canViewAll = can('reminders', 'view_all');
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const fetchReminders = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// useQuery replaces the prior useEffect(fetch+setState) pattern.
|
||||
// The query key captures every filter so a switch refetches; the
|
||||
// mutation handlers below invalidate-by-prefix to refresh after
|
||||
// complete/dismiss.
|
||||
const remindersQuery = useQuery<{ reminders: Reminder[]; total: number }>({
|
||||
queryKey: ['reminders', viewMode, statusFilter, priorityFilter],
|
||||
queryFn: async () => {
|
||||
if (viewMode === 'my') {
|
||||
const res = await apiFetch<{ data: Reminder[] }>('/api/v1/reminders/my');
|
||||
let filtered = res.data;
|
||||
if (priorityFilter !== 'all') {
|
||||
filtered = filtered.filter((r) => r.priority === priorityFilter);
|
||||
}
|
||||
setReminders(filtered);
|
||||
setTotal(filtered.length);
|
||||
} else {
|
||||
const params = new URLSearchParams({ limit: '50', order: 'asc', sort: 'dueAt' });
|
||||
if (statusFilter === 'active') {
|
||||
params.set('status', 'pending');
|
||||
} else if (statusFilter !== 'all') {
|
||||
params.set('status', statusFilter);
|
||||
}
|
||||
if (priorityFilter !== 'all') {
|
||||
params.set('priority', priorityFilter);
|
||||
}
|
||||
const res = await apiFetch<{
|
||||
data: Reminder[];
|
||||
pagination: { total: number };
|
||||
}>(`/api/v1/reminders?${params}`);
|
||||
setReminders(res.data);
|
||||
setTotal(res.pagination.total);
|
||||
const filtered =
|
||||
priorityFilter === 'all'
|
||||
? res.data
|
||||
: res.data.filter((r) => r.priority === priorityFilter);
|
||||
return { reminders: filtered, total: filtered.length };
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [viewMode, statusFilter, priorityFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchReminders();
|
||||
}, [fetchReminders]);
|
||||
const sp = new URLSearchParams({ limit: '50', order: 'asc', sort: 'dueAt' });
|
||||
if (statusFilter === 'active') sp.set('status', 'pending');
|
||||
else if (statusFilter !== 'all') sp.set('status', statusFilter);
|
||||
if (priorityFilter !== 'all') sp.set('priority', priorityFilter);
|
||||
const res = await apiFetch<{
|
||||
data: Reminder[];
|
||||
pagination: { total: number };
|
||||
}>(`/api/v1/reminders?${sp}`);
|
||||
return { reminders: res.data, total: res.pagination.total };
|
||||
},
|
||||
});
|
||||
const reminders = remindersQuery.data?.reminders ?? [];
|
||||
const total = remindersQuery.data?.total ?? 0;
|
||||
const loading = remindersQuery.isLoading;
|
||||
|
||||
async function handleComplete(id: string) {
|
||||
await apiFetch(`/api/v1/reminders/${id}/complete`, { method: 'POST' });
|
||||
await fetchReminders();
|
||||
void queryClient.invalidateQueries({ queryKey: ['reminders'] });
|
||||
}
|
||||
|
||||
async function handleDismiss(id: string) {
|
||||
await apiFetch(`/api/v1/reminders/${id}/dismiss`, { method: 'POST' });
|
||||
await fetchReminders();
|
||||
void queryClient.invalidateQueries({ queryKey: ['reminders'] });
|
||||
}
|
||||
|
||||
function isOverdue(dueAt: string, status: string): boolean {
|
||||
@@ -399,7 +391,7 @@ export function ReminderList({ embedded = false }: ReminderListProps = {}) {
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
reminder={editingReminder}
|
||||
onSuccess={fetchReminders}
|
||||
onSuccess={() => queryClient.invalidateQueries({ queryKey: ['reminders'] })}
|
||||
/>
|
||||
|
||||
<SnoozeDialog
|
||||
@@ -408,7 +400,7 @@ export function ReminderList({ embedded = false }: ReminderListProps = {}) {
|
||||
if (!open) setSnoozingId(null);
|
||||
}}
|
||||
reminderId={snoozingId}
|
||||
onSuccess={fetchReminders}
|
||||
onSuccess={() => queryClient.invalidateQueries({ queryKey: ['reminders'] })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -128,6 +128,9 @@ export function CommandSearch() {
|
||||
const [lastAllTotals, setLastAllTotals] = useState<SearchResults['totals'] | null>(null);
|
||||
useEffect(() => {
|
||||
if (activeBucket === 'all' && results?.totals) {
|
||||
// Snapshot the totals at the moment the user is on "All" so the
|
||||
// chips stay stable when they switch to a filtered bucket.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setLastAllTotals(results.totals);
|
||||
}
|
||||
}, [activeBucket, results]);
|
||||
@@ -220,8 +223,10 @@ export function CommandSearch() {
|
||||
});
|
||||
}, [showDropdown, query, results, recentlyViewed, recentSearches, activeBucket, portSlug]);
|
||||
|
||||
// Reset focus index when the visible row set changes.
|
||||
// Reset focus index when the visible row set changes. The set-state
|
||||
// is intentional — external state (bucket / query) drives focus.
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setFocusIndex(-1);
|
||||
}, [activeBucket, query]);
|
||||
|
||||
|
||||
@@ -70,11 +70,14 @@ export function MobileSearchOverlay({ open, onOpenChange }: MobileSearchOverlayP
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setVisibleHeight(null);
|
||||
return;
|
||||
}
|
||||
const vv = window.visualViewport;
|
||||
if (!vv) return;
|
||||
// Subscribing to the visualViewport external store — canonical
|
||||
// useEffect+setState shape for that pattern.
|
||||
const update = () => setVisibleHeight(vv.height);
|
||||
update();
|
||||
vv.addEventListener('resize', update);
|
||||
@@ -98,6 +101,7 @@ export function MobileSearchOverlay({ open, onOpenChange }: MobileSearchOverlayP
|
||||
const [lastAllTotals, setLastAllTotals] = useState<SearchResults['totals'] | null>(null);
|
||||
useEffect(() => {
|
||||
if (activeBucket === 'all' && results?.totals) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setLastAllTotals(results.totals);
|
||||
}
|
||||
}, [activeBucket, results]);
|
||||
@@ -120,8 +124,11 @@ export function MobileSearchOverlay({ open, onOpenChange }: MobileSearchOverlayP
|
||||
|
||||
// Reset query when the drawer closes. Without this, reopening the
|
||||
// overlay would flash stale results before the empty state renders.
|
||||
// setState in effect is intentional — the trigger is a discrete
|
||||
// open/close transition.
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setQuery('');
|
||||
setActiveBucket('all');
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { WarningCallout } from '@/components/ui/warning-callout';
|
||||
import { PageHeader } from '@/components/shared/page-header';
|
||||
import { CountryCombobox } from '@/components/shared/country-combobox';
|
||||
import { PhoneInput, type PhoneInputValue } from '@/components/shared/phone-input';
|
||||
@@ -91,11 +92,12 @@ export function UserSettings() {
|
||||
}, [detectedTz]);
|
||||
|
||||
// When the user picks a country and no timezone is set, suggest the
|
||||
// primary zone for that country. Doesn't fight an explicit timezone
|
||||
// selection — only fires while the timezone slot is empty.
|
||||
// primary zone for that country. setState in effect is intentional —
|
||||
// we're reacting to a discrete user choice (country picker).
|
||||
useEffect(() => {
|
||||
if (!country || timezone) return;
|
||||
const primary = primaryTimezoneFor(country as CountryCode);
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
if (primary) setTimezone(primary);
|
||||
}, [country, timezone]);
|
||||
|
||||
@@ -319,20 +321,22 @@ export function UserSettings() {
|
||||
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>
|
||||
<WarningCallout icon={false}>
|
||||
<span className="flex items-start gap-2 text-xs">
|
||||
<Globe aria-hidden className="h-3.5 w-3.5 shrink-0 mt-0.5" />
|
||||
<span 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>
|
||||
</span>
|
||||
</span>
|
||||
</WarningCallout>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { CountryCombobox } from '@/components/shared/country-combobox';
|
||||
import { SubdivisionCombobox } from '@/components/shared/subdivision-combobox';
|
||||
import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { toastError } from '@/lib/api/toast-error';
|
||||
import type { CountryCode } from '@/lib/i18n/countries';
|
||||
@@ -41,6 +42,7 @@ interface AddressesEditorProps {
|
||||
export function AddressesEditor({ endpoint, invalidateKey, addresses }: AddressesEditorProps) {
|
||||
const qc = useQueryClient();
|
||||
const [adding, setAdding] = useState(false);
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
function invalidate() {
|
||||
qc.invalidateQueries({ queryKey: invalidateKey });
|
||||
@@ -74,7 +76,12 @@ export function AddressesEditor({ endpoint, invalidateKey, addresses }: Addresse
|
||||
address={a}
|
||||
onUpdate={(patch) => updateMutation.mutateAsync({ id: a.id, patch })}
|
||||
onRemove={async () => {
|
||||
if (!confirm('Remove this address?')) return;
|
||||
const ok = await confirm({
|
||||
title: 'Remove address',
|
||||
description: 'Remove this address?',
|
||||
confirmLabel: 'Remove',
|
||||
});
|
||||
if (!ok) return;
|
||||
await removeMutation.mutateAsync(a.id);
|
||||
}}
|
||||
/>
|
||||
@@ -102,6 +109,7 @@ export function AddressesEditor({ endpoint, invalidateKey, addresses }: Addresse
|
||||
Add address
|
||||
</Button>
|
||||
)}
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
import { STAGE_LABELS, formatSource, type PipelineStage } from '@/lib/constants';
|
||||
import { STAGE_LABELS, formatEnum, formatSource, type PipelineStage } from '@/lib/constants';
|
||||
|
||||
interface AuditRow {
|
||||
id: string;
|
||||
@@ -51,11 +51,11 @@ function formatValueForField(field: string | null, value: unknown): string {
|
||||
const f = field.replace(/_/g, '').toLowerCase();
|
||||
if (typeof value === 'string') {
|
||||
if (f === 'pipelinestage' || f === 'stage') {
|
||||
return STAGE_LABELS[value as PipelineStage] ?? value.replace(/_/g, ' ');
|
||||
return STAGE_LABELS[value as PipelineStage] ?? formatEnum(value);
|
||||
}
|
||||
if (f === 'source') return formatSource(value) ?? value;
|
||||
if (f === 'leadcategory' || f === 'category' || f === 'outcome') {
|
||||
return value.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
return formatEnum(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,14 @@ export type InlineEditableFieldProps = TextProps | SelectFieldProps | TextareaPr
|
||||
* Enter/blur and cancels on Escape.
|
||||
*/
|
||||
export function InlineEditableField(props: InlineEditableFieldProps) {
|
||||
// Key-based remount: keying the inner body on `value` re-runs the
|
||||
// `useState(value)` initializer whenever the prop changes externally
|
||||
// (optimistic-update settle, parent refetch). Replaces the prior
|
||||
// useEffect(setDraft, [value]) Compiler-flagged set-state-in-effect.
|
||||
return <InlineEditableFieldBody key={String(props.value ?? '')} {...props} />;
|
||||
}
|
||||
|
||||
function InlineEditableFieldBody(props: InlineEditableFieldProps) {
|
||||
const { value, displayValue, onSave, placeholder, emptyText = '-', className, disabled } = props;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(value ?? '');
|
||||
@@ -73,10 +81,6 @@ export function InlineEditableField(props: InlineEditableFieldProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(value ?? '');
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editing) {
|
||||
if (inputRef.current) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Check, ChevronsUpDown } from 'lucide-react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
@@ -42,15 +42,16 @@ export function OwnerPicker({
|
||||
disabled,
|
||||
}: OwnerPickerProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [type, setType] = useState<'client' | 'company'>(value?.type ?? 'client');
|
||||
// `type` is derived: when an owner is selected the prop wins; with no
|
||||
// selection the user's local tab pick is the source of truth. Render-
|
||||
// phase derivation replaces the prior useEffect(setType, [value?.type])
|
||||
// that the Compiler flagged as set-state-in-effect.
|
||||
const [localType, setLocalType] = useState<'client' | 'company'>(value?.type ?? 'client');
|
||||
const type: 'client' | 'company' = value?.type ?? localType;
|
||||
const setType = setLocalType;
|
||||
const [search, setSearch] = useState('');
|
||||
const debounced = useDebounce(search, 300);
|
||||
|
||||
// Keep local `type` in sync if value.type changes externally.
|
||||
useEffect(() => {
|
||||
if (value?.type) setType(value.type);
|
||||
}, [value?.type]);
|
||||
|
||||
const endpoint =
|
||||
type === 'client'
|
||||
? `/api/v1/clients/options?search=${encodeURIComponent(debounced)}`
|
||||
|
||||
@@ -36,18 +36,15 @@ export function ReminderDaysInput({
|
||||
className,
|
||||
}: ReminderDaysInputProps) {
|
||||
const isPreset = typeof value === 'number' && (PRESETS as readonly number[]).includes(value);
|
||||
const [customStr, setCustomStr] = React.useState<string>(() =>
|
||||
!isPreset && typeof value === 'number' ? String(value) : '',
|
||||
);
|
||||
|
||||
// Sync external value → custom input when it changes to a non-preset.
|
||||
React.useEffect(() => {
|
||||
if (typeof value === 'number' && !(PRESETS as readonly number[]).includes(value)) {
|
||||
setCustomStr(String(value));
|
||||
} else if (value == null) {
|
||||
setCustomStr('');
|
||||
}
|
||||
}, [value]);
|
||||
// Derived from the prop: a non-preset numeric value renders its string
|
||||
// form; null/preset values show empty. Local edits flow through onChange
|
||||
// and bounce back via `value` so render-phase derivation stays correct.
|
||||
const customStr = !isPreset && typeof value === 'number' ? String(value) : '';
|
||||
const [draftStr, setDraftStr] = React.useState<string>(customStr);
|
||||
// When the user is mid-typing (`draftStr` set), keep their text; otherwise
|
||||
// show the derived value. Resets when value changes externally because
|
||||
// the derived `customStr` overrides on commit.
|
||||
const shownStr = draftStr !== '' ? draftStr : customStr;
|
||||
|
||||
return (
|
||||
<div className={cn('space-y-2', className)}>
|
||||
@@ -79,10 +76,10 @@ export function ReminderDaysInput({
|
||||
step={1}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
value={customStr}
|
||||
value={shownStr}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
setCustomStr(raw);
|
||||
setDraftStr(raw);
|
||||
if (raw === '') {
|
||||
onChange(null);
|
||||
return;
|
||||
@@ -90,6 +87,7 @@ export function ReminderDaysInput({
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (Number.isFinite(n) && n > 0) onChange(n);
|
||||
}}
|
||||
onBlur={() => setDraftStr('')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* - Body length capped at 50KB; char count visible.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
@@ -59,7 +59,20 @@ interface PreviewResponse {
|
||||
data: { html: string; markdown: string; unresolved: string[] };
|
||||
}
|
||||
|
||||
export function SendDocumentDialog({
|
||||
export function SendDocumentDialog(props: SendDocumentDialogProps) {
|
||||
// Key-based remount: the body is keyed on `open + recipient.email` so
|
||||
// its useState initializers re-run each time the dialog opens with a
|
||||
// new recipient. Replaces the prior useEffect-driven reset that the
|
||||
// Compiler flagged as set-state-in-effect.
|
||||
return (
|
||||
<SendDocumentDialogInner
|
||||
key={props.open ? `open:${props.recipient.email ?? ''}` : 'closed'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SendDocumentDialogInner({
|
||||
open,
|
||||
onOpenChange,
|
||||
documentKind,
|
||||
@@ -73,14 +86,6 @@ export function SendDocumentDialog({
|
||||
const [emailOverride, setEmailOverride] = useState(recipient.email ?? '');
|
||||
const [customBody, setCustomBody] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('compose');
|
||||
setEmailOverride(recipient.email ?? '');
|
||||
setCustomBody('');
|
||||
}
|
||||
}, [open, recipient.email]);
|
||||
|
||||
const recipientForApi = useMemo(
|
||||
() => ({
|
||||
clientId: recipient.clientId,
|
||||
|
||||
@@ -65,6 +65,11 @@ const Carousel = React.forwardRef<
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return;
|
||||
// Embla doesn't fire 'select' on mount, so we sync state from the
|
||||
// external store once here. This is the canonical pattern for
|
||||
// subscribing to a third-party event source and is intentionally
|
||||
// flagged-but-allowed.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
onSelect(api);
|
||||
api.on('reInit', onSelect);
|
||||
api.on('select', onSelect);
|
||||
|
||||
48
src/components/ui/warning-callout.tsx
Normal file
48
src/components/ui/warning-callout.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import * as React from 'react';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* Compact amber-bordered alert callout. Replaces the dozen-plus ad-hoc
|
||||
* `border-amber-{200,300} bg-amber-50` `<div>`s scattered through the
|
||||
* codebase that the ui/ux audit (L5) flagged as drift.
|
||||
*
|
||||
* Renders a leading triangle icon by default; pass `icon={false}` to
|
||||
* suppress when the surrounding layout already conveys the warning
|
||||
* semantics. The icon is `aria-hidden` because the text content always
|
||||
* carries the meaning.
|
||||
*/
|
||||
export interface WarningCalloutProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
|
||||
/** Optional pre-content heading rendered bolder than the body. */
|
||||
title?: React.ReactNode;
|
||||
/** Set false to suppress the leading icon. */
|
||||
icon?: boolean;
|
||||
}
|
||||
|
||||
export function WarningCallout({
|
||||
title,
|
||||
icon = true,
|
||||
className,
|
||||
children,
|
||||
...rest
|
||||
}: WarningCalloutProps) {
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className={cn(
|
||||
'rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900',
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
{icon ? <AlertTriangle aria-hidden className="mt-0.5 size-4 shrink-0" /> : null}
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
{title ? <div className="font-medium">{title}</div> : null}
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -30,12 +30,14 @@ import { getYachtColumns, type YachtRow } from '@/components/yachts/yacht-column
|
||||
import { useCreateFromUrl } from '@/hooks/use-create-from-url';
|
||||
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
|
||||
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
|
||||
import { useConfirmation } from '@/hooks/use-confirmation';
|
||||
import { apiFetch } from '@/lib/api/client';
|
||||
|
||||
export function YachtList() {
|
||||
const params = useParams<{ portSlug: string }>();
|
||||
const portSlug = params?.portSlug ?? '';
|
||||
const queryClient = useQueryClient();
|
||||
const { confirm, dialog: confirmDialog } = useConfirmation();
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
useCreateFromUrl(() => setCreateOpen(true));
|
||||
@@ -181,15 +183,14 @@ export function YachtList() {
|
||||
label: 'Archive',
|
||||
icon: Archive,
|
||||
variant: 'destructive',
|
||||
onClick: (ids) => {
|
||||
onClick: async (ids) => {
|
||||
if (ids.length === 0) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Archive ${ids.length} yacht${ids.length === 1 ? '' : 's'}? This can be undone from the archived list.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const ok = await confirm({
|
||||
title: `Archive ${ids.length} yacht${ids.length === 1 ? '' : 's'}`,
|
||||
description: 'This can be undone from the archived list.',
|
||||
confirmLabel: 'Archive',
|
||||
});
|
||||
if (!ok) return;
|
||||
bulkMutation.mutate({ action: 'archive', ids });
|
||||
},
|
||||
},
|
||||
@@ -290,6 +291,7 @@ export function YachtList() {
|
||||
onConfirm={() => archiveYacht && archiveMutation.mutate(archiveYacht.id)}
|
||||
isLoading={archiveMutation.isPending}
|
||||
/>
|
||||
{confirmDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user