feat(client-archive): bulk-archive wizard with per-high-stakes confirmation
Replaces the single window.confirm() with a 3-stage wizard: - preflight: counts auto/needs-reason/blocked (POST /bulk-archive-preflight) - reasons: carousel through high-stakes clients capturing per-client reason (≥5 chars) — bulk endpoint accepts reasonsByClientId map - confirm: shows the final archivable count and submits Low-stakes still auto-archives with safe defaults; blocked clients are skipped with a per-row reason in the preflight summary. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
68
src/app/api/v1/clients/bulk-archive-preflight/route.ts
Normal file
68
src/app/api/v1/clients/bulk-archive-preflight/route.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
import { parseBody } from '@/lib/api/route-helpers';
|
||||
import { getClientArchiveDossier } from '@/lib/services/client-archive-dossier.service';
|
||||
import { errorResponse } from '@/lib/errors';
|
||||
|
||||
const bodySchema = z.object({
|
||||
ids: z.array(z.string().min(1)).min(1).max(100),
|
||||
});
|
||||
|
||||
interface PreflightItem {
|
||||
clientId: string;
|
||||
fullName: string;
|
||||
stakeLevel: 'low' | 'high';
|
||||
highStakesStage: string | null;
|
||||
blockers: string[];
|
||||
summary: { berths: number; yachts: number; reservations: number; signedDocs: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* Preflight check for the bulk-archive wizard. Returns the per-client
|
||||
* stake level + a small summary so the UI can:
|
||||
* - count how many will auto-archive
|
||||
* - cycle through high-stakes clients to capture per-client reasons
|
||||
* - surface blockers (e.g. "has unpaid invoices") for the operator
|
||||
*/
|
||||
export const POST = withAuth(
|
||||
withPermission('clients', 'delete', async (req, ctx) => {
|
||||
try {
|
||||
const { ids } = await parseBody(req, bodySchema);
|
||||
const items: PreflightItem[] = [];
|
||||
for (const id of ids) {
|
||||
try {
|
||||
const d = await getClientArchiveDossier(id, ctx.portId);
|
||||
items.push({
|
||||
clientId: d.client.id,
|
||||
fullName: d.client.fullName,
|
||||
stakeLevel: d.stakeLevel,
|
||||
highStakesStage: d.highStakesStage,
|
||||
blockers: d.blockers,
|
||||
summary: {
|
||||
berths: d.berths.length,
|
||||
yachts: d.yachts.length,
|
||||
reservations: d.reservations.length,
|
||||
signedDocs: d.documents.filter(
|
||||
(doc) => doc.status === 'completed' || doc.status === 'signed',
|
||||
).length,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
items.push({
|
||||
clientId: id,
|
||||
fullName: '(unknown)',
|
||||
stakeLevel: 'low',
|
||||
highStakesStage: null,
|
||||
blockers: [err instanceof Error ? err.message : 'Failed to load dossier'],
|
||||
summary: { berths: 0, yachts: 0, reservations: 0, signedDocs: 0 },
|
||||
});
|
||||
}
|
||||
}
|
||||
return NextResponse.json({ data: items });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -20,6 +20,10 @@ const bulkSchema = z.discriminatedUnion('action', [
|
||||
z.object({
|
||||
action: z.literal('archive'),
|
||||
ids: z.array(z.string().min(1)).min(1).max(100),
|
||||
/** When provided, lifts the high-stakes block on listed clients
|
||||
* individually. The bulk-archive wizard collects these from the
|
||||
* operator one client at a time. Reasons must be ≥5 characters. */
|
||||
reasonsByClientId: z.record(z.string(), z.string().min(5).max(2000)).optional(),
|
||||
}),
|
||||
z.object({
|
||||
action: z.literal('add_tag'),
|
||||
@@ -59,18 +63,21 @@ export const POST = withAuth(async (req, ctx) => {
|
||||
userAgent: ctx.userAgent,
|
||||
};
|
||||
|
||||
const reasonsByClientId = body.action === 'archive' ? (body.reasonsByClientId ?? {}) : {};
|
||||
|
||||
const { results, summary } = await runBulk(body.ids, async (id) => {
|
||||
if (body.action === 'archive') {
|
||||
// Bulk archive uses the smart-archive backend with sensible
|
||||
// low-stakes defaults: release available/under-offer berths,
|
||||
// retain sold ones, cancel active reservations, leave invoices,
|
||||
// leave Documenso envelopes pending. High-stakes clients are
|
||||
// refused — the operator must use the single-client smart dialog
|
||||
// for those (which captures the per-client reason + decisions).
|
||||
// leave Documenso envelopes pending. High-stakes clients require
|
||||
// a per-client reason supplied via reasonsByClientId; the bulk-
|
||||
// archive wizard captures these one at a time before submitting.
|
||||
const dossier = await getClientArchiveDossier(id, ctx.portId);
|
||||
if (dossier.stakeLevel === 'high') {
|
||||
const perClientReason = reasonsByClientId[id];
|
||||
if (dossier.stakeLevel === 'high' && !perClientReason) {
|
||||
throw new Error(
|
||||
`Client at ${dossier.highStakesStage} requires individual archive (open the client to confirm + supply a reason).`,
|
||||
`Client at ${dossier.highStakesStage} requires a per-client reason; supply one in reasonsByClientId.`,
|
||||
);
|
||||
}
|
||||
if (dossier.blockers.length > 0) {
|
||||
@@ -79,10 +86,11 @@ export const POST = withAuth(async (req, ctx) => {
|
||||
const hasSignedDocs = dossier.documents.some(
|
||||
(d) => d.status === 'completed' || d.status === 'signed',
|
||||
);
|
||||
const reason = perClientReason ?? 'Bulk archive (low-stakes auto-mode)';
|
||||
await archiveClientWithDecisions({
|
||||
dossier,
|
||||
decisions: {
|
||||
reason: 'Bulk archive (low-stakes auto-mode)',
|
||||
reason,
|
||||
acknowledgedSignedDocuments: hasSignedDocs,
|
||||
berthDecisions: dossier.berths.map((b) => ({
|
||||
berthId: b.berthId,
|
||||
|
||||
312
src/components/clients/bulk-archive-wizard.tsx
Normal file
312
src/components/clients/bulk-archive-wizard.tsx
Normal file
@@ -0,0 +1,312 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, 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 { 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({ 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,
|
||||
});
|
||||
|
||||
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(
|
||||
() => 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
|
||||
reservations, leave invoices/Documenso envelopes alone. Yachts stay on the
|
||||
archived 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>
|
||||
<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">
|
||||
{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)`
|
||||
: ''}
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { ArchiveConfirmDialog } from '@/components/shared/archive-confirm-dialog
|
||||
import { PermissionGate } from '@/components/shared/permission-gate';
|
||||
import { TagPicker } from '@/components/shared/tag-picker';
|
||||
import { BulkHardDeleteDialog } from '@/components/clients/bulk-hard-delete-dialog';
|
||||
import { BulkArchiveWizard } from '@/components/clients/bulk-archive-wizard';
|
||||
import { usePermissions } from '@/hooks/use-permissions';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -46,6 +47,7 @@ export function ClientList() {
|
||||
);
|
||||
const [tagChoice, setTagChoice] = useState<string[]>([]);
|
||||
const [bulkDeleteIds, setBulkDeleteIds] = useState<string[]>([]);
|
||||
const [bulkArchiveIds, setBulkArchiveIds] = useState<string[]>([]);
|
||||
|
||||
const { can } = usePermissions();
|
||||
const canHardDelete = can('admin', 'permanently_delete_clients');
|
||||
@@ -183,14 +185,7 @@ export function ClientList() {
|
||||
variant: 'destructive',
|
||||
onClick: (ids) => {
|
||||
if (ids.length === 0) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Archive ${ids.length} client${ids.length === 1 ? '' : 's'}? This can be undone from the archived list.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
bulkMutation.mutate({ action: 'archive', ids });
|
||||
setBulkArchiveIds(ids);
|
||||
},
|
||||
},
|
||||
...(canHardDelete
|
||||
@@ -298,6 +293,13 @@ export function ClientList() {
|
||||
clientIds={bulkDeleteIds}
|
||||
onDeleted={() => setBulkDeleteIds([])}
|
||||
/>
|
||||
|
||||
<BulkArchiveWizard
|
||||
open={bulkArchiveIds.length > 0}
|
||||
onOpenChange={(open) => !open && setBulkArchiveIds([])}
|
||||
clientIds={bulkArchiveIds}
|
||||
onSuccess={() => setBulkArchiveIds([])}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user