Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | 1x 1x 1x 1x 86x 49x 19x 30x 30x 4x 3x 19x 19x 3x 133x 1x 3x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 49x 56x 56x 56x 31x 56x 56x 56x 8x 8x 8x 8x 8x 6x 6x 2x 8x 8x 3x 3x 2x 2x 2x 5x 5x 4x 56x 1x 55x 1x 54x 30x 7x 19x 3x 1x 3x 1x 3x 1x 2x | import { useQueryClient } from "@tanstack/react-query";
import {
AlertTriangle,
CheckCircle2,
ListChecks,
PhoneCall,
Quote,
} from "lucide-react";
import { useState } from "react";
import { Button } from "../../../components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../../../components/ui/card";
import { ConfirmDialog } from "../../../components/ui/confirm-dialog";
import { EmptyState } from "../../../components/ui/empty-state";
import { Input } from "../../../components/ui/input";
import { PageHeader } from "../../../components/ui/page-header";
import { Skeleton } from "../../../components/ui/skeleton";
import { StatusBadge } from "../../../components/ui/status-badge";
import { Tooltip } from "../../../components/ui/tooltip";
import { useRrmTasks } from "../../../hooks/queries/useRrmQueries";
import {
adminRrmApi,
type RrmTask,
type RrmTaskType,
} from "../../../lib/api/admin/rrm";
import { getErrorMessage } from "../../../lib/api/base";
import { queryKeys } from "../../../lib/query-keys";
/**
* The operator work queue — F-21, `/admin/rrm/tasks`.
*
* Two jobs, deliberately unequal in weight. Confirming stated intent is the
* program's only success criterion (three inside 14 days), so it sits at the
* top with room to read the quote. Calls are the volume work below it.
*/
/**
* TCCCPR treats a commercial call from an unregistered sender as unsolicited
* BY DEFINITION, with action available at five complaints in ten days. Pacing
* the calls and logging every outcome is what makes a complaint answerable, so
* the number is on screen rather than in a runbook.
*
* Hard-coded because `rrm_config` has no key for it yet — see the report.
*/
const DAILY_CALL_QUOTA = 15;
/**
* The call-log vocabulary. `completeTask` takes a free string, so this list is
* the only thing keeping the log countable; an operator typing their own
* wording would make "how many no-answers today" unanswerable.
*/
const CALL_OUTCOMES: ReadonlyArray<{ code: string; label: string }> = [
{ code: "connected_interested", label: "Connected — interested" },
{ code: "connected_not_now", label: "Connected — not now" },
{ code: "connected_refused", label: "Connected — refused" },
{ code: "no_answer", label: "No answer" },
{ code: "busy_callback", label: "Busy — call back" },
{ code: "wrong_number", label: "Wrong number" },
{ code: "asked_to_stop", label: "Asked us to stop contacting" },
];
const TASK_TYPE_LABELS: Record<RrmTaskType, string> = {
call: "Call",
followup: "Follow-up",
escalation: "Escalation",
confirm_intent: "Confirm intent",
};
/**
* The quota is a calendar-day rule under Indian law, so the day is an IST day
* — never the operator's laptop timezone.
*/
const IST_DAY = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Kolkata",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
function istDay(value: string | Date): string {
return IST_DAY.format(new Date(value));
}
function formatDue(dueAt: string): string {
return new Date(dueAt).toLocaleString("en-IN", {
day: "numeric",
month: "short",
hour: "2-digit",
minute: "2-digit",
});
}
function isOverdue(dueAt: string): boolean {
return new Date(dueAt).getTime() < Date.now();
}
// ─── Confirm-intent panel ────────────────────────────────────────────────────
function IntentTaskCard({
task,
busy,
onDecide,
}: {
task: RrmTask;
busy: boolean;
onDecide: (task: RrmTask, confirmed: boolean) => void;
}) {
const hasEvidence = Boolean(task.evidence);
return (
<div
className="rounded-lg border border-border-default bg-background-elevated p-4"
data-testid={`rrm-intent-task-${task.id}`}
>
<div className="flex flex-wrap items-baseline justify-between gap-2">
<p className="font-medium text-foreground-default">
{task.prospectName ?? "Unnamed prospect"}
</p>
<p className="text-xs text-foreground-muted">
Raised for {formatDue(task.dueAt)}
</p>
</div>
{hasEvidence ? (
<blockquote className="mt-3 flex gap-2 border-l-2 border-success pl-3">
<Quote className="h-4 w-4 shrink-0 text-success" aria-hidden="true" />
<p
className="text-sm italic text-foreground-default"
data-testid={`rrm-intent-evidence-${task.id}`}
>
{task.evidence}
</p>
</blockquote>
) : (
<p
className="mt-3 text-sm text-foreground-muted"
data-testid={`rrm-intent-no-evidence-${task.id}`}
>
No quote was captured with this task. There is nothing to confirm
against, so it can only be rejected — reopen it from the prospect if
the words exist somewhere.
</p>
)}
{task.notes && (
<p className="mt-2 text-sm text-foreground-muted">{task.notes}</p>
)}
<div className="mt-4 flex flex-wrap gap-2">
<Button
type="button"
size="sm"
disabled={!hasEvidence || busy}
onClick={() => onDecide(task, true)}
data-testid={`rrm-intent-confirm-${task.id}`}
>
Confirm intent
</Button>
<Button
type="button"
size="sm"
variant="outline"
disabled={busy}
onClick={() => onDecide(task, false)}
data-testid={`rrm-intent-reject-${task.id}`}
>
Not concrete
</Button>
</div>
</div>
);
}
// ─── Call queue row ──────────────────────────────────────────────────────────
function CallTaskRow({
task,
outcome,
note,
busy,
onOutcomeChange,
onNoteChange,
onComplete,
}: {
task: RrmTask;
outcome: string;
note: string;
busy: boolean;
onOutcomeChange: (taskId: string, code: string) => void;
onNoteChange: (taskId: string, note: string) => void;
onComplete: (task: RrmTask, outcome: string) => void;
}) {
const overdue = isOverdue(task.dueAt);
return (
<tr data-testid={`rrm-task-row-${task.id}`}>
<td className="whitespace-nowrap px-4 py-3 text-sm">
<span
className={
overdue ? "font-semibold text-error" : "text-foreground-muted"
}
>
{formatDue(task.dueAt)}
</span>
{overdue && <span className="sr-only"> (overdue)</span>}
</td>
<td className="px-4 py-3">
<StatusBadge
status={TASK_TYPE_LABELS[task.type]}
variant={task.type === "escalation" ? "warning" : "info"}
/>
</td>
<td className="px-4 py-3 text-sm text-foreground-default">
{task.prospectName ?? "Unnamed prospect"}
</td>
<td className="max-w-xs px-4 py-3 text-sm text-foreground-muted">
{task.notes ?? "—"}
</td>
<td className="px-4 py-3">
<div className="flex w-56 flex-col gap-2">
<select
aria-label={`Call outcome for ${task.prospectName ?? task.id}`}
value={outcome}
onChange={(e) => onOutcomeChange(task.id, e.target.value)}
className="h-10 rounded-md border border-border-default bg-background-base px-3 py-2 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="">Select an outcome…</option>
{CALL_OUTCOMES.map((option) => (
<option key={option.code} value={option.code}>
{option.label}
</option>
))}
</select>
<Input
aria-label={`Note for ${task.prospectName ?? task.id}`}
placeholder="Optional note"
value={note}
onChange={(e) => onNoteChange(task.id, e.target.value)}
/>
</div>
</td>
<td className="px-4 py-3">
<Button
type="button"
size="sm"
variant="outline"
disabled={outcome === "" || busy}
onClick={() => onComplete(task, outcome)}
data-testid={`rrm-task-complete-${task.id}`}
>
Log call
</Button>
</td>
</tr>
);
}
// ─── Page ────────────────────────────────────────────────────────────────────
type IntentDecision = { task: RrmTask; confirmed: boolean };
export function AdminRrmTasksPage() {
const queryClient = useQueryClient();
const openQuery = useRrmTasks({ state: "open" });
// Second query on purpose: the quota counts calls already LOGGED today, and
// those have left the open queue.
const callQuery = useRrmTasks({ type: "call" });
const [outcomes, setOutcomes] = useState<Record<string, string>>({});
const [notes, setNotes] = useState<Record<string, string>>({});
const [decision, setDecision] = useState<IntentDecision | null>(null);
const [busy, setBusy] = useState(false);
const [actionError, setActionError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const openTasks = openQuery.data?.data ?? [];
const intentTasks = openTasks.filter(
(task) => task.type === "confirm_intent",
);
const queueTasks = openTasks.filter((task) => task.type !== "confirm_intent");
// Counted by due date: `RrmTask` exposes no `completedAt`, and a call is
// worked on the day it comes due. A call logged the morning after it was due
// therefore lands on yesterday's count — see the report.
const today = istDay(new Date());
const callsLoggedToday = (callQuery.data?.data ?? []).filter(
(task) => task.state === "done" && istDay(task.dueAt) === today,
).length;
// A failed call query must not read as "full quota remaining": an operator
// who trusts a wrong zero makes calls nobody can account for later.
const quotaUnknown = Boolean(callQuery.error);
const quotaLabel = `${quotaUnknown ? "—" : callsLoggedToday} / ${DAILY_CALL_QUOTA} calls today`;
const quotaVariant = quotaUnknown
? "warning"
: callsLoggedToday >= DAILY_CALL_QUOTA
? "error"
: callsLoggedToday >= DAILY_CALL_QUOTA - 3
? "warning"
: "default";
async function run(action: () => Promise<string>) {
setBusy(true);
setActionError(null);
setNotice(null);
try {
const message = await action();
setNotice(message);
queryClient.invalidateQueries({ queryKey: queryKeys.admin.rrm.all });
} catch (err) {
// A refusal from the API is information the operator needs, not a
// console entry: the task stays open and they must know why.
setActionError(getErrorMessage(err));
} finally {
setBusy(false);
setDecision(null);
}
}
/**
* The row passes the outcome it is displaying rather than the page reading
* it back out of state: the Log button is disabled while that value is
* empty, so there is exactly one place where "no outcome, no completion" is
* enforced instead of two that can drift apart.
*/
function handleComplete(task: RrmTask, outcomeCode: string) {
return run(async () => {
await adminRrmApi.completeTask(
task.id,
outcomeCode,
notes[task.id] || undefined,
);
setOutcomes((prev) => ({ ...prev, [task.id]: "" }));
setNotes((prev) => ({ ...prev, [task.id]: "" }));
return `Call logged for ${task.prospectName ?? "prospect"}.`;
});
}
function handleDecision({ task, confirmed }: IntentDecision) {
return run(async () => {
await adminRrmApi.confirmIntent(task.id, confirmed, task.evidence ?? "");
return confirmed
? `Intent confirmed for ${task.prospectName ?? "prospect"} — the prospect is now intent_stated.`
: `Marked not concrete for ${task.prospectName ?? "prospect"}. No stage change.`;
});
}
if (openQuery.isLoading) {
return (
<div className="space-y-6" data-testid="rrm-tasks-loading">
<Skeleton className="h-9 w-72" />
<Skeleton className="h-56 w-full" />
<Skeleton className="h-64 w-full" />
</div>
);
}
if (openQuery.error) {
return (
<div className="space-y-6">
<PageHeader
title="Calls and confirmations"
description="The operator work queue."
/>
<Card>
<CardContent className="pt-6">
<EmptyState
icon={AlertTriangle}
title="Could not load tasks"
description={getErrorMessage(openQuery.error)}
/>
</CardContent>
</Card>
</div>
);
}
return (
<div className="space-y-6" data-testid="rrm-tasks-page">
<PageHeader
title="Calls and confirmations"
description="Confirmations first — three of them inside 14 days is the whole program. Calls below."
icon={
<ListChecks className="h-6 w-6 text-primary-500" aria-hidden="true" />
}
actions={
<span className="flex items-center gap-2">
<span
data-testid="rrm-tasks-quota"
title={
quotaUnknown
? "The call log could not be loaded, so today's count is unknown."
: undefined
}
>
<StatusBadge status={quotaLabel} variant={quotaVariant} />
</span>
<Tooltip content="TCCCPR treats a commercial call from an unregistered sender as unsolicited by definition, with action at five complaints in ten days. Pacing the calls and logging every outcome is what makes a complaint answerable. Counted by due date — the task record carries no completion time." />
</span>
}
/>
{notice && (
<p
className="rounded-lg border border-notification-success-border bg-notification-success-bg p-3 text-sm text-notification-success-text"
data-testid="rrm-tasks-notice"
>
{notice}
</p>
)}
{actionError && (
<p
className="rounded-lg border border-notification-error-border bg-notification-error-bg p-3 text-sm text-notification-error-text"
data-testid="rrm-tasks-error"
>
{actionError}
</p>
)}
{/* Confirm intent — the gate lives or dies here, so it goes first. */}
<Card
className="border-success bg-success-light"
data-testid="rrm-tasks-intent-panel"
>
<CardHeader>
<CardTitle className="flex items-center gap-2 font-heading text-lg text-foreground-default">
<CheckCircle2 className="h-5 w-5 text-success" aria-hidden="true" />
Intent to confirm
{intentTasks.length > 0 && (
<span className="text-foreground-muted">
({intentTasks.length})
</span>
)}
</CardTitle>
<p className="text-sm text-foreground-default">
Read the quote and judge it. This is the only path to{" "}
<span className="font-semibold">intent_stated</span> — a submitted
contact note raises a task, it never sets the stage, so “maybe
later” cannot count itself towards the gate.
</p>
</CardHeader>
<CardContent>
{intentTasks.length === 0 ? (
<EmptyState
icon={CheckCircle2}
title="Nothing waiting"
description="Referral submissions and replies that name a contact raise a task here."
/>
) : (
<div className="grid gap-4 lg:grid-cols-2">
{intentTasks.map((task) => (
<IntentTaskCard
key={task.id}
task={task}
busy={busy}
onDecide={(chosen, confirmed) =>
setDecision({ task: chosen, confirmed })
}
/>
))}
</div>
)}
</CardContent>
</Card>
{/* Call queue */}
<Card data-testid="rrm-tasks-queue">
<CardHeader>
<CardTitle className="flex items-center gap-2 font-heading text-lg">
<PhoneCall
className="h-5 w-5 text-primary-500"
aria-hidden="true"
/>
Call queue
<span className="text-foreground-muted">({queueTasks.length})</span>
</CardTitle>
<p className="text-sm text-foreground-muted">
A task cannot be closed without an outcome: the log is the only
record that the call happened at all.
</p>
</CardHeader>
<CardContent className="p-0">
{queueTasks.length === 0 ? (
<div className="px-4 pb-6">
<EmptyState
icon={PhoneCall}
title="No open calls"
description="Replies and follow-ups schedule themselves into this queue."
/>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b border-border-default bg-background-subtle">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-foreground-muted">
Due
</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-foreground-muted">
Type
</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-foreground-muted">
Prospect
</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-foreground-muted">
Context
</th>
<th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-foreground-muted">
Outcome
</th>
<th className="px-4 py-3 w-24" />
</tr>
</thead>
<tbody className="divide-y divide-border-default">
{queueTasks.map((task) => (
<CallTaskRow
key={task.id}
task={task}
outcome={outcomes[task.id] ?? ""}
note={notes[task.id] ?? ""}
busy={busy}
onOutcomeChange={(taskId, code) =>
setOutcomes((prev) => ({ ...prev, [taskId]: code }))
}
onNoteChange={(taskId, value) =>
setNotes((prev) => ({ ...prev, [taskId]: value }))
}
onComplete={(chosen, outcome) => {
void handleComplete(chosen, outcome);
}}
/>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
{/* One pending decision drives two dialogs; `confirmed` picks which. */}
{decision && (
<>
<ConfirmDialog
open={decision.confirmed}
title="Confirm stated intent?"
description="This moves the prospect to intent_stated and counts towards the 14-day gate. Confirm only if the quote names a concrete contact or referral."
confirmLabel="Confirm and count it"
onCancel={() => setDecision(null)}
onConfirm={() => {
void handleDecision(decision);
}}
/>
<ConfirmDialog
open={!decision.confirmed}
variant="destructive"
title="Mark as not concrete?"
description="The task closes and the stage does not move. The prospect stays where they are and can still be worked."
confirmLabel="Mark not concrete"
onCancel={() => setDecision(null)}
onConfirm={() => {
void handleDecision(decision);
}}
/>
</>
)}
</div>
);
}
|