Files
pn-new-crm/src/components/clients/bulk-archive-wizard.tsx

319 lines
12 KiB
TypeScript
Raw Normal View History

'use client';
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';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
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 {
clientId: string;
fullName: string;
stakeLevel: 'low' | 'high';
highStakesStage: string | null;
blockers: string[];
summary: { berths: number; yachts: number; reservations: number; signedDocs: number };
}
interface Props {
open: boolean;
onOpenChange: (next: boolean) => void;
clientIds: string[];
onSuccess?: () => void;
}
type Stage = 'preflight' | 'reasons' | 'confirm';
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>>({});
const [carouselIndex, setCarouselIndex] = useState(0);
const preflight = useQuery({
queryKey: ['bulk-archive-preflight', clientIds.join(',')],
queryFn: () =>
apiFetch<{ data: PreflightItem[] }>('/api/v1/clients/bulk-archive-preflight', {
method: 'POST',
body: { ids: clientIds },
}).then((r) => r.data),
enabled: open && clientIds.length > 0,
});
const items = preflight.data ?? [];
const blocked = useMemo(() => items.filter((i) => i.blockers.length > 0), [items]);
const highStakes = useMemo(
() => items.filter((i) => i.stakeLevel === 'high' && i.blockers.length === 0),
[items],
);
const lowStakes = useMemo(
() => items.filter((i) => i.stakeLevel === 'low' && i.blockers.length === 0),
[items],
);
const archivable = useMemo(() => [...lowStakes, ...highStakes], [lowStakes, highStakes]);
const allHighStakesReasoned = useMemo(
() => highStakes.every((i) => (reasons[i.clientId]?.trim().length ?? 0) >= 5),
[highStakes, reasons],
);
const archiveMutation = useMutation({
mutationFn: () =>
apiFetch<{ data: { summary: { total: number; succeeded: number; failed: number } } }>(
'/api/v1/clients/bulk',
{
method: 'POST',
body: {
action: 'archive',
ids: archivable.map((i) => i.clientId),
reasonsByClientId: reasons,
},
},
),
onSuccess: (res) => {
const s = res.data.summary;
if (s.failed === 0) {
toast.success(`${s.succeeded} client${s.succeeded === 1 ? '' : 's'} archived.`);
} else {
toast.warning(`${s.succeeded} of ${s.total} archived. ${s.failed} failed.`);
}
qc.invalidateQueries({ queryKey: ['clients'] });
onOpenChange(false);
onSuccess?.();
},
onError: (err: unknown) => {
toast.error(err instanceof Error ? err.message : 'Bulk archive failed');
},
});
const currentHighStakes = highStakes[carouselIndex];
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Bulk archive · {clientIds.length} clients</DialogTitle>
<DialogDescription>
Smart archive runs the same backend per client. Late-stage deals require an individual
reason; everything else auto-archives with safe defaults.
</DialogDescription>
</DialogHeader>
{preflight.isLoading ? (
<div className="py-8 text-center text-sm text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
Checking each client
</div>
) : preflight.error ? (
<div className="py-8 text-center text-sm text-red-600">
Preflight failed:{' '}
{preflight.error instanceof Error ? preflight.error.message : 'unknown error'}
</div>
) : (
<>
{stage === 'preflight' && (
<div className="space-y-3 max-h-[60vh] overflow-y-auto pr-1">
<div className="grid grid-cols-3 gap-2 text-sm">
<div className="rounded-md border bg-emerald-50 border-emerald-200 p-3">
<div className="text-2xl font-bold text-emerald-900">{lowStakes.length}</div>
<div className="text-xs text-emerald-800">Auto-archive</div>
</div>
<div className="rounded-md border bg-amber-50 border-amber-200 p-3">
<div className="text-2xl font-bold text-amber-900">{highStakes.length}</div>
<div className="text-xs text-amber-800">Need reason</div>
</div>
<div className="rounded-md border bg-red-50 border-red-200 p-3">
<div className="text-2xl font-bold text-red-900">{blocked.length}</div>
<div className="text-xs text-red-800">Blocked, will skip</div>
</div>
</div>
{blocked.length > 0 && (
<div className="rounded-md border border-red-300 bg-red-50 p-3 text-xs text-red-900 space-y-1">
<div className="font-medium flex items-center gap-1.5">
<AlertTriangle className="h-4 w-4" /> Blocked
</div>
{blocked.slice(0, 5).map((b) => (
<div key={b.clientId}>
<span className="font-medium">{b.fullName}</span>: {b.blockers[0]}
</div>
))}
{blocked.length > 5 && <div>and {blocked.length - 5} more</div>}
</div>
)}
<div className="rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground">
Low-stakes defaults: release available/under-offer berths, keep sold ones, cancel
fix(audit-wave-9): copy/terminology sweep (copy-auditor) Address the highest-impact items from the copy-auditor's CRITICAL + HIGH + MEDIUM bands: **C2 portal raw-status leak** - Drop the staff-only `leadCategory` chip from the portal interests page entirely. Privacy + optics: clients should never see "hot lead" in their own portal. `eoiStatus` was already wrapped in `portalSigningLabel`; only the categorical chip remained. **C3 signing-status label drift** - Add `src/lib/labels/document-status.ts` as the single source of truth for the {draft, sent, partially_signed, completed, expired, cancelled} lifecycle: labels (CRM + portal variants), StatusPill variant, and the "active / in-flight" set. - Wire it into interest-eoi-tab, interest-contract-tab, interest-reservation-tab — they previously redefined identical STATUS_LABELS / ACTIVE_STATUSES blocks per-file. **H1 + M3 verbiage codemod** - `Save Changes` → `Save changes` (sentence case, matches the surrounding admin/CRM pattern). - `Saving...` (ASCII three dots) → `Saving…` (Unicode ellipsis). Matches the project's UTF-8-elsewhere convention and reads correctly via screen-readers. **M1 envelope jargon → signing request** - smart-archive-dialog: "Leave envelope pending" → "Leave signing request pending"; "Void the signing envelope" → "Cancel the signing request"; section header updated to match. - document-detail: "voids the signing envelope" → "cancels the signing request". - bulk-archive-wizard: "leave invoices/signing envelopes alone" → "leave invoices/signing requests alone". - Documenso admin page intentionally keeps `envelope` (dev/integration vocabulary). **M5 Hot Lead casing** - Normalize `Hot Lead` / `General Interest` / `Specific Qualified` to sentence case in `constants.ts` LABEL_OVERRIDES and all per-file lead-category maps so the CRM trend (sentence case) is consistent. **C1 surface-level rename** - "Linked prospect (optional)" → "Linked interest (optional)" on the berth status-change dialog. - "Deal Documents" tab → "Interest Documents" (URL/route kept as `/deal-documents` to avoid breaking deep links; rename deferred). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:12:40 +02:00
reservations, leave invoices/signing requests alone. Yachts stay on the archived
feat: round 2 — stage prompts, berth header, EOI inline edit, measurement units Berth surfaces - New compact mooring-chip header (colored plate + status pill, dock-label in tooltip) replaces the redundant "Berth B1 / Sold / B DOCK" stack - Berth list gains a "Latest deal stage" column showing the most-advanced pipeline stage of any active linked interest (server-aggregated, ranks by PIPELINE_STAGES index) - "Linked prospect" Select on the status-change dialog rebuilt as a Command combobox: search, recent-first sort, stage-coloured pills Pipeline UX - Reverting an interest to Open with linked berths now prompts: keep the links, unlink and reset, or cancel. Silent when no berths are linked - Activity feed + entity-activity feed normalise enum field values via STAGE_LABELS / formatSource: "deposit_10pct → contract_sent" reads as "10% Deposit → Contract Sent" EOI generate dialog - Inline-editable rows for client name, nationality (country combobox), and yacht name — pencil affordance saves directly via clients/yachts PATCH - Replaces the single "Edit on client's page" link with two contextual links framed by short copy explaining what's inline vs what needs the canonical page - Backend EoiContext now includes client.id + yacht.id so the dialog can PATCH without an extra round-trip Company form - New "Connections" section lets the rep attach members (clients) and yachts during create. Yacht attach uses the existing transfer endpoint so audit log + ownership history capture the change - Inline "+ New client" / "+ New yacht" buttons open the canonical forms stacked over the company sheet - After save, the form chains to a yacht pull-in prompt (if any attached client owns yachts not yet linked) and an optional "Create interest" step pre-filled with the first attached client Admin - /admin landing gains a searchable index — typed query flattens groups into a result list matching label + description + group title - "Documenso & EOI" card relabelled to "EOI signing service" (consistent with the user-facing language rename from round 1) Measurement units (migration 0053) - interests gains desired_*_m columns + desired_*_unit discriminators so the rep's literal entry (ft OR m) is preserved verbatim instead of being reconstructed from a single canonical column on every render - yachts + berths gain matching *_unit columns alongside their existing ft + m pairs; defaults to 'ft' so legacy rows still render normally - Interest form POST/PATCH now sends both ft + m + unit; computed m is derived from the ft canonical to keep the recommender SQL unchanged Misc - Active-deals tile + topbar type their Link href as `Route` instead of `any` - Unused REPORT_TYPE_LABELS const dropped from generate-report-form - Test fixtures (fill-eoi-form, documenso-payload, public-berths) updated to include the new id + unit fields on the EoiContext / Berth shapes Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 15:28:22 +02:00
client. To customise per-client, archive that client individually instead.
</div>
</div>
)}
{stage === 'reasons' && currentHighStakes && (
<div className="space-y-3">
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>
Reason {carouselIndex + 1} of {highStakes.length}
</span>
<span className="flex items-center gap-1">
{highStakes.map((_, idx) => (
<span
key={idx}
className={`h-1.5 w-6 rounded-full ${
idx === carouselIndex
? 'bg-amber-500'
: idx < carouselIndex ||
(reasons[highStakes[idx]?.clientId ?? '']?.trim().length ?? 0) >= 5
? 'bg-amber-300'
: 'bg-muted'
}`}
/>
))}
</span>
</div>
<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), `
: ''}
{currentHighStakes.summary.signedDocs > 0
? `${currentHighStakes.summary.signedDocs} signed doc(s), `
: ''}
{currentHighStakes.summary.reservations > 0
? `${currentHighStakes.summary.reservations} reservation(s)`
: ''}
</span>
</WarningCallout>
<Textarea
value={reasons[currentHighStakes.clientId] ?? ''}
onChange={(e) =>
setReasons((prev) => ({
...prev,
[currentHighStakes.clientId]: e.target.value,
}))
}
placeholder="Why are you archiving this late-stage deal? (≥ 5 chars)"
rows={3}
/>
</div>
)}
{stage === 'confirm' && (
<div className="space-y-2 text-sm">
<div className="rounded-md border border-emerald-300 bg-emerald-50 p-3 text-emerald-900 flex items-start gap-2">
<CheckCircle2 className="h-4 w-4 mt-0.5" />
<div>
Ready to archive <strong>{archivable.length}</strong> client
{archivable.length === 1 ? '' : 's'}
{blocked.length > 0 && ` (skipping ${blocked.length} blocked)`}.
</div>
</div>
<p className="text-xs text-muted-foreground">
This action is reversible restore individually from each archived client.
</p>
</div>
)}
</>
)}
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
{stage === 'preflight' && (
<Button
disabled={archivable.length === 0 || preflight.isLoading}
onClick={() => {
if (highStakes.length > 0) {
setCarouselIndex(0);
setStage('reasons');
} else {
setStage('confirm');
}
}}
>
Continue <ArrowRight className="h-4 w-4 ml-1" />
</Button>
)}
{stage === 'reasons' && (
<>
<Button
variant="outline"
disabled={carouselIndex === 0}
onClick={() => setCarouselIndex((i) => Math.max(0, i - 1))}
>
<ArrowLeft className="h-4 w-4 mr-1" /> Back
</Button>
{carouselIndex < highStakes.length - 1 ? (
<Button
disabled={(reasons[currentHighStakes?.clientId ?? '']?.trim().length ?? 0) < 5}
onClick={() => setCarouselIndex((i) => i + 1)}
>
Next <ArrowRight className="h-4 w-4 ml-1" />
</Button>
) : (
<Button disabled={!allHighStakesReasoned} onClick={() => setStage('confirm')}>
Review <ArrowRight className="h-4 w-4 ml-1" />
</Button>
)}
</>
)}
{stage === 'confirm' && (
<Button
variant="destructive"
disabled={archiveMutation.isPending}
onClick={() => archiveMutation.mutate()}
>
{archiveMutation.isPending ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-1.5" /> Archiving
</>
) : (
`Archive ${archivable.length}`
)}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}