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 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | 1x 55x 54x 6x 6x 4x 4x 2x 2x 2x 53x 51x 50x 49x 49x 1x 1x 1x 345x 1x 1x 1x 424x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 204x 7x 7x 7x 7x 1x 1x 4x 4x 1x 1x 3x 3x 3x 3x 1x 1x 2x 3x 55x 55x 345x 245x 55x 55x 55x 55x 55x 55x 12x 345x 345x 345x 216x 7x 4x 1x 3x | import { useQueryClient } from "@tanstack/react-query";
import {
Ban,
Clock,
ListChecks,
Pencil,
Reply,
Send,
Sparkles,
Target,
UserPlus,
} from "lucide-react";
import { type ReactNode, useState } from "react";
import { Button } from "../../../components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../../../components/ui/card";
import { DrawerDialog } from "../../../components/ui/drawer-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 {
useRrmCampaignConfig,
useRrmFunnel,
useRrmRamp,
} from "../../../hooks/queries/useRrmQueries";
import {
adminRrmApi,
type RrmFunnel,
type RrmStage,
} from "../../../lib/api/admin/rrm";
import { queryKeys } from "../../../lib/query-keys";
import { cn } from "../../../lib/utils";
/**
* RRM command screen (F-21). It answers exactly two questions on open:
* are we going to clear the gate, and is anything on fire?
*
* Only ONE number on this page carries semantic colour — intent-stated
* against the gate target. Everything else stays monochrome until it needs
* attention, so a coloured pixel anywhere here means something.
*/
/** Unanswered inbound past this many minutes is a fire, not a backlog. */
const REPLY_SLA_MINUTES = 120;
// ─── Wait age ────────────────────────────────────────────────────────────────
/**
* Renders a wait in words so the SLA breach survives greyscale, a colourblind
* reader and a printout — colour alone is never the only carrier of the signal.
*/
export function formatWaitAge(minutes: number): string {
if (minutes < 1) return "under a minute";
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) {
const rest = minutes % 60;
return rest === 0 ? `${hours}h` : `${hours}h ${rest}m`;
}
const days = Math.floor(hours / 24);
const restHours = hours % 24;
return restHours === 0 ? `${days}d` : `${days}d ${restHours}h`;
}
/**
* The unanswered tile's second line. Every branch says something true about
* the current state — "oldest wait unknown" during a load would be a lie.
*/
function unansweredSubtext(funnel: RrmFunnel | undefined): string {
if (!funnel) return "Waiting for metrics";
if (funnel.unansweredCount === 0) return "Inbox clear";
if (funnel.oldestWaitingMinutes === null) return "Oldest wait unknown";
const age = `Oldest waiting ${formatWaitAge(funnel.oldestWaitingMinutes)}`;
return funnel.oldestWaitingMinutes > REPLY_SLA_MINUTES
? `${age} — past the 2h reply SLA`
: age;
}
// ─── Stage vocabulary ────────────────────────────────────────────────────────
/**
* Explicit because `StatusBadge.getVariantForStatus` does not know RRM stages —
* it would read "contacted" as a warning, which is the opposite of true here.
*/
const STAGE_VARIANT: Record<
RrmStage,
"default" | "info" | "warning" | "success" | "error"
> = {
sourced: "default",
not_now: "default",
unreachable: "default",
queued: "info",
contacted: "info",
delivered: "info",
read: "info",
replied: "warning",
interested: "success",
intent_stated: "success",
joined: "success",
do_not_contact: "error",
};
const STAGE_LABEL: Record<RrmStage, string> = {
sourced: "Sourced",
queued: "Queued",
contacted: "Contacted",
delivered: "Delivered",
read: "Read",
replied: "Replied",
interested: "Interested",
intent_stated: "Intent stated",
joined: "Joined",
not_now: "Not now",
unreachable: "Unreachable",
do_not_contact: "Do not contact",
};
/** The two stages that precede any send. Everything after them was contacted. */
const PRE_SEND_STAGES: readonly RrmStage[] = ["sourced", "queued"];
function StageBadge({ stage }: { stage: RrmStage }) {
return (
<StatusBadge
status={STAGE_LABEL[stage]}
variant={STAGE_VARIANT[stage]}
// The program's single success criterion. In a table of hundreds it
// has to be findable without reading, so it gets weight and a ring on
// top of the success tone every other good stage already carries.
className={
stage === "intent_stated"
? "font-semibold ring-1 ring-success"
: undefined
}
/>
);
}
// ─── Tiles ───────────────────────────────────────────────────────────────────
type Tone = "neutral" | "success" | "error";
const TONE_CARD: Record<Tone, string> = {
neutral: "",
success: "border-success ring-1 ring-success/30",
error: "border-error ring-1 ring-error/30",
};
const TONE_VALUE: Record<Tone, string> = {
neutral: "text-foreground-default",
success: "text-success",
error: "text-error",
};
const TONE_ICON: Record<Tone, string> = {
neutral: "text-foreground-subtle",
success: "text-success",
error: "text-error",
};
function Tile({
label,
icon: Icon,
tone = "neutral",
value,
subtext,
caption,
testId,
isLoading,
}: {
label: string;
icon: typeof Target;
tone?: Tone;
value: ReactNode;
subtext: string;
caption?: string;
testId: string;
isLoading: boolean;
}) {
return (
<Card className={cn("h-full", TONE_CARD[tone])} data-testid={testId}>
<CardHeader className="flex flex-row items-center justify-between p-4 pb-1 sm:p-5 sm:pb-2">
<CardTitle className="text-xs sm:text-sm font-medium text-foreground-muted">
{label}
</CardTitle>
<Icon className={cn("h-4 w-4 sm:h-5 sm:w-5", TONE_ICON[tone])} />
</CardHeader>
<CardContent className="p-4 pt-0 sm:p-5 sm:pt-0">
{isLoading ? (
<Skeleton className="h-8 w-24" />
) : (
<div
className={cn("font-heading text-2xl font-bold", TONE_VALUE[tone])}
>
{value}
</div>
)}
<p className="mt-1 text-xs text-foreground-muted">{subtext}</p>
{caption && (
<p className="mt-2 text-xs text-foreground-subtle">{caption}</p>
)}
</CardContent>
</Card>
);
}
// ─── Campaign copy ───────────────────────────────────────────────────────────
/**
* The only values expected to change mid-test. They live in `rrm_config` so an
* amount or a destination number is an edit here, not a PR and a deploy.
*/
const CONFIG_FIELDS: ReadonlyArray<{
key: string;
label: string;
hint: string;
}> = [
{
key: "validatedAmount",
label: "Validated contact rate",
hint: "Paid once a submitted contact is validated",
},
{
key: "convertedAmount",
label: "Converted contact rate",
hint: "Paid when the contact goes ahead with a matched professional",
},
{
key: "whatsappNumber",
label: "WhatsApp number",
hint: "Destination on the partner page — never the OTP number",
},
{
key: "faqCount",
label: "FAQ entries",
hint: "Questions answered on /partners",
},
];
// ─── Page ────────────────────────────────────────────────────────────────────
export function AdminRrmDashboardPage() {
const queryClient = useQueryClient();
const {
data: funnelResponse,
isLoading: funnelLoading,
error: funnelError,
} = useRrmFunnel();
// Not in the funnel contract: the WABA tier the rolling window is measured
// against only exists on the ramp. Without it the 24h tile is a bare number
// with no ceiling, which cannot tell you whether you are near the limit.
const { data: rampResponse } = useRrmRamp();
const {
data: configResponse,
isLoading: configLoading,
error: configError,
} = useRrmCampaignConfig();
// `request` throws on a failed call, so a resolved envelope always carries
// its payload — an absent one here means loading, not a silent failure.
const funnel = funnelResponse?.data;
const ramp = rampResponse?.data;
const config = configResponse?.data;
const [editingKey, setEditingKey] = useState<string | null>(null);
const [draftValue, setDraftValue] = useState("");
const [draftReason, setDraftReason] = useState("");
const [saveError, setSaveError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const editingField = CONFIG_FIELDS.find((f) => f.key === editingKey) ?? null;
function openEditor(key: string) {
setEditingKey(key);
setDraftValue(config?.[key] ?? "");
setDraftReason("");
setSaveError(null);
}
function closeEditor() {
setEditingKey(null);
setSaveError(null);
}
async function saveEdit(key: string) {
const reason = draftReason.trim();
if (!reason) {
setSaveError("A reason is required — config changes are audited.");
return;
}
setSaving(true);
setSaveError(null);
try {
await adminRrmApi.setCampaignConfig(key, draftValue.trim(), reason);
queryClient.invalidateQueries({ queryKey: queryKeys.admin.rrm.config() });
setEditingKey(null);
} catch (err) {
setSaveError(
err instanceof Error
? err.message
: "Could not save the change. Please try again.",
);
} finally {
setSaving(false);
}
}
const stages = funnel?.stages ?? [];
// Share is of everyone a send was attempted on. `sourced` and `queued` are
// the only pre-send stages, so the rest of the board — terminal stages
// included — is the denominator. It can never exceed 100% this way.
const contactedTotal = stages
.filter((s) => !PRE_SEND_STAGES.includes(s.stage))
.reduce((sum, s) => sum + s.count, 0);
const gateMet = funnel ? funnel.intentStated >= funnel.gateTarget : false;
const oldestWait = funnel?.oldestWaitingMinutes ?? null;
const slaBreached = oldestWait !== null && oldestWait > REPLY_SLA_MINUTES;
const tier = ramp?.rollingWindow.tier ?? null;
const sentRolling24h = (funnel?.sentRolling24h ?? 0).toLocaleString();
return (
<div className="space-y-6" data-testid="rrm-dashboard">
<PageHeader
title="Partner recruitment"
description="Hyderabad channel-partner campaign — gate progress and anything on fire."
/>
{funnelError ? (
<div
data-testid="funnel-error"
className="rounded-lg border border-notification-error-border bg-notification-error-bg p-6 text-sm text-notification-error-text"
>
Could not load campaign metrics. The numbers below would be stale, so
none are shown. Please refresh the page.
</div>
) : (
<>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Tile
testId="gate-tile"
label="Intent stated"
icon={Target}
tone={gateMet ? "success" : "neutral"}
isLoading={funnelLoading}
value={`${funnel?.intentStated ?? 0} / ${funnel?.gateTarget ?? 0}`}
subtext={`Day ${funnel?.daysElapsed ?? 0} of ${funnel?.gateWindowDays ?? 0}`}
caption={
gateMet
? "Gate cleared. This is the whole success criterion."
: "The program's only success criterion."
}
/>
<Tile
testId="rolling-tile"
label="Sent, rolling 24h"
icon={Send}
isLoading={funnelLoading}
value={
tier === null
? sentRolling24h
: `${sentRolling24h} / ${tier.toLocaleString()}`
}
subtext={
tier === null
? "Unique recipients — WABA tier unavailable"
: "Unique recipients against the WABA tier"
}
caption="Meta counts unique recipients in a rolling window, not messages per calendar day."
/>
<Tile
testId="unanswered-tile"
label="Unanswered"
icon={Clock}
tone={slaBreached ? "error" : "neutral"}
isLoading={funnelLoading}
value={(funnel?.unansweredCount ?? 0).toLocaleString()}
subtext={unansweredSubtext(funnel)}
caption="Backlog older than 24h auto-pauses the campaign."
/>
<Tile
testId="optout-tile"
label="Opt-outs vs blocks"
icon={Ban}
isLoading={funnelLoading}
value={
<div className="flex items-baseline gap-6">
<div>
<span data-testid="optout-count">
{(funnel?.optOuts ?? 0).toLocaleString()}
</span>
<span className="block font-sans text-xs font-normal text-foreground-muted">
Opt-outs
</span>
</div>
<div>
<span data-testid="block-count">
{(funnel?.blocks ?? 0).toLocaleString()}
</span>
<span className="block font-sans text-xs font-normal text-foreground-muted">
Blocks
</span>
</div>
</div>
}
subtext="Opt-outs above blocks is the negative path working."
caption="An opt-out is free and logged; a block is invisible and costs sender quality."
/>
</div>
{/*
* The week-1 number the owner actually watches (3.5): everything
* above mixes in 455 scraped rows, so the organic slice — people
* who found go.interioring.com/partners themselves — needs its own
* strip rather than being buried inside the combined funnel.
*/}
<div className="space-y-3" data-testid="organic-strip">
<h2 className="font-heading text-lg font-semibold text-foreground-default">
Organic sign-ups
</h2>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Tile
testId="organic-signups-tile"
label="Signed up"
icon={UserPlus}
isLoading={funnelLoading}
value={(funnel?.organic?.signups ?? 0).toLocaleString()}
subtext="Through the partner page"
/>
<Tile
testId="organic-replied-tile"
label="Replied"
icon={Reply}
isLoading={funnelLoading}
value={(funnel?.organic?.replied ?? 0).toLocaleString()}
subtext={`${(funnel?.organic?.unrepliedCount ?? 0).toLocaleString()} still waiting`}
/>
<Tile
testId="organic-intent-tile"
label="Intent"
icon={Target}
isLoading={funnelLoading}
value={(funnel?.organic?.intentStated ?? 0).toLocaleString()}
subtext="Referral intent confirmed"
/>
<Tile
testId="organic-joined-tile"
label="Joined"
icon={Sparkles}
isLoading={funnelLoading}
value={(funnel?.organic?.joined ?? 0).toLocaleString()}
subtext="Became an active partner"
/>
</div>
</div>
<Card>
<CardHeader>
<CardTitle className="font-heading text-lg">Funnel</CardTitle>
</CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm" data-testid="funnel-table">
<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">
Stage
</th>
<th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-foreground-muted">
Prospects
</th>
<th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-foreground-muted">
Share of contacted
</th>
</tr>
</thead>
<tbody className="divide-y divide-border-default">
{funnelLoading ? (
["a", "b", "c", "d", "e", "f"].map((key) => (
<tr key={`funnel-skeleton-${key}`}>
<td colSpan={3} className="px-4 py-3">
<Skeleton className="h-5 w-full" />
</td>
</tr>
))
) : stages.length === 0 ? (
<tr>
<td colSpan={3} className="px-4 py-8">
<EmptyState
icon={ListChecks}
title="No prospects yet"
description="Import a sourcing batch to start the funnel."
/>
</td>
</tr>
) : (
stages.map((row) => {
const preSend = PRE_SEND_STAGES.includes(row.stage);
const share =
preSend || contactedTotal === 0
? "—"
: `${Math.round((row.count / contactedTotal) * 100)}%`;
return (
<tr
key={row.stage}
data-testid={`funnel-row-${row.stage}`}
>
<td className="px-4 py-3">
<StageBadge stage={row.stage} />
</td>
<td className="px-4 py-3 text-right tabular-nums text-foreground-default">
{row.count.toLocaleString()}
</td>
<td className="px-4 py-3 text-right tabular-nums text-foreground-muted">
{share}
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
{!funnelLoading && stages.length > 0 && (
<p className="border-t border-border-default px-4 py-3 text-xs text-foreground-subtle">
Share is of the {contactedTotal.toLocaleString()} prospects a
send was attempted on. Sourced and queued are pre-send, so
they have no share.
</p>
)}
</CardContent>
</Card>
</>
)}
<Card data-testid="campaign-copy-card">
<CardHeader>
<CardTitle className="font-heading text-lg">Campaign copy</CardTitle>
<p className="text-sm text-foreground-muted">
Editable without a deploy. Every change is recorded with its reason.
</p>
</CardHeader>
<CardContent className="p-0">
{configError ? (
<p
data-testid="config-error"
className="px-6 pb-6 text-sm text-error"
>
Could not load campaign copy. Please refresh the page.
</p>
) : (
<ul className="divide-y divide-border-default border-t border-border-default">
{CONFIG_FIELDS.map((field) => (
<li
key={field.key}
data-testid={`config-row-${field.key}`}
className="flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-6"
>
<div className="min-w-0">
<p className="text-sm font-medium text-foreground-default">
{field.label}
</p>
<p className="text-xs text-foreground-subtle">
{field.hint}
</p>
</div>
<div className="flex items-center gap-3">
{configLoading ? (
<Skeleton className="h-5 w-20" />
) : config?.[field.key] ? (
<span className="text-sm font-semibold text-foreground-default">
{config[field.key]}
</span>
) : (
<span className="text-sm text-foreground-subtle">
Not set
</span>
)}
<Button
variant="outline"
size="sm"
data-testid={`config-edit-${field.key}`}
onClick={() => openEditor(field.key)}
>
<Pencil className="h-4 w-4" />
Edit
</Button>
</div>
</li>
))}
</ul>
)}
</CardContent>
</Card>
{editingField && (
<DrawerDialog
open
onClose={closeEditor}
title={`Edit ${editingField.label}`}
footer={
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={closeEditor}
data-testid="config-cancel"
>
Cancel
</Button>
<Button
onClick={() => saveEdit(editingField.key)}
isLoading={saving}
data-testid="config-save"
>
Save
</Button>
</div>
}
>
<div className="space-y-4">
<div>
<label
htmlFor="rrm-config-value"
className="mb-1 block text-sm font-medium text-foreground-default"
>
Value
</label>
<Input
id="rrm-config-value"
value={draftValue}
onChange={(e) => setDraftValue(e.target.value)}
/>
<p className="mt-1 text-xs text-foreground-subtle">
{editingField.hint}
</p>
</div>
<div>
<label
htmlFor="rrm-config-reason"
className="mb-1 block text-sm font-medium text-foreground-default"
>
Reason for change
</label>
<Input
id="rrm-config-reason"
value={draftReason}
onChange={(e) => setDraftReason(e.target.value)}
placeholder="Why is this changing?"
/>
</div>
{saveError && (
<p
role="alert"
data-testid="config-save-error"
className="text-sm text-error"
>
{saveError}
</p>
)}
</div>
</DrawerDialog>
)}
</div>
);
}
|