All files / src/pages/admin/rrm partners.tsx

90.17% Statements 156/173
92.64% Branches 126/136
82.75% Functions 48/58
93.29% Lines 153/164

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 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970                                                                                          1x     1x             162x         81x 72x   9x                               220x 220x 18x 18x             1x     1x     1x   1x 1x     1x     6x                                                         81x 81x   81x                                                                                                                                     90x                         2x                     4x                     5x                   2x                             1x                                         3x                                       110x 46x     46x 46x       110x     110x   110x 110x 110x     110x 110x 110x 110x 110x 110x 110x 110x 110x   110x 110x 110x 110x 110x 110x   110x             110x   110x             110x 110x 110x     110x       110x   110x           7x 7x       1x 1x 1x         4x 4x 4x 4x       5x 5x 5x     5x 5x       2x 2x 2x 2x 2x 1x     1x       1x         2x 2x 2x 2x 1x   1x   2x         1x 1x 1x 1x 1x           1x         2x 2x 2x 2x 1x           1x   2x           2x 2x 2x 2x         110x     2x 2x 2x 2x 1x     1x 1x   1x       110x 110x 110x     3x   3x 3x 3x       2x 2x   1x       110x   110x                 110x                                                         1x                   5x 5x                                                                                                                                                           93x           2x 2x 2x         1x 1x 1x     3x 3x 3x                                                                       2x                                                                 2x                                                   4x                                                     2x                           1x                         1x   2x                                             3x                                                     4x                               1x                                                                         2x                                                             3x                                                  
import { defaultParseSearch } from "@tanstack/react-router";
import { Users } 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 { 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 { StatusBadge } from "../../../components/ui/status-badge";
import { useDebouncedValue } from "../../../hooks";
import {
	useAdminPartners,
	useErasePartner,
	useMutePartner,
	useSetPartnerCaps,
	useSetPartnerPan,
	useSuspendPartner,
	useUnsuspendPartner,
} from "../../../hooks/queries/useRrmQueries";
import type { AdminPartnerRow } from "../../../lib/api/admin/rrm";
import { getErrorMessage } from "../../../lib/api/base";
import { formatPaise } from "../../../lib/currency-utils";
import { cn } from "../../../lib/utils";
 
/**
 * The partner program roster — FR-A-3, `/admin/rrm/partners`.
 *
 * Who is in the program, what they have produced, and the two levers an
 * operator has over them: suspension and caps. Both are written to a person —
 * a suspension reason reaches their login screen (FR-F-7) and a cap decides
 * how much they are allowed to earn — so neither is a quiet toggle here.
 *
 * Plus one fallback: recording a PAN that arrived on WhatsApp (FR-M-7). The
 * partner entering it themselves in the app is the primary path; this is for
 * the one who sent it to a person instead.
 */
 
const PAGE_SIZE = 20;
 
/** Wire values are snake_case; operators read English. */
const SOURCE_LABELS: Record<string, string> = {
	self_registered: "Signed up themselves",
	rrm_recruited: "Recruited by us",
	operator_added: "Added by an operator",
};
 
function sourceLabel(source: string): string {
	return SOURCE_LABELS[source] ?? source.replace(/_/g, " ");
}
 
/** Both caps null is the common case, and it deserves one line, not two. */
function capsLabel(partner: AdminPartnerRow): string[] {
	if (partner.capPerDay === null && partner.capPerMonth === null) {
		return ["Program default"];
	}
	return [
		partner.capPerDay === null
			? "Day: program default"
			: `Day: ${partner.capPerDay}`,
		partner.capPerMonth === null
			? "Month: program default"
			: `Month: ${partner.capPerMonth}`,
	];
}
 
/**
 * "" clears the override and returns them to the program default, so it maps
 * to `null` and never to `undefined` — undefined would leave the cap where it
 * was and the operator would think they had cleared it.
 */
function parseCap(raw: string): number | null | "invalid" {
	const trimmed = raw.trim();
	if (trimmed === "") return null;
	const value = Number(trimmed);
	return Number.isInteger(value) && value >= 0 ? value : "invalid";
}
 
/** A full PAN: five letters, four digits, one letter. */
// MUST match PAN_PATTERN in apps/api/src/routes/partner/me.routes.ts exactly.
// When the two disagree the screen accepts something the API rejects, and the
// operator sees a validation error for a field the dialog said was fine.
const PAN_PATTERN = /^[A-Z]{5}[0-9]{4}[A-Z]$/;
 
const SELECT_CLASS =
	"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";
 
const HEADER_CELL =
	"px-4 py-3 text-left text-xs font-medium text-foreground-muted uppercase tracking-wider";
 
const COLUMN_COUNT = 7;
const SKELETON_KEYS = ["a", "b", "c", "d", "e", "f"];
 
function SkeletonRows() {
	return (
		<>
			{SKELETON_KEYS.map((key) => (
				<tr key={key} data-testid="rrm-partners-skeleton-row">
					<td colSpan={COLUMN_COUNT} className="px-4 py-3">
						<div className="h-5 animate-pulse rounded bg-background-muted" />
					</td>
				</tr>
			))}
		</>
	);
}
 
function PartnerRow({
	partner,
	busy,
	onSuspend,
	onUnsuspend,
	onEditCaps,
	onRecordPan,
	onMute,
	onErase,
}: {
	partner: AdminPartnerRow;
	busy: boolean;
	onSuspend: (partner: AdminPartnerRow) => void;
	onUnsuspend: (partner: AdminPartnerRow) => void;
	onEditCaps: (partner: AdminPartnerRow) => void;
	onRecordPan: (partner: AdminPartnerRow) => void;
	onMute: (partner: AdminPartnerRow) => void;
	onErase: (partner: AdminPartnerRow) => void;
}) {
	const suspended = partner.suspendedAt !== null;
	const caps = capsLabel(partner);
 
	return (
		<tr
			data-testid="rrm-partner-row"
			data-partner-id={partner.id}
			data-suspended={suspended}
			// A suspended partner cannot log in and their money is frozen. A pill
			// alone disappears in a wide table, so the whole row is tinted and
			// struck through the left edge.
			className={cn(suspended && "border-l-4 border-error bg-error-light")}
		>
			<td className="px-4 py-3">
				<div className="flex flex-wrap items-center gap-2">
					<p className="text-sm font-medium text-foreground-default">
						{partner.name}
					</p>
					{suspended && <StatusBadge status="Suspended" variant="error" />}
				</div>
				<p className="text-xs text-foreground-muted">
					{partner.firmName ?? "No firm on file"}
				</p>
				{/* The columns hidden on narrow screens fold into this cell. */}
				<p className="text-xs text-foreground-subtle md:hidden">
					{partner.phoneNorm} · {sourceLabel(partner.source)}
				</p>
				{suspended && partner.suspendedReason && (
					<p
						className="mt-1 text-xs text-error"
						data-testid={`rrm-partner-suspended-reason-${partner.id}`}
					>
						They see: &ldquo;{partner.suspendedReason}&rdquo;
					</p>
				)}
				{/* Last four only — that is all the database holds. Shown so an
				    operator settling past ₹15,000 can see at a glance whether the
				    gate will refuse them. */}
				{partner.panLast4 && (
					<p
						className="mt-1 text-xs text-foreground-muted"
						data-testid={`rrm-partner-pan-${partner.id}`}
					>
						PAN on file (…{partner.panLast4})
					</p>
				)}
			</td>
			<td className="hidden whitespace-nowrap px-4 py-3 text-sm text-foreground-muted md:table-cell">
				{partner.phoneNorm}
			</td>
			<td className="hidden px-4 py-3 text-sm text-foreground-muted lg:table-cell">
				{sourceLabel(partner.source)}
			</td>
			<td className="px-4 py-3 text-sm text-foreground-default">
				{partner.referralCount}
				<span className="block text-xs text-foreground-muted">
					{partner.verifiedCount} verified
				</span>
			</td>
			<td
				className="whitespace-nowrap px-4 py-3 text-sm text-foreground-default"
				data-testid={`rrm-partner-paid-${partner.id}`}
			>
				₹{formatPaise(partner.cumulativePaidPaise)}
			</td>
			<td
				className="hidden px-4 py-3 text-sm text-foreground-muted md:table-cell"
				data-testid={`rrm-partner-caps-${partner.id}`}
			>
				{caps.map((line) => (
					<span key={line} className="block">
						{line}
					</span>
				))}
			</td>
			<td className="px-4 py-3">
				<div className="flex flex-wrap gap-2">
					{suspended ? (
						<Button
							type="button"
							size="sm"
							variant="outline"
							disabled={busy}
							onClick={() => onUnsuspend(partner)}
							data-testid={`rrm-partner-unsuspend-${partner.id}`}
						>
							Unsuspend
						</Button>
					) : (
						<Button
							type="button"
							size="sm"
							variant="outline"
							disabled={busy}
							onClick={() => onSuspend(partner)}
							data-testid={`rrm-partner-suspend-${partner.id}`}
						>
							Suspend
						</Button>
					)}
					<Button
						type="button"
						size="sm"
						variant="ghost"
						disabled={busy}
						onClick={() => onEditCaps(partner)}
						data-testid={`rrm-partner-caps-edit-${partner.id}`}
					>
						Caps
					</Button>
					<Button
						type="button"
						size="sm"
						variant="ghost"
						disabled={busy}
						onClick={() => onRecordPan(partner)}
						data-testid={`rrm-partner-pan-edit-${partner.id}`}
					>
						{partner.panLast4 ? "Change PAN" : "Record PAN"}
					</Button>
					{/* Only while updates are still on. A STOP that arrived on the
					    operator's own handset is invisible to the webhook, so this is
					    where it gets typed in; once off, only the partner's START
					    turns it back on. */}
					{partner.notifyWhatsapp ? (
						<Button
							type="button"
							size="sm"
							variant="ghost"
							disabled={busy}
							onClick={() => onMute(partner)}
							data-testid={`rrm-partner-mute-${partner.id}`}
						>
							Mute updates
						</Button>
					) : (
						<span
							className="self-center text-xs text-foreground-muted"
							data-testid={`rrm-partner-muted-${partner.id}`}
						>
							Updates off
						</span>
					)}
					{/* Last, and the only destructive one here. The request
					    arrives on WhatsApp, so this is where it is honoured. */}
					<Button
						type="button"
						size="sm"
						variant="ghost"
						className="text-error"
						disabled={busy}
						onClick={() => onErase(partner)}
						data-testid={`rrm-partner-erase-${partner.id}`}
					>
						Erase
					</Button>
				</div>
			</td>
		</tr>
	);
}
 
export function PartnersPage() {
	// `?search=` seeds the box, so the payouts screen can link straight to the
	// partner whose settle was just refused. Read once, on mount; the route
	// declares no search schema and the box owns the value from here on.
	//
	// Decoded with the router's own parser, not `URLSearchParams`: the router
	// writes a digit-only string QUOTED (`?search=%22919…%22`) because its
	// serialiser round-trips through JSON, and a hand-typed `?search=9198`
	// comes back as a number. Either way the box wants the bare text.
	const [search, setSearch] = useState(() => {
		const parsed: Record<string, unknown> = defaultParseSearch(
			window.location.search,
		);
		const seed = parsed.search;
		return typeof seed === "string" || typeof seed === "number"
			? String(seed)
			: "";
	});
	const [suspendedFilter, setSuspendedFilter] = useState<"" | "true" | "false">(
		"",
	);
	const [offset, setOffset] = useState(0);
 
	const [suspending, setSuspending] = useState<AdminPartnerRow | null>(null);
	const [reason, setReason] = useState("");
	const [unsuspending, setUnsuspending] = useState<AdminPartnerRow | null>(
		null,
	);
	const [capsFor, setCapsFor] = useState<AdminPartnerRow | null>(null);
	const [capPerDay, setCapPerDay] = useState("");
	const [capPerMonth, setCapPerMonth] = useState("");
	const [panFor, setPanFor] = useState<AdminPartnerRow | null>(null);
	const [pan, setPan] = useState("");
	const [muting, setMuting] = useState<AdminPartnerRow | null>(null);
	const [erasing, setErasing] = useState<AdminPartnerRow | null>(null);
	const [actionError, setActionError] = useState<string | null>(null);
	const [notice, setNotice] = useState<string | null>(null);
 
	const suspendPartner = useSuspendPartner();
	const unsuspendPartner = useUnsuspendPartner();
	const setCaps = useSetPartnerCaps();
	const recordPan = useSetPartnerPan();
	const mutePartner = useMutePartner();
	const erasePartner = useErasePartner();
	const busy =
		suspendPartner.isPending ||
		unsuspendPartner.isPending ||
		setCaps.isPending ||
		recordPan.isPending ||
		mutePartner.isPending ||
		erasePartner.isPending;
 
	const debouncedSearch = useDebouncedValue(search);
 
	const { data, isLoading, error } = useAdminPartners({
		search: debouncedSearch || undefined,
		suspended: suspendedFilter || undefined,
		limit: PAGE_SIZE,
		offset,
	});
 
	const partners = data?.data?.partners ?? [];
	const total = data?.data?.total;
	const hasFilters = Boolean(search || suspendedFilter);
 
	const countLabel =
		total === undefined
			? `${partners.length} partner${partners.length === 1 ? "" : "s"} on this page`
			: `${total.toLocaleString("en-IN")} partner${total === 1 ? "" : "s"}`;
 
	const hasPrev = offset > 0;
	const hasNext =
		total === undefined
			? partners.length === PAGE_SIZE
			: offset + PAGE_SIZE < total;
 
	/** Any change to what is being listed sends the operator back to page one. */
	function applyFilter(change: () => void) {
		change();
		setOffset(0);
	}
 
	function clearFilters() {
		applyFilter(() => {
			setSearch("");
			setSuspendedFilter("");
		});
	}
 
	function openSuspend(partner: AdminPartnerRow) {
		setSuspending(partner);
		setReason("");
		setActionError(null);
		setNotice(null);
	}
 
	function openCaps(partner: AdminPartnerRow) {
		setCapsFor(partner);
		setCapPerDay(partner.capPerDay === null ? "" : String(partner.capPerDay));
		setCapPerMonth(
			partner.capPerMonth === null ? "" : String(partner.capPerMonth),
		);
		setActionError(null);
		setNotice(null);
	}
 
	async function handleSuspend() {
		const trimmed = reason.trim();
		Iif (!suspending || trimmed === "") return;
		setActionError(null);
		try {
			await suspendPartner.mutateAsync({ id: suspending.id, reason: trimmed });
			setNotice(
				`${suspending.name} is suspended. Your reason is what they will read the next time they try to log in.`,
			);
			setSuspending(null);
		} catch (err) {
			// The dialog stays open with the reason still typed — a refusal is
			// something to read and retry, not something to start over from.
			setActionError(getErrorMessage(err));
		}
	}
 
	async function handleUnsuspend() {
		Iif (!unsuspending) return;
		setActionError(null);
		try {
			await unsuspendPartner.mutateAsync(unsuspending.id);
			setNotice(`${unsuspending.name} can log in again.`);
		} catch (err) {
			setActionError(getErrorMessage(err));
		} finally {
			setUnsuspending(null);
		}
	}
 
	async function handleMute() {
		Iif (!muting) return;
		setActionError(null);
		try {
			await mutePartner.mutateAsync(muting.id);
			setNotice(
				`${muting.name} will get no more updates. Their login and their money are untouched — only they can turn updates back on, by replying START.`,
			);
		} catch (err) {
			setActionError(getErrorMessage(err));
		} finally {
			setMuting(null);
		}
	}
 
	async function handleErase() {
		Iif (!erasing) return;
		setActionError(null);
		try {
			await erasePartner.mutateAsync(erasing.id);
			setNotice(
				`${erasing.name} is erased. Their number is blocked, so nothing of ours reaches it again — and what they were paid is still on the ledger.`,
			);
		} catch (err) {
			// A plain admin gets a 403 here. Showing it is the point: the
			// request still has to be honoured, by someone who can.
			setActionError(getErrorMessage(err));
		} finally {
			setErasing(null);
		}
	}
 
	function openPan(partner: AdminPartnerRow) {
		// Never prefilled: the row holds four characters, not a PAN.
		setPanFor(partner);
		setPan("");
		setActionError(null);
		setNotice(null);
	}
 
	// Uppercased and trimmed as typed, so what the operator sees is what is
	// validated — and what the API would have uppercased anyway.
	const panInvalid = pan !== "" && !PAN_PATTERN.test(pan);
 
	async function handleSavePan() {
		Iif (!panFor || !PAN_PATTERN.test(pan)) return;
		setActionError(null);
		try {
			await recordPan.mutateAsync({ id: panFor.id, pan });
			setNotice(
				`PAN recorded for ${panFor.name}. Only the last four are kept here — the full number stays in the finance register.`,
			);
			setPanFor(null);
			setPan("");
		} catch (err) {
			setActionError(getErrorMessage(err));
		}
	}
 
	const parsedDay = parseCap(capPerDay);
	const parsedMonth = parseCap(capPerMonth);
	const capsInvalid = parsedDay === "invalid" || parsedMonth === "invalid";
 
	async function handleSaveCaps() {
		Iif (!capsFor || parsedDay === "invalid" || parsedMonth === "invalid")
			return;
		setActionError(null);
		try {
			await setCaps.mutateAsync({
				id: capsFor.id,
				caps: { capPerDay: parsedDay, capPerMonth: parsedMonth },
			});
			setNotice(`Caps updated for ${capsFor.name}.`);
			setCapsFor(null);
		} catch (err) {
			setActionError(getErrorMessage(err));
		}
	}
 
	const dialogOpen = suspending !== null || capsFor !== null || panFor !== null;
 
	const errorBanner = 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-partners-action-error"
		>
			{actionError}
		</p>
	);
 
	return (
		<div className="space-y-6" data-testid="rrm-partners-page">
			<PageHeader
				title="Partners"
				description="Everyone in the referral program, what they have brought in, and the two levers you have over them."
			/>
 
			{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-partners-notice"
				>
					{notice}
				</p>
			)}
			{/* Rendered here only when no dialog covers the page — inside a dialog
			    the same message is shown in its body instead. */}
			{!dialogOpen && errorBanner}
 
			<Card>
				<CardContent className="pt-6">
					<div className="flex flex-col flex-wrap gap-3 sm:flex-row">
						<div className="sm:w-64">
							<Input
								type="search"
								aria-label="Search partners"
								placeholder="Name, firm or phone"
								data-testid="rrm-partners-search"
								value={search}
								onChange={(e) => applyFilter(() => setSearch(e.target.value))}
							/>
						</div>
 
						<select
							aria-label="Filter by suspension"
							data-testid="rrm-partners-suspended-filter"
							className={SELECT_CLASS}
							value={suspendedFilter}
							onChange={(e) =>
								applyFilter(() =>
									setSuspendedFilter(e.target.value as "" | "true" | "false"),
								)
							}
						>
							<option value="">Everyone</option>
							<option value="false">Active only</option>
							<option value="true">Suspended only</option>
						</select>
 
						{hasFilters && (
							<Button
								variant="outline"
								data-testid="rrm-partners-clear-filters"
								onClick={clearFilters}
							>
								Clear
							</Button>
						)}
					</div>
				</CardContent>
			</Card>
 
			<Card>
				<CardHeader>
					<CardTitle className="text-lg" data-testid="rrm-partners-total">
						{isLoading ? "Loading partners…" : countLabel}
					</CardTitle>
				</CardHeader>
				<CardContent className="p-0">
					{error ? (
						<div
							data-testid="rrm-partners-error"
							className="p-6 text-sm text-error"
						>
							Could not load partners. Refresh the page to try again.
						</div>
					) : (
						<div className="overflow-x-auto">
							<table
								className="w-full text-sm"
								data-testid="rrm-partners-table"
							>
								<thead className="border-b border-border-default bg-background-subtle">
									<tr>
										<th className={HEADER_CELL}>Partner</th>
										<th className={cn(HEADER_CELL, "hidden md:table-cell")}>
											Phone
										</th>
										<th className={cn(HEADER_CELL, "hidden lg:table-cell")}>
											How they joined
										</th>
										<th className={HEADER_CELL}>Referrals</th>
										<th className={HEADER_CELL}>Paid so far</th>
										<th className={cn(HEADER_CELL, "hidden md:table-cell")}>
											Caps
										</th>
										<th className={cn(HEADER_CELL, "w-40")}>Actions</th>
									</tr>
								</thead>
								<tbody className="divide-y divide-border-default">
									{isLoading ? (
										<SkeletonRows />
									) : partners.length === 0 ? (
										<tr>
											<td colSpan={COLUMN_COUNT} className="px-4 py-12">
												<EmptyState
													icon={Users}
													title="No partners found"
													description={
														hasFilters
															? "No partner matches these filters. Clear them to see the whole program."
															: "Nobody has joined the referral program yet."
													}
												/>
											</td>
										</tr>
									) : (
										partners.map((partner) => (
											<PartnerRow
												key={partner.id}
												partner={partner}
												busy={busy}
												onSuspend={openSuspend}
												onUnsuspend={(chosen) => {
													setUnsuspending(chosen);
													setActionError(null);
													setNotice(null);
												}}
												onEditCaps={openCaps}
												onRecordPan={openPan}
												onMute={(chosen) => {
													setMuting(chosen);
													setActionError(null);
													setNotice(null);
												}}
												onErase={(chosen) => {
													setErasing(chosen);
													setActionError(null);
													setNotice(null);
												}}
											/>
										))
									)}
								</tbody>
							</table>
						</div>
					)}
 
					{!isLoading && !error && (hasPrev || hasNext) && (
						<div
							className="flex flex-col gap-3 border-t border-border-default px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
							data-testid="rrm-partners-pagination"
						>
							<p className="text-sm text-foreground-muted">
								{total === undefined
									? `Partners ${offset + 1}–${offset + partners.length}`
									: `Partners ${offset + 1}–${offset + partners.length} of ${total.toLocaleString("en-IN")}`}
							</p>
							<div className="flex gap-2">
								<Button
									variant="outline"
									size="sm"
									data-testid="rrm-partners-prev"
									onClick={() =>
										setOffset((current) => Math.max(0, current - PAGE_SIZE))
									}
									disabled={!hasPrev}
								>
									Previous
								</Button>
								<Button
									variant="outline"
									size="sm"
									data-testid="rrm-partners-next"
									onClick={() => setOffset((current) => current + PAGE_SIZE)}
									disabled={!hasNext}
								>
									Next
								</Button>
							</div>
						</div>
					)}
				</CardContent>
			</Card>
 
			{/* ── Suspend ──────────────────────────────────────────────────────── */}
			<DrawerDialog
				open={suspending !== null}
				onClose={() => setSuspending(null)}
				title={
					suspending ? `Suspend ${suspending.name}` : "Suspend this partner"
				}
				footer={
					<div className="flex justify-end gap-2">
						<Button
							type="button"
							variant="outline"
							onClick={() => setSuspending(null)}
						>
							Cancel
						</Button>
						<Button
							type="button"
							variant="destructive"
							disabled={reason.trim() === "" || busy}
							isLoading={suspendPartner.isPending}
							onClick={() => {
								void handleSuspend();
							}}
							data-testid="rrm-partner-suspend-confirm"
						>
							Suspend partner
						</Button>
					</div>
				}
			>
				<div className="space-y-4">
					<p className="text-sm text-foreground-default">
						They will not be able to log in and their earnings stay frozen until
						you lift this.
					</p>
					<div>
						<label
							className="mb-1 block text-sm font-medium text-foreground-default"
							htmlFor="rrm-partner-suspend-reason"
						>
							Why are you suspending them?
						</label>
						<textarea
							id="rrm-partner-suspend-reason"
							data-testid="rrm-partner-suspend-reason"
							rows={3}
							value={reason}
							onChange={(e) => setReason(e.target.value)}
							placeholder="Duplicate referrals submitted from three different numbers"
							className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm text-foreground-default placeholder:text-foreground-subtle focus:border-transparent focus:outline-none focus:ring-2 focus:ring-primary-500"
						/>
						{/* FR-F-7 forbids a silent suspension. An operator typing "test"
						    here would be typing it TO someone, so say so before they do. */}
						<p className="mt-2 text-sm text-warning">
							This is shown to them, word for word, on their login screen. Write
							it to them, not about them.
						</p>
					</div>
					{errorBanner}
				</div>
			</DrawerDialog>
 
			{/* ── Unsuspend ────────────────────────────────────────────────────── */}
			<ConfirmDialog
				open={unsuspending !== null}
				title={
					unsuspending
						? `Let ${unsuspending.name} back in?`
						: "Lift this suspension?"
				}
				description="They can log in again straight away and their earnings unfreeze. No reason is needed to lift a suspension."
				confirmLabel="Let them back in"
				onCancel={() => setUnsuspending(null)}
				onConfirm={() => {
					void handleUnsuspend();
				}}
			/>
 
			{/* ── Mute updates ─────────────────────────────────────────────────── */}
			<ConfirmDialog
				open={muting !== null}
				title={
					muting ? `Stop updates to ${muting.name}?` : "Stop their updates?"
				}
				description="For a STOP that came to your own phone, where the system never saw it. They keep their login, their referrals and their money — this only stops the WhatsApp updates. You cannot switch them back on: only they can, by replying START."
				confirmLabel="Stop their updates"
				onCancel={() => setMuting(null)}
				onConfirm={() => {
					void handleMute();
				}}
			/>
 
			{/* ── Erase (DPDP) ─────────────────────────────────────────────────── */}
			<ConfirmDialog
				open={erasing !== null}
				variant="destructive"
				title={
					erasing ? `Erase ${erasing.name}?` : "Erase this partner's details?"
				}
				description="Removed: their name, firm, phone number, UPI details — on their account and on payments already made — and PAN, plus their name and number wherever another partner referred them. Kept: the money. What they earned, what was paid and the reference proving it stay, because a payment we made is not ours to erase. Their number goes on the block list so nothing of ours reaches it again. If they have a withdrawal pending, settle or fail it first: afterwards there is no UPI id left to pay them with. This cannot be undone."
				confirmLabel="Erase their details"
				onCancel={() => setErasing(null)}
				onConfirm={() => {
					void handleErase();
				}}
			/>
 
			{/* ── Caps ─────────────────────────────────────────────────────────── */}
			<DrawerDialog
				open={capsFor !== null}
				onClose={() => setCapsFor(null)}
				title={capsFor ? `Caps for ${capsFor.name}` : "Referral caps"}
				footer={
					<div className="flex justify-end gap-2">
						<Button
							type="button"
							variant="outline"
							onClick={() => setCapsFor(null)}
						>
							Cancel
						</Button>
						<Button
							type="button"
							disabled={capsInvalid || busy}
							isLoading={setCaps.isPending}
							onClick={() => {
								void handleSaveCaps();
							}}
							data-testid="rrm-partner-caps-save"
						>
							Save caps
						</Button>
					</div>
				}
			>
				<div className="space-y-4">
					<p className="text-sm text-foreground-default">
						How many referrals this partner may submit. Leave a box empty to put
						them back on the program default.
					</p>
					<div className="grid gap-4 sm:grid-cols-2">
						<div>
							<label
								className="mb-1 block text-sm font-medium text-foreground-default"
								htmlFor="rrm-partner-cap-day"
							>
								Per day
							</label>
							<Input
								id="rrm-partner-cap-day"
								data-testid="rrm-partner-cap-day"
								inputMode="numeric"
								value={capPerDay}
								onChange={(e) => setCapPerDay(e.target.value)}
								placeholder="Program default"
							/>
						</div>
						<div>
							<label
								className="mb-1 block text-sm font-medium text-foreground-default"
								htmlFor="rrm-partner-cap-month"
							>
								Per month
							</label>
							<Input
								id="rrm-partner-cap-month"
								data-testid="rrm-partner-cap-month"
								inputMode="numeric"
								value={capPerMonth}
								onChange={(e) => setCapPerMonth(e.target.value)}
								placeholder="Program default"
							/>
						</div>
					</div>
					{capsInvalid && (
						<p
							className="text-sm text-error"
							data-testid="rrm-partner-caps-invalid"
						>
							A cap has to be a whole number of referrals, or empty for the
							program default.
						</p>
					)}
					{errorBanner}
				</div>
			</DrawerDialog>
 
			{/* ── PAN ──────────────────────────────────────────────────────────── */}
			<DrawerDialog
				open={panFor !== null}
				onClose={() => setPanFor(null)}
				title={panFor ? `PAN for ${panFor.name}` : "Record a PAN"}
				footer={
					<div className="flex justify-end gap-2">
						<Button
							type="button"
							variant="outline"
							onClick={() => setPanFor(null)}
						>
							Cancel
						</Button>
						<Button
							type="button"
							disabled={!PAN_PATTERN.test(pan) || busy}
							isLoading={recordPan.isPending}
							onClick={() => {
								void handleSavePan();
							}}
							data-testid="rrm-partner-pan-save"
						>
							Save PAN
						</Button>
					</div>
				}
			>
				<div className="space-y-4">
					<p className="text-sm text-foreground-default">
						For a PAN that arrived on the WhatsApp thread. The partner can also
						enter it themselves on their payout screen — this is the fallback,
						not the rule.
					</p>
					<div>
						<label
							className="mb-1 block text-sm font-medium text-foreground-default"
							htmlFor="rrm-partner-pan"
						>
							PAN, as printed on the card
						</label>
						<Input
							id="rrm-partner-pan"
							data-testid="rrm-partner-pan-input"
							autoComplete="off"
							autoCapitalize="characters"
							spellCheck={false}
							maxLength={10}
							className="font-mono uppercase tracking-widest"
							value={pan}
							onChange={(e) => setPan(e.target.value.toUpperCase().trim())}
							placeholder="ABCDE1234F"
						/>
						{/* The one thing worth saying before they press Save. */}
						<p className="mt-2 text-sm text-warning">
							Only the last four characters are stored. Keep the full PAN in the
							finance register — it cannot be read back from here.
						</p>
					</div>
					{panInvalid && (
						<p
							className="text-sm text-error"
							data-testid="rrm-partner-pan-invalid"
						>
							A PAN is five letters, four digits and a letter, like ABCDE1234F.
						</p>
					)}
					{errorBanner}
				</div>
			</DrawerDialog>
		</div>
	);
}
 
export default PartnersPage;