Files
pn-new-crm/src/components/interests/qualification-checklist.tsx
Matt 6b28459c45 feat(pipeline): 9→7 stage refactor + v1.1 hardening wave
Replaces the legacy 9-stage pipeline with 7 canonical stages
(enquiry → qualified → eoi → reservation → deposit_paid → contract →
nurturing) plus three doc sub-status columns (eoi_doc_status,
reservation_doc_status, contract_doc_status) that track sent/signed
within a single stage instead of branching it.

Schema (migration 0062):
- interests gains assigned_to, deposit_expected_amount/currency,
  three doc-status columns, two documenso-id columns, and
  date_reservation_signed.
- New tables: qualification_criteria (per-port admin-configurable),
  interest_qualifications (per-interest state), payments (deposit /
  balance / refund records keyed to interest + client).
- Default qualification criteria seeded for every existing port.
- Dummy-data UPDATEs collapse Sent/Signed pairs and 'completed' into
  the new stage + doc-status + outcome shape.

Migration 0063 adds interest_contact_log.voice_transcript and
template_used columns for v1.1-A/B (quick-template buttons + voice
transcription via Web Speech API).

v1.1 phase work bundled here:
- A/B: Quick-template buttons (Call / Visit / Email) + mic toggle on
       the contact-log compose dialog (useVoiceTranscription hook).
- C:   berth-rules-engine wraps state writes in pg_advisory_xact_lock
       with an idempotent re-read; emits rule_evaluated audit traces.
- D:   Documenso webhook: reservation/contract sub-status stamping
       moved out of the PDF-download try-block so a download failure
       no longer swallows the stamp. New integration test coverage.
- E:   /admin/qualification-criteria CRUD page + admin component.
- F:   default_new_interest_owner exposed in System Settings.
- G:   recentActivityCount + active_engagement deal-pulse signal
       surfaced as a chip on interests + hot-deals card.
- H:   interest_assigned notification on assignedTo change (skips
       self-assign, uses a dedupe key).

Plus the supporting components: AssignedToChip, DealPulseChip,
PaymentsSection, QualificationChecklist, MultiEoiChip,
SkipAheadBanner, WonStatusPanel, InterestBerthStatusBanner,
SupplementalInfoRequestButton, UserPicker.

Tests: 1370/1370 vitest pass (added deal-health unit suite +
expanded constants/validators/pipeline-transitions coverage). tsc
clean, eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:39:21 +02:00

158 lines
5.2 KiB
TypeScript

'use client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useParams } from 'next/navigation';
import { CheckCircle2, ChevronRight } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { cn } from '@/lib/utils';
interface QualificationRow {
key: string;
label: string;
description: string | null;
enabled: boolean;
displayOrder: number;
confirmed: boolean;
confirmedAt: string | null;
confirmedBy: string | null;
notes: string | null;
}
interface QualificationResponse {
data: {
criteria: QualificationRow[];
fullyQualified: boolean;
};
}
/**
* Per-interest qualification checklist. Hidden when the port has no
* enabled criteria. When the rep has confirmed every enabled criterion AND
* the deal is still in 'enquiry', a soft hint surfaces a Promote button
* that advances the stage to 'qualified' through the standard transition
* endpoint (no override; this is the canonical adjacent move).
*/
export function QualificationChecklist({
interestId,
currentStage,
}: {
interestId: string;
currentStage: string;
}) {
const params = useParams<{ portSlug: string }>();
const queryClient = useQueryClient();
const { data, isLoading } = useQuery<QualificationResponse>({
queryKey: ['interest-qualifications', interestId],
queryFn: () => apiFetch(`/api/v1/interests/${interestId}/qualifications`),
});
const toggleMutation = useMutation({
mutationFn: async (vars: { criterionKey: string; confirmed: boolean }) =>
apiFetch(`/api/v1/interests/${interestId}/qualifications`, {
method: 'PUT',
body: { criterionKey: vars.criterionKey, confirmed: vars.confirmed },
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['interest-qualifications', interestId] });
},
onError: (err) => toastError(err),
});
const promoteMutation = useMutation({
mutationFn: async () =>
apiFetch(`/api/v1/interests/${interestId}/stage`, {
method: 'POST',
body: { pipelineStage: 'qualified' },
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['interests', interestId] });
queryClient.invalidateQueries({ queryKey: ['interests'] });
},
onError: (err) => toastError(err),
});
if (isLoading) return null;
if (!data) return null;
const criteria = data.data.criteria;
if (criteria.length === 0) return null;
const fullyQualified = data.data.fullyQualified;
const showPromoteHint = fullyQualified && currentStage === 'enquiry';
// Avoid referencing `params` in the JSX so the unused destructure passes
// strict noUnused checks; it stays available for future deep-link hooks.
void params;
return (
<section className="rounded-lg border bg-card/40 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="text-sm font-semibold">Qualification</h3>
{fullyQualified ? (
<span className="inline-flex items-center gap-1 text-xs text-emerald-700">
<CheckCircle2 className="size-3.5" aria-hidden />
All confirmed
</span>
) : (
<span className="text-xs text-muted-foreground">
{criteria.filter((c) => c.confirmed).length} of {criteria.length} confirmed
</span>
)}
</div>
<ul className="space-y-2">
{criteria.map((c) => (
<li key={c.key} className="flex items-start gap-2.5">
<Checkbox
id={`qual-${c.key}`}
checked={c.confirmed}
disabled={toggleMutation.isPending}
onCheckedChange={(v) =>
toggleMutation.mutate({ criterionKey: c.key, confirmed: v === true })
}
className="mt-0.5"
/>
<label
htmlFor={`qual-${c.key}`}
className={cn(
'flex-1 text-sm cursor-pointer',
c.confirmed ? 'text-foreground' : 'text-foreground/90',
)}
>
<span
className={cn('font-medium', c.confirmed && 'line-through text-muted-foreground')}
>
{c.label}
</span>
{c.description ? (
<p className="mt-0.5 text-xs text-muted-foreground">{c.description}</p>
) : null}
</label>
</li>
))}
</ul>
{showPromoteHint ? (
<div className="flex items-center justify-between rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2">
<p className="text-xs text-emerald-800">
All criteria confirmed this lead is ready to qualify.
</p>
<Button
type="button"
size="sm"
className="h-7 px-2.5 text-xs"
disabled={promoteMutation.isPending}
onClick={() => promoteMutation.mutate()}
>
Promote to Qualified
<ChevronRight className="size-3.5" aria-hidden />
</Button>
</div>
) : null}
</section>
);
}