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 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 | 1x 1x 1x 1x 138x 1x 350x 175x 436x 436x 1x 38x 17x 21x 19x 27x 142x 141x 141x 141x 140x 279x 278x 140x 1x 10x 6x 4x 2x 2x 1x 175x 175x 828x 278x 278x 1x 144x 144x 144x 144x 144x 140x 144x 144x 144x 2x 2x 2x 2x 2x 1x 1x 1x 144x 282x 2x 138x 138x 138x 138x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 178x 146x 146x 146x 146x 146x 146x 146x 13x 13x 13x 15x 15x 15x 13x 13x 2x 7x 7x 7x 7x 6x 7x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 9x 3x 3x 3x 3x 2x 2x 1x 146x 1x 145x 1x 144x 146x 146x 146x 146x 146x 146x 146x 146x 146x 178x 2x 2x 9x 3x 1x 1x 2x 24x 2x 1x 1x 2x 1x 1x 38x 38x 38x 38x 5x 3x 80x 1x 3x 3x 7x 1x 2x 278x 2x 1x | import { useQueryClient } from "@tanstack/react-query";
import { useParams } from "@tanstack/react-router";
import {
AlertTriangle,
BadgeCheck,
Ban,
Banknote,
CheckCircle2,
Copy,
FileText,
Handshake,
History,
MessageSquare,
Send,
ShieldAlert,
Undo2,
XCircle,
} 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 { PageHeader } from "../../../components/ui/page-header";
import { Skeleton } from "../../../components/ui/skeleton";
import { StatusBadge } from "../../../components/ui/status-badge";
import { StatusIcon } from "../../../components/whatsapp/MessageThread";
import { useAdminProLookup } from "../../../hooks/queries/useAdminQueries";
import {
useAdminReferral,
useAdminReferrals,
useAdvanceReferral,
useClawbackEarning,
useMarkReferralDuplicate,
useRecordOutcome,
useRejectReferral,
useReverseEarning,
useVerifyReferral,
} from "../../../hooks/queries/useRrmQueries";
import { useReplyToConversation } from "../../../hooks/queries/useWhatsAppQueries";
import type {
AdminEarningRow,
AdminReferralDetail,
AdminReferralRow,
ReferralStatus,
RrmReversalReason,
} from "../../../lib/api/admin/rrm";
import { ApiError, getErrorMessage } from "../../../lib/api/base";
import { formatPaise } from "../../../lib/currency-utils";
import { queryKeys } from "../../../lib/query-keys";
import { cn } from "../../../lib/utils";
import { formatDateTime, formatRelative } from "./prospects";
/**
* The verification queue (FR-A-1) — `/admin/rrm/referrals`.
*
* The bar is a median of sixty seconds per referral and "ops never opens
* WhatsApp to decide". Both follow from the same thing: the WhatsApp thread is
* ON this screen, next to what the partner claimed, so the decision is a
* comparison rather than a hunt across two apps.
*
* Queue on the left, decision on the right. Acting advances to the next item
* by itself — an operator works down a list, they do not navigate.
*/
/**
* The programme default for `verify_amount_paise` (FR-M-2), used ONLY until the
* referral detail loads.
*
* The live rate arrives with the detail as `verifyAmountPaise` and is what the
* screen shows. This fallback exists so the button has a number during the
* first paint, never so that a stale rate reaches the confirmation dialog — a
* wrong figure at the moment of a money decision is found later by a partner
* disputing their balance, which is the worst way to find it.
*/
const VERIFY_CREDIT_PAISE_FALLBACK = 10_000;
/** Waiting longer than this and the row starts shouting. */
const STALE_HOURS = 24;
// ─── Status vocabulary ───────────────────────────────────────────────────────
/**
* All twelve. The queue only lists `engaged`, but the detail pane keeps
* rendering the referral it was showing while the list refetches, so it has to
* be able to name whatever the referral just became.
*/
const STATUS_LABELS: Record<ReferralStatus, string> = {
draft: "Draft",
forwarded: "Forwarded",
engaged: "Engaged",
verified: "Verified",
contacted: "Contacted",
quoted: "Quoted",
converted: "Converted",
duplicate: "Duplicate",
rejected: "Rejected",
expired: "Expired",
lost: "Lost",
opted_out: "Opted out",
};
/**
* `StatusBadge.getVariantForStatus` knows marketplace statuses, not referral
* ones — it would colour "contacted" as a warning and everything else grey —
* so the variant is always passed explicitly.
*/
const STATUS_VARIANTS: Record<
ReferralStatus,
"default" | "info" | "warning" | "success" | "error"
> = {
draft: "default",
forwarded: "info",
// The one state that means "an operator has to do something".
engaged: "warning",
verified: "success",
contacted: "info",
quoted: "info",
converted: "success",
duplicate: "default",
rejected: "error",
expired: "default",
lost: "default",
opted_out: "error",
};
function ReferralStatusBadge({ status }: { status: ReferralStatus }) {
return (
<span data-testid="referral-status-badge" data-status={status}>
<StatusBadge
status={STATUS_LABELS[status]}
variant={STATUS_VARIANTS[status]}
/>
</span>
);
}
// ─── Small helpers ───────────────────────────────────────────────────────────
const HOUR_MS = 3_600_000;
/** A referral has been waiting since it engaged, not since it was written. */
function waitingSince(referral: AdminReferralRow): string {
return referral.engagedAt ?? referral.dateCreated;
}
function isStale(referral: AdminReferralRow): boolean {
return (
Date.now() - new Date(waitingSince(referral)).getTime() >
STALE_HOURS * HOUR_MS
);
}
function humanise(value: string): string {
const words = value.replace(/_/g, " ");
return words.charAt(0).toUpperCase() + words.slice(1);
}
/**
* `RRM_EARNING_REVERSAL_REASONS`, in the order the operator manual lists them.
* The option text is `humanise`d, so the screen and `admin/payouts.md` say the
* same five words rather than two spellings of the same five decisions.
*/
const REVERSAL_REASONS: readonly RrmReversalReason[] = [
"duplicate_referral",
"unreachable_contact",
"consent_denied",
"operator_correction",
"fraud",
];
/**
* Which withdrawal, if any, this ledger row can take — the API's own rules,
* asked before the click rather than discovered through a 409.
*
* `reverse` is for money that has not moved, and the API additionally requires
* `payout_id IS NULL`: a row locked to a payout an operator already requested
* cannot be pulled out from under the total that payout was fixed at. Its 409
* for that case blames the *state*, which is not what is wrong, so the button
* is withheld and the row explains itself instead.
*
* `clawback` is for money that has. The index behind it is
* `(referral_id, kind) WHERE state != 'reversed'` and every clawback row is
* written `kind: 'clawback'` — so the limit is ONE LIVE CLAWBACK PER REFERRAL,
* not one per earning. Asking `reversedOf === earning.id` instead would offer a
* doomed button in two ordinary situations: a second paid earning on the same
* referral (`validated` and `converted` both reach `paid` on their own), and
* the clawback row itself once the next payout sweeps it to `paid` — the sweep
* filters on state, never on kind. Both 409. A reversed clawback does not hold
* the slot, which is what the index's `WHERE` says.
*/
function withdrawalFor(
earning: AdminEarningRow,
ledger: AdminEarningRow[],
): "reverse" | "clawback" | null {
if (earning.state === "accrued" || earning.state === "released") {
return earning.payoutId ? null : "reverse";
}
if (earning.state !== "paid") return null;
return ledger.some(
(row) => row.kind === "clawback" && row.state !== "reversed",
)
? null
: "clawback";
}
/**
* Event payloads arrive as a JSON string. Flattened to one line of primitives:
* a raw blob in the timeline is noise, and noise is what pushes the operator
* back into WhatsApp.
*/
export function summarisePayload(payload: string | null): string | null {
if (!payload) return null;
try {
const parsed: unknown = JSON.parse(payload);
Iif (parsed === null || typeof parsed !== "object") return String(parsed);
const parts = Object.entries(parsed as Record<string, unknown>)
.filter(([, v]) => v !== null && v !== undefined && typeof v !== "object")
.map(([k, v]) => `${k.replace(/_/g, " ")}: ${String(v)}`);
return parts.length > 0 ? parts.join(" · ") : null;
} catch {
return payload;
}
}
/**
* `verifyReferral` reports whether money actually moved. `already_credited` is
* not an error — it means a colleague got there first — and reading it as one
* would send the operator chasing a payment that has already been made.
*/
export function creditOutcome(
credited: boolean,
creditReason: string | null,
partner: string,
amountPaise: number = VERIFY_CREDIT_PAISE_FALLBACK,
): Notice {
if (credited) {
return {
tone: "success",
message: `Verified. ₹${formatPaise(amountPaise)} credited to ${partner}.`,
};
}
if (creditReason === "already_credited") {
return {
tone: "info",
message: `Already credited — someone verified this one before you. ${partner} was paid once, not twice.`,
};
}
return {
tone: "warning",
message: `Verified, but no credit was added${
creditReason ? ` — ${humanise(creditReason).toLowerCase()}` : ""
}. Check the partner's ledger before telling them anything.`,
};
}
type Notice = {
tone: "success" | "info" | "warning" | "error";
message: string;
};
const NOTICE_TONES: Record<Notice["tone"], string> = {
success:
"border-notification-success-border bg-notification-success-bg text-notification-success-text",
info: "border-border-default bg-background-subtle text-foreground-default",
warning: "border-warning bg-warning-light text-warning",
error:
"border-notification-error-border bg-notification-error-bg text-notification-error-text",
};
// ─── Queue row ───────────────────────────────────────────────────────────────
function QueueRow({
referral,
selected,
onSelect,
}: {
referral: AdminReferralRow;
selected: boolean;
onSelect: () => void;
}) {
const stale = isStale(referral);
return (
<button
type="button"
onClick={onSelect}
aria-current={selected ? "true" : undefined}
data-testid={`referral-row-${referral.id}`}
className={cn(
"w-full border-b border-border-default px-4 py-3 text-left transition-colors hover:bg-background-muted",
selected && "bg-background-muted",
)}
>
<div className="flex items-center gap-2">
{/* Age leads the row: the operator scans this column for the number
that has grown too big, then reads the name. */}
<span
className={cn(
"inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-0.5 text-xs font-semibold tabular-nums",
stale
? "bg-warning-light text-warning"
: "bg-background-muted text-foreground-muted",
)}
>
{stale && <AlertTriangle className="h-3 w-3" aria-hidden="true" />}
{formatRelative(waitingSince(referral))}
</span>
<span className="truncate text-sm font-medium text-foreground-default">
{referral.contactName}
</span>
</div>
<p className="mt-1 truncate text-xs text-foreground-muted">
{[referral.society, referral.config].filter(Boolean).join(" · ") ||
"No society or home size given"}
</p>
<p className="mt-1 truncate text-xs text-foreground-subtle">
from {referral.partnerName ?? "an unnamed partner"}
</p>
</button>
);
}
// ─── Claim vs conversation ───────────────────────────────────────────────────
function ClaimRow({ label, value }: { label: string; value: string | null }) {
return (
<div className="flex gap-2 text-sm">
<dt className="w-28 shrink-0 text-foreground-muted">{label}</dt>
<dd className="min-w-0 break-words text-foreground-default">
{value ?? <span className="text-foreground-subtle">not given</span>}
</dd>
</div>
);
}
/**
* The endpoint returns whole `wa_messages` rows, so Meta's delivery status is
* already on every message here — `AdminReferralDetail["messages"]` simply does
* not name it. Widened here rather than in the shared API type, which this
* change does not own.
*/
type ThreadMessage = AdminReferralDetail["messages"][number] & {
status?: string;
};
function MessageBubble({ message }: { message: ThreadMessage }) {
const inbound = message.direction === "inbound";
return (
<div
className={cn("flex", inbound ? "justify-start" : "justify-end")}
data-testid={`referral-message-${message.id}`}
>
<div
className={cn(
"max-w-[85%] rounded-lg px-3 py-2 text-sm",
inbound
? "bg-background-muted text-foreground-default"
: // The inbox's sent-bubble palette, not `primary-500`: the ticks
// below tell delivered from read by colour, and blue on
// terracotta is a 1:1 contrast — a status nobody can read.
"bg-whatsapp-bubble-sent dark:bg-whatsapp-green/20 text-foreground-default",
)}
>
<p className="whitespace-pre-wrap break-words">
{message.content ?? (
<span className="italic">
No text — this was {humanise(message.messageType).toLowerCase()}
</span>
)}
</p>
<div className="mt-1 flex items-center justify-end gap-1 text-xs text-foreground-subtle">
<span>
{formatDateTime(message.createdAt)}
{message.messageType !== "text" ? ` · ${message.messageType}` : ""}
</span>
{/* The same ticks as the WhatsApp inbox: one grey = sent, two grey
= delivered, two blue = read, a red alert = failed. Without them
the screen a referral is decided on cannot say whether the last
message ever landed. */}
{!inbound && message.status && (
<span data-testid={`referral-message-status-${message.id}`}>
<StatusIcon status={message.status} />
</span>
)}
</div>
</div>
</div>
);
}
/** Meta's free-form window: 24 hours from the homeowner's last message. */
const WINDOW_MS = 24 * 60 * 60 * 1000;
function Conversation({ detail }: { detail: AdminReferralDetail }) {
const queryClient = useQueryClient();
const reply = useReplyToConversation();
const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null);
// Oldest first. The API makes no ordering promise and a thread read
// backwards is worse than no thread at all.
const messages = [...detail.messages].sort(
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
);
const conversationId = detail.conversation?.id ?? null;
const lastCustomerMessageAt = detail.conversation?.lastCustomerMessageAt;
// The same rule the RRM inbox draws its box from, computed the same way the
// server computes `windowExpiresAt` — no last inbound message means closed,
// never "unknown, try it and see".
const windowOpen = Boolean(
lastCustomerMessageAt &&
Date.now() - new Date(lastCustomerMessageAt).getTime() < WINDOW_MS,
);
async function handleSend() {
const message = draft.trim();
Iif (!conversationId || !message) return;
setError(null);
try {
await reply.mutateAsync({ id: conversationId, body: { message } });
setDraft("");
// The reply hook refreshes the WhatsApp caches; the thread on THIS
// screen comes from the referral detail, which it has never heard of.
queryClient.invalidateQueries({
queryKey: queryKeys.admin.rrm.referral(detail.referral.id),
});
} catch (err) {
// Nothing was sent. Say so here rather than leaving an operator to
// wonder whether the homeowner got it twice.
setError(getErrorMessage(err));
}
}
return (
<Card data-testid="referral-conversation">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-lg">
<MessageSquare
className="h-5 w-5 text-primary-500"
aria-hidden="true"
/>
WhatsApp
</CardTitle>
<p className="text-sm text-foreground-muted">
{detail.conversation?.lastCustomerMessageAt
? `They last wrote ${formatRelative(detail.conversation.lastCustomerMessageAt)}.`
: "The whole thread, so the decision does not need a second screen."}
</p>
</CardHeader>
<CardContent>
{messages.length === 0 ? (
// Not the same as "nothing happened": no thread means the evidence
// this screen is built on is missing, and the operator has to know
// that before deciding rather than after.
<div
className="flex items-start gap-2 rounded-lg border border-warning bg-warning-light p-3 text-sm text-warning"
data-testid="referral-no-conversation"
>
<AlertTriangle
className="mt-0.5 h-4 w-4 shrink-0"
aria-hidden="true"
/>
<p>
No WhatsApp messages on this referral. There is nothing here to
check the partner’s claim against — decide on the timeline
below, or leave it for someone who can reach the homeowner.
</p>
</div>
) : (
<div className="max-h-[45vh] space-y-3 overflow-y-auto">
{messages.map((message) => (
<MessageBubble key={message.id} message={message} />
))}
</div>
)}
{/* Reply, here. Leaving for the inbox and finding the thread by phone
is two screens and a search to answer one question. */}
{conversationId && (
<div className="mt-4 border-t border-border-default pt-4">
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
rows={3}
aria-label="Reply to the homeowner"
data-testid="referral-reply-textarea"
disabled={!windowOpen}
placeholder={
windowOpen
? "Write a reply. It goes to the homeowner on WhatsApp."
: "The 24-hour window is closed."
}
className="w-full rounded-md border border-border-default bg-background-base p-3 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:bg-background-muted disabled:text-foreground-subtle"
/>
{!windowOpen && (
<p
data-testid="referral-window-closed"
className="mt-2 text-xs text-warning"
>
The 24-hour free-form window has closed. Only an approved
template can reach this person now — the API will refuse a plain
reply.
</p>
)}
{error && (
<p
data-testid="referral-reply-error"
className="mt-2 text-xs text-error"
>
{error}
</p>
)}
<div className="mt-2 flex justify-end">
<Button
size="sm"
onClick={handleSend}
disabled={!windowOpen || reply.isPending || !draft.trim()}
data-testid="referral-reply-send"
>
<Send className="h-4 w-4" aria-hidden="true" />
Send reply
</Button>
</div>
</div>
)}
</CardContent>
</Card>
);
}
function Timeline({ events }: { events: AdminReferralDetail["events"] }) {
const ordered = [...events].sort(
(a, b) =>
new Date(b.occurredAt).getTime() - new Date(a.occurredAt).getTime(),
);
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-lg">
<History
className="h-5 w-5 text-foreground-muted"
aria-hidden="true"
/>
What happened
</CardTitle>
</CardHeader>
<CardContent>
{ordered.length === 0 ? (
<p className="text-sm text-foreground-muted">
Nothing has been recorded against this referral yet.
</p>
) : (
<ul className="space-y-3" data-testid="referral-timeline">
{ordered.map((event) => {
const summary = summarisePayload(event.payload);
return (
<li key={event.id} data-testid="referral-timeline-entry">
<p className="text-sm font-medium text-foreground-default">
{humanise(event.type)}
</p>
{summary && (
<p className="text-xs text-foreground-subtle break-words">
{summary}
</p>
)}
<p className="text-xs text-foreground-subtle">
{formatRelative(event.occurredAt)} · by {event.actorType}
</p>
</li>
);
})}
</ul>
)}
</CardContent>
</Card>
);
}
// ─── Page ────────────────────────────────────────────────────────────────────
export function ReferralQueuePage() {
// No status filter: the API answers with `engaged` only, oldest first.
const queueQuery = useAdminReferrals();
const verify = useVerifyReferral();
const reject = useRejectReferral();
const duplicate = useMarkReferralDuplicate();
const advance = useAdvanceReferral();
const recordOutcome = useRecordOutcome();
/**
* The professionals the handoff can pick from — the same 500-row lookup
* every other admin screen uses, rather than a referral-only endpoint.
*/
const { data: pros = [] } = useAdminProLookup();
const reverse = useReverseEarning();
const clawback = useClawbackEarning();
const { referralId } = useParams({ strict: false }) as {
referralId?: string;
};
/**
* Two empties, deliberately. `undefined` is "has clicked nothing since
* arriving"; `null` is "acted on the last row and there is nothing after
* it". Sharing one sentinel made working the queue dry snap the pane back
* to the referral in the URL — see the three cases on `activeId`.
*/
const [selectedId, setSelectedId] = useState<string | null | undefined>(
undefined,
);
/**
* Both drafts carry the referral they belong to.
*
* The selection is derived, so a refetch can move it out from under an open
* dialog — a colleague verifies this referral, it leaves the engaged-only
* queue, and the pane falls through to the next one. Tying the draft to an
* id is what stops that confirmation from crediting a referral the operator
* never read, or a typed rejection reason from reaching the wrong partner.
*/
const [confirming, setConfirming] = useState<{
kind:
| "verify"
| "convert"
| "duplicate"
| "handoff"
| "reverse"
| "clawback";
/** The referral, for the first four; the EARNING, for the other two. */
id: string;
} | null>(null);
/**
* The withdrawal being written, against the one earning it is for.
*
* `reason` is a plain string because that is what a `<select>` gives back;
* it is narrowed against `REVERSAL_REASONS` at submit rather than cast, so
* a stale option can never reach the API as a reason the ledger cannot
* explain.
*/
const [withdrawal, setWithdrawal] = useState<{
id: string;
reason: string;
notes: string;
} | null>(null);
const [draft, setDraft] = useState<{ id: string; reason: string }>({
id: "",
reason: "",
});
/**
* The optional internal note — for the verify decision and, later, the
* conversion. One draft for both because they are never on screen together
* (`engaged` versus `quoted`), and both write the same column.
*
* Kept apart from the rejection draft, though: those are two different
* decisions, and one `setState` replacing the other's text is the bug that
* reads as the screen eating what you typed.
*/
const [noteDraft, setNoteDraft] = useState<{ id: string; note: string }>({
id: "",
note: "",
});
/**
* The professional picked for the handoff, keyed to its referral for the
* same reason the other two drafts are: the selection is derived, and a
* pro chosen for one referral must never be confirmed against another.
*/
const [handoff, setHandoff] = useState<{ id: string; proId: string }>({
id: "",
proId: "",
});
const [notice, setNotice] = useState<Notice | null>(null);
const page = queueQuery.data?.data;
const referrals = page?.referrals ?? [];
/**
* Which referral the pane shows. Derived, never stored — three cases:
*
* 1. The operator clicked a row and it is still in the queue: that one.
* 2. They clicked a row a colleague has since decided, so it has left the
* queue: the top of what is left, rather than a blank pane.
* 3. They clicked nothing and arrived by LINK: the referral in the URL.
* The queue lists `engaged` only, and everything this screen does past
* verification happens to a referral that has left it. `routes.tsx`
* already points `/admin/rrm/referrals/:referralId` here for exactly
* that — the page just never read the parameter, so every row of the
* referrals table opened whatever was at the top of the queue.
*
* Case 3 is `selectedId === undefined` — never touched — not "not in the
* queue" and not "empty". Once they click inside the page the link has been
* left behind, and a stale selection must fall through (case 2) rather than
* snap back to where they arrived. `advancePast` sets `null` when it runs
* off the end of the queue, which is exactly that stale case.
*/
const activeId =
referrals.find((r) => r.id === selectedId)?.id ??
(selectedId === undefined && referralId ? referralId : referrals[0]?.id);
const detailQuery = useAdminReferral(activeId);
const detail = detailQuery.data?.data;
// Keyed to the referral the pane is actually showing — which is the one
// every action on this screen acts on.
const shownId = detail?.referral.id;
const rejectReason = draft.id === shownId ? draft.reason : "";
const noteForRecord = noteDraft.id === shownId ? noteDraft.note : "";
const handoffProId = handoff.id === shownId ? handoff.proId : "";
const busy =
verify.isPending ||
reject.isPending ||
duplicate.isPending ||
advance.isPending ||
recordOutcome.isPending;
/** Down the list, not back to the top — this is the whole ergonomic claim. */
function advancePast(id: string) {
const index = referrals.findIndex((r) => r.id === id);
// Not in the queue — opened by link, or already past `engaged`. Moving
// to the top of a queue the operator was not working would hide the
// result of what they just did.
Iif (index === -1) return;
setSelectedId(referrals[index + 1]?.id ?? null);
}
async function act(id: string, work: () => Promise<Notice>) {
setNotice(null);
try {
const result = await work();
setNotice(result);
advancePast(id);
} catch (err) {
// The referral stays in the queue, so the operator has to be told why
// rather than left to wonder whether the click registered.
setNotice({ tone: "error", message: getErrorMessage(err) });
}
}
function handleVerify(referral: AdminReferralRow) {
setConfirming(null);
const note = noteForRecord.trim();
void act(referral.id, async () => {
// Sent only when there is one: an empty note is not a note, and the
// audit log should not carry an empty string as if an operator had
// written something.
const response = await verify.mutateAsync({
id: referral.id,
note: note || undefined,
});
const partner = referral.partnerName ?? "the partner";
return creditOutcome(
response.data?.credited ?? false,
response.data?.creditReason ?? null,
partner,
);
});
}
function handleReject(referral: AdminReferralRow) {
const reason = rejectReason.trim();
// The button is disabled while this is empty; the guard is what any second
// caller — a keyboard shortcut, a canned reason chip — would hit.
Iif (!reason) return;
void act(referral.id, async () => {
await reject.mutateAsync({ id: referral.id, reason });
return {
tone: "success",
message: `Rejected. ${referral.partnerName ?? "The partner"} will see your reason.`,
};
});
}
/**
* The handoff. Everything past this point on a referral happens because a
* professional has it — which is why this is the one action that names one.
*/
function handleHandoff(referral: AdminReferralRow) {
setConfirming(null);
const proId = handoffProId;
Iif (!proId) return;
void act(referral.id, async () => {
const response = await advance.mutateAsync({
id: referral.id,
to: "contacted",
proId,
});
setHandoff({ id: "", proId: "" });
const pro = pros.find((p) => p.id === proId)?.businessName ?? "them";
return {
tone: "success",
message: `Handed to ${pro}. Enquiry #${response.data?.inquiryId ?? ""} is in their CRM and they have been notified.`,
};
});
}
function handleQuote(referral: AdminReferralRow) {
void act(referral.id, async () => {
await advance.mutateAsync({ id: referral.id, to: "quoted" });
return {
tone: "success",
message: `Quote recorded. ${referral.partnerName ?? "The partner"} can now be credited the conversion if it goes ahead.`,
};
});
}
/**
* The conversion payment — the other end of the money, and until now
* reachable only with curl.
*
* `outcome` is the ONLY route that credits `converted`; it moves the
* referral through the state machine first, which is why the button appears
* at `quoted` and nowhere else. A 409 back from it is not a failure: a
* colleague credited it a moment ago, or the referral moved under the open
* screen. Both are things to READ, so they are shown as a notice in the
* API's own words rather than in red.
*/
function handleConvert(referral: AdminReferralRow, amountPaise: number) {
setConfirming(null);
const note = noteForRecord.trim();
void act(referral.id, async () => {
const partner = referral.partnerName ?? "the partner";
try {
await recordOutcome.mutateAsync({
id: referral.id,
kind: "converted",
notes: note || undefined,
});
return {
tone: "success",
message: `Converted. ₹${formatPaise(amountPaise)} credited to ${partner}.`,
};
} catch (err) {
Eif (err instanceof ApiError && err.status === 409) {
return { tone: "info", message: getErrorMessage(err) };
}
throw err;
}
});
}
function handleLost(referral: AdminReferralRow) {
const reason = rejectReason.trim();
// The button is disabled while this is empty; the guard is what any
// second caller would hit. The API refuses it too.
Iif (!reason) return;
void act(referral.id, async () => {
await advance.mutateAsync({ id: referral.id, to: "lost", reason });
return {
tone: "success",
message: `Closed as not proceeding. Anything already credited to ${referral.partnerName ?? "the partner"} stands.`,
};
});
}
function handleDuplicate(referral: AdminReferralRow) {
setConfirming(null);
void act(referral.id, async () => {
await duplicate.mutateAsync(referral.id);
return {
tone: "success",
message: `Marked as a duplicate. Nothing was credited for ${referral.contactName}.`,
};
});
}
/**
* Reverse or claw back one earning.
*
* Deliberately NOT routed through `act()`: that advances past the referral,
* and withdrawing a credit does not settle the referral or take it out of
* the queue. The operator stays where they are and reads what happened.
*/
async function handleWithdrawal(
earning: AdminEarningRow,
action: "reverse" | "clawback",
) {
setConfirming(null);
setNotice(null);
Iif (withdrawal?.id !== earning.id) return;
// Narrowed against the union rather than cast: the value came from a
// `<select>`, and the reason column is the one field that has to explain
// this to a partner months later.
const reason = REVERSAL_REASONS.find((r) => r === withdrawal.reason);
Iif (!reason) return;
const notes = withdrawal.notes.trim();
try {
await (action === "reverse" ? reverse : clawback).mutateAsync({
id: earning.id,
reason,
notes: notes || undefined,
});
setWithdrawal(null);
setNotice(
action === "reverse"
? {
tone: "success",
message:
"Reversed. The row stays on the ledger with your reason — say so on the thread, a balance that shrinks in silence is how this becomes an accusation.",
}
: {
tone: "success",
message:
"Clawed back. It comes off their next payment; the one already sent is untouched.",
},
);
} catch (err) {
// The API's 409s are written for an operator to act on — "has not been
// paid — reverse it instead", "already been clawed back". Shown as
// written, and the draft is left standing so nothing typed is lost.
setNotice({ tone: "error", message: getErrorMessage(err) });
}
}
if (queueQuery.isLoading) {
return (
<div className="space-y-6" data-testid="referral-queue-loading">
<Skeleton className="h-9 w-72" />
<div className="flex flex-col gap-4 lg:flex-row">
<Skeleton className="h-96 w-full lg:w-80" />
<Skeleton className="h-96 w-full" />
</div>
</div>
);
}
if (queueQuery.error) {
return (
<div className="space-y-6">
<PageHeader
title="Verification queue"
description="Referrals waiting on a decision."
/>
<Card>
<CardContent className="pt-6">
<EmptyState
icon={AlertTriangle}
title="Could not load the queue"
description={getErrorMessage(queueQuery.error)}
/>
</CardContent>
</Card>
</div>
);
}
const total = page?.total ?? referrals.length;
/**
* What this referral can be moved to NOW, from `lib/partners/state.ts`.
*
* One boolean per action rather than one `canAct`: a referral past
* verification is not "already decided", it is waiting on a DIFFERENT
* decision, and a screen that greyed everything out at `verified` is why
* nothing in the programme ever reached `converted`.
*/
const status = detail?.referral.status;
const canDecide = status === "engaged";
const canHandoff = status === "verified";
const canQuote = status === "contacted";
// The ₹1,000. `quoted` only — the state machine allows nothing else into
// `converted`, and the money route runs that transition before it credits.
const canConvert = status === "quoted";
const canLose = status === "contacted" || status === "quoted";
// Genuinely finished — or not ours to move yet (draft, forwarded).
const settled =
!canDecide && !canHandoff && !canQuote && !canConvert && !canLose;
/**
* The LIVE rate, from the detail response. The fallback only covers the
* moment before it loads — an operator must never be shown one figure and
* have the ledger record another.
*/
const verifyAmountPaise =
detail?.verifyAmountPaise ?? VERIFY_CREDIT_PAISE_FALLBACK;
return (
<div className="space-y-4" data-testid="referral-queue-page">
<PageHeader
title="Verification queue"
description="Engaged referrals, oldest first. The WhatsApp thread is on this page — you should never need to open WhatsApp to decide."
icon={
<BadgeCheck className="h-6 w-6 text-primary-500" aria-hidden="true" />
}
actions={
<StatusBadge
status={total === 1 ? "1 waiting" : `${total} waiting`}
variant={total > 0 ? "warning" : "success"}
/>
}
/>
{notice && (
<p
role="status"
data-testid="referral-queue-notice"
className={cn(
"rounded-lg border p-3 text-sm",
NOTICE_TONES[notice.tone],
)}
>
{notice.message}
</p>
)}
{referrals.length === 0 && !activeId ? (
<Card>
<CardContent className="pt-6" data-testid="referral-queue-empty">
<EmptyState
icon={CheckCircle2}
title="All caught up"
description="Nothing is waiting to be verified — good place to be. The next referral lands here the moment a homeowner replies on WhatsApp."
/>
</CardContent>
</Card>
) : (
<div className="flex flex-col gap-4 lg:flex-row lg:items-start">
{/* Left — the queue. Absent when there is none, which is what a
referral opened from the table looks like. */}
{referrals.length > 0 && (
<Card className="w-full lg:w-80 lg:shrink-0">
<div className="max-h-[75vh] overflow-y-auto">
{referrals.map((referral) => (
<QueueRow
key={referral.id}
referral={referral}
selected={referral.id === activeId}
onSelect={() => setSelectedId(referral.id)}
/>
))}
</div>
{referrals.length < total && (
<p className="border-t border-border-default p-3 text-xs text-foreground-muted">
Showing the oldest {referrals.length} of {total}. Clear these
and the rest move up.
</p>
)}
</Card>
)}
{/* Right — the decision */}
<div className="min-w-0 flex-1 space-y-4">
{detailQuery.isLoading || !detail ? (
<Card>
<CardContent className="pt-6">
{detailQuery.error ? (
<EmptyState
icon={AlertTriangle}
title="Could not load this referral"
description={getErrorMessage(detailQuery.error)}
/>
) : (
<div
className="space-y-3"
data-testid="referral-detail-loading"
>
<Skeleton className="h-8 w-64" />
<Skeleton className="h-40 w-full" />
</div>
)}
</CardContent>
</Card>
) : (
<>
<Card data-testid="referral-detail">
<CardContent className="space-y-3 pt-6">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<h2 className="font-heading text-xl font-bold text-foreground-default">
{detail.referral.contactName}
</h2>
<p className="font-mono text-sm text-foreground-default">
{detail.referral.contactPhoneNorm}
</p>
</div>
<div className="flex items-center gap-2">
<ReferralStatusBadge status={detail.referral.status} />
<span className="font-mono text-xs text-foreground-subtle">
{detail.referral.code}
</span>
</div>
</div>
{detail.firstReferral && (
<div
className="flex items-start gap-2 rounded-lg border border-warning bg-warning-light p-3 text-sm text-warning"
data-testid="referral-duplicate-warning"
>
<Copy
className="mt-0.5 h-4 w-4 shrink-0"
aria-hidden="true"
/>
<p>
This household was referred before, as{" "}
<span className="font-mono">
{detail.firstReferral.code}
</span>{" "}
on {formatDateTime(detail.firstReferral.dateCreated)}.
First submission wins.
</p>
</div>
)}
{detail.partner?.suspendedAt && (
<div
className="flex items-start gap-2 rounded-lg border border-error bg-error-light p-3 text-sm text-error"
data-testid="referral-partner-suspended"
>
<ShieldAlert
className="mt-0.5 h-4 w-4 shrink-0"
aria-hidden="true"
/>
<p>
This partner is suspended. Verifying still credits
them — check why they were suspended first.
</p>
</div>
)}
<dl className="grid gap-2 sm:grid-cols-2">
<ClaimRow
label="Society"
value={detail.referral.society}
/>
<ClaimRow
label="Home size"
value={detail.referral.config}
/>
<ClaimRow
label="Possession"
value={detail.referral.possessionBand}
/>
<ClaimRow
label="Mode"
value={humanise(detail.referral.mode)}
/>
<ClaimRow
label="Partner"
value={
detail.partner
? [detail.partner.name, detail.partner.firmName]
.filter(Boolean)
.join(" · ")
: (detail.referral.partnerName ?? null)
}
/>
<ClaimRow
label="Partner phone"
value={
detail.partner?.phoneNorm ??
detail.referral.partnerPhone
}
/>
</dl>
<p className="text-xs text-foreground-subtle">
That is what the partner told us. The thread below is what
actually happened.
</p>
</CardContent>
</Card>
<Conversation key={detail.referral.id} detail={detail} />
{/* Actions sit under the thread on purpose: the operator reads,
then decides. */}
<Card data-testid="referral-actions">
<CardHeader>
<CardTitle className="text-lg">Decide</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{settled && (
<p
className="rounded-lg border border-border-default bg-background-subtle p-3 text-sm text-foreground-default"
data-testid="referral-already-decided"
>
This one is{" "}
{STATUS_LABELS[detail.referral.status].toLowerCase()} —
nothing left to do here.
</p>
)}
{detail.referral.inquiryId && (
<p
className="text-sm text-foreground-muted"
data-testid="referral-inquiry-link"
>
Handed to a professional as enquiry{" "}
<span className="font-mono text-foreground-default">
#{detail.referral.inquiryId}
</span>
. It is in their CRM like any other lead.
</p>
)}
{detail.referral.rejectedReason && (
<p className="text-sm text-foreground-muted">
Rejection reason on record:{" "}
<span className="text-foreground-default">
{detail.referral.rejectedReason}
</span>
</p>
)}
{/* Engaged: the three verification decisions. They are RENDERED
only here — a disabled "Verify — credits ₹100" next to an
enabled handoff is a screen that cannot say what it wants. */}
{canDecide && (
<>
<div className="space-y-2">
<label
htmlFor="referral-verify-note"
className="block text-sm font-medium text-foreground-default"
>
Note for the record{" "}
<span className="font-normal text-foreground-subtle">
(optional)
</span>
</label>
<input
id="referral-verify-note"
data-testid="referral-verify-note"
type="text"
maxLength={300}
value={noteForRecord}
disabled={!canDecide || busy}
onChange={(e) =>
setNoteDraft({
id: detail.referral.id,
note: e.target.value,
})
}
placeholder="Confirmed the possession date on the call."
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:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
/>
<p className="text-xs text-foreground-muted">
Internal — the partner never sees it. The
conversation and the homeowner’s last message
are recorded on their own, so this is only for what
they do not show.
</p>
<Button
className="w-full sm:w-auto"
disabled={!canDecide || busy}
isLoading={verify.isPending}
onClick={() =>
setConfirming({
kind: "verify",
id: detail.referral.id,
})
}
data-testid="referral-verify"
>
<CheckCircle2 aria-hidden="true" />
Verify — credits ₹{formatPaise(verifyAmountPaise)}
</Button>
{/* The consequence, before the click. */}
<p
className="text-sm text-foreground-muted"
data-testid="referral-verify-consequence"
>
Pays ₹{formatPaise(verifyAmountPaise)} to{" "}
{detail.partner?.name ??
detail.referral.partnerName ??
"the partner"}
. You cannot take it back from this screen — a
reversal is a separate action, in someone’s
name.
</p>
</div>
<div className="space-y-2 border-t border-border-default pt-4">
<label
htmlFor="referral-reject-reason"
className="block text-sm font-medium text-foreground-default"
>
Why are you rejecting this?
</label>
<textarea
id="referral-reject-reason"
data-testid="referral-reject-reason"
rows={2}
value={rejectReason}
disabled={!canDecide || busy}
onChange={(e) =>
setDraft({
id: detail.referral.id,
reason: e.target.value,
})
}
placeholder="Wrong number — the homeowner said they never asked to be referred."
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:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
/>
<p className="text-sm text-foreground-muted">
The partner reads this word for word, so write it to
them, not about them. A reason is required.
</p>
<Button
variant="outline"
className="w-full sm:w-auto"
disabled={
!canDecide || busy || rejectReason.trim() === ""
}
isLoading={reject.isPending}
onClick={() => handleReject(detail.referral)}
data-testid="referral-reject"
>
<XCircle aria-hidden="true" />
Reject
</Button>
</div>
<div className="border-t border-border-default pt-4">
<Button
variant="outline"
className="w-full sm:w-auto"
disabled={!canDecide || busy}
isLoading={duplicate.isPending}
onClick={() =>
setConfirming({
kind: "duplicate",
id: detail.referral.id,
})
}
data-testid="referral-duplicate"
>
<Copy aria-hidden="true" />
Duplicate
</Button>
<p className="mt-2 text-sm text-foreground-muted">
Same household as an earlier referral. Nothing is
credited, and the first submission keeps the claim.
</p>
</div>
</>
)}
{/* Verified: the handoff. The FIRST moment an inquiry can
exist — `inquiries.pro_id` is NOT NULL, so a lead cannot
be raised until a human picks the professional. */}
{canHandoff && (
<div className="space-y-2">
<label
htmlFor="referral-handoff-pro"
className="block text-sm font-medium text-foreground-default"
>
Which professional is taking this?
</label>
<select
id="referral-handoff-pro"
data-testid="referral-handoff-pro"
value={handoffProId}
disabled={busy}
onChange={(e) =>
setHandoff({
id: detail.referral.id,
proId: e.target.value,
})
}
className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
>
<option value="">Choose a professional…</option>
{pros.map((pro) => (
<option key={pro.id} value={pro.id}>
{pro.businessName}
</option>
))}
</select>
<Button
className="w-full sm:w-auto"
disabled={busy || handoffProId === ""}
isLoading={advance.isPending}
onClick={() =>
setConfirming({
kind: "handoff",
id: detail.referral.id,
})
}
data-testid="referral-handoff"
>
<Handshake aria-hidden="true" />
Hand to a designer
</Button>
<p className="text-sm text-foreground-muted">
This raises a real enquiry against them —{" "}
{detail.referral.contactName} lands in their CRM and
they are notified, exactly as if the enquiry had come
through the site.
</p>
</div>
)}
{/* Contacted: the quote went out. */}
{canQuote && (
<div className="space-y-2">
<Button
className="w-full sm:w-auto"
disabled={busy}
isLoading={advance.isPending}
onClick={() => handleQuote(detail.referral)}
data-testid="referral-quoted"
>
<FileText aria-hidden="true" />
Quote issued
</Button>
<p className="text-sm text-foreground-muted">
Mark this once the professional has priced the job.
The ₹1,000 conversion cannot be credited until it is —
that is deliberate, not a bug.
</p>
</div>
)}
{/* Quoted: the conversion. The ONLY place the ₹1,000 is
credited — there is no other route to it. */}
{canConvert && (
<div className="space-y-2">
<label
htmlFor="referral-convert-note"
className="block text-sm font-medium text-foreground-default"
>
Note for the record{" "}
<span className="font-normal text-foreground-subtle">
(optional)
</span>
</label>
<input
id="referral-convert-note"
data-testid="referral-convert-note"
type="text"
maxLength={300}
value={noteForRecord}
disabled={busy}
onChange={(e) =>
setNoteDraft({
id: detail.referral.id,
note: e.target.value,
})
}
placeholder="Signed on 12 Sep — designer confirmed the advance."
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:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
/>
<Button
className="w-full sm:w-auto"
disabled={busy}
isLoading={recordOutcome.isPending}
onClick={() =>
setConfirming({
kind: "convert",
id: detail.referral.id,
})
}
data-testid="referral-convert"
>
<Banknote aria-hidden="true" />
Mark converted — credits ₹
{formatPaise(detail.convertAmountPaise)}
</Button>
<p
className="text-sm text-foreground-muted"
data-testid="referral-convert-consequence"
>
Only once the homeowner has actually signed with the
professional. Pays ₹
{formatPaise(detail.convertAmountPaise)} to{" "}
{detail.partner?.name ??
detail.referral.partnerName ??
"the partner"}
, on top of the ₹{formatPaise(verifyAmountPaise)}{" "}
verification, and closes the referral for good.
</p>
</div>
)}
{/* Contacted or quoted: the dead end. */}
{canLose && (
<div className="space-y-2 border-t border-border-default pt-4">
<label
htmlFor="referral-lost-reason"
className="block text-sm font-medium text-foreground-default"
>
Why is this not going ahead?
</label>
<textarea
id="referral-lost-reason"
data-testid="referral-lost-reason"
rows={2}
value={rejectReason}
disabled={busy}
onChange={(e) =>
setDraft({
id: detail.referral.id,
reason: e.target.value,
})
}
placeholder="Homeowner went with their builder's in-house team."
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:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
/>
<p className="text-sm text-foreground-muted">
Internal — the partner sees only “Not
proceeding”. Anything already credited to them
still stands.
</p>
<Button
variant="outline"
className="w-full sm:w-auto"
disabled={busy || rejectReason.trim() === ""}
isLoading={advance.isPending}
onClick={() => handleLost(detail.referral)}
data-testid="referral-lost"
>
<Ban aria-hidden="true" />
Lost
</Button>
</div>
)}
</CardContent>
</Card>
<Timeline events={detail.events} />
{detail.earnings.length > 0 && (
<Card data-testid="referral-earnings">
<CardHeader>
<CardTitle className="text-lg">Ledger</CardTitle>
</CardHeader>
<CardContent>
<ul className="space-y-3 text-sm">
{detail.earnings.map((earning) => {
const action = withdrawalFor(
earning,
detail.earnings,
);
const partner =
detail.partner?.name ??
detail.referral.partnerName ??
"the partner";
// Keyed to the row, like every other draft on this
// screen: a refetch can reorder the ledger under an
// open form, and a reason typed against one earning
// must never be submitted against another.
const form =
withdrawal?.id === earning.id ? withdrawal : null;
return (
<li
key={earning.id}
className="space-y-2 border-b border-border-default pb-3 last:border-b-0 last:pb-0"
>
<div className="flex flex-wrap items-baseline justify-between gap-2">
<span className="text-foreground-default">
₹{formatPaise(earning.amountPaise)} ·{" "}
{humanise(earning.kind)}
</span>
<span className="text-xs text-foreground-subtle">
{earning.reversedAt
? `Reversed ${formatDateTime(earning.reversedAt)}`
: `${humanise(earning.state)} · held until ${formatDateTime(earning.holdUntil)}`}
</span>
</div>
{/*
* The row is live but locked to a payout an
* operator already requested. The API's 409 for
* this blames the state, which is not what is
* wrong — so say what actually is, and what to
* do about it.
*/}
{!action &&
earning.payoutId &&
earning.state !== "paid" && (
<p
className="text-xs text-foreground-muted"
data-testid={`earning-locked-${earning.id}`}
>
Attached to a pending payout. Fail that
payout first — it detaches the earning —
then reverse it.
</p>
)}
{action && !form && (
<Button
variant="outline"
size="sm"
onClick={() =>
setWithdrawal({
id: earning.id,
reason: "",
notes: "",
})
}
data-testid={`earning-${action}-${earning.id}`}
>
<Undo2 aria-hidden="true" />
{action === "reverse"
? "Reverse"
: "Claw back"}
</Button>
)}
{action && form && (
<div className="space-y-2 rounded-md border border-border-default bg-background-subtle p-3">
<label
htmlFor={`earning-reason-${earning.id}`}
className="block text-sm font-medium text-foreground-default"
>
Why?
</label>
<select
id={`earning-reason-${earning.id}`}
data-testid={`earning-reason-${earning.id}`}
value={form.reason}
onChange={(e) =>
setWithdrawal({
id: earning.id,
reason: e.target.value,
notes: form.notes,
})
}
className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="">Choose a reason</option>
{REVERSAL_REASONS.map((reason) => (
<option key={reason} value={reason}>
{humanise(reason)}
</option>
))}
</select>
<input
type="text"
maxLength={300}
aria-label="Note for the record (optional)"
data-testid={`earning-notes-${earning.id}`}
value={form.notes}
onChange={(e) =>
setWithdrawal({
id: earning.id,
reason: form.reason,
notes: e.target.value,
})
}
placeholder="Spoke to the homeowner — they never asked to be referred."
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:outline-none focus:ring-2 focus:ring-primary-500"
/>
<p className="text-xs text-foreground-muted">
The reason reaches {partner} on their own
dashboard, in words. The note is internal.
</p>
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
size="sm"
disabled={form.reason === ""}
isLoading={
action === "reverse"
? reverse.isPending
: clawback.isPending
}
onClick={() =>
setConfirming({
kind: action,
id: earning.id,
})
}
data-testid={`earning-submit-${earning.id}`}
>
{action === "reverse"
? "Reverse"
: "Claw back"}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setWithdrawal(null)}
data-testid={`earning-cancel-${earning.id}`}
>
Cancel
</Button>
</div>
</div>
)}
{action && (
<ConfirmDialog
open={
confirming?.kind === action &&
confirming.id === earning.id
}
variant="destructive"
title={
action === "reverse"
? `Reverse ₹${formatPaise(earning.amountPaise)}?`
: `Claw back ₹${formatPaise(earning.amountPaise)}?`
}
description={
action === "reverse"
? `This withdraws the credit from ${partner}. The row stays on the ledger carrying your name and your reason, so "why did my balance drop?" still has an answer months from now — but tell them on the thread too.`
: `The settled row is not touched — this writes a negative row that comes off ${partner}'s NEXT payment. We never ask anyone for money back. One clawback per referral; a second is refused by the database.`
}
confirmLabel={
action === "reverse"
? "Reverse the credit"
: "Claw it back"
}
onConfirm={() =>
handleWithdrawal(earning, action)
}
onCancel={() => setConfirming(null)}
/>
)}
</li>
);
})}
</ul>
</CardContent>
</Card>
)}
<ConfirmDialog
open={
confirming?.kind === "verify" &&
confirming.id === detail.referral.id
}
title={`Credit ₹${formatPaise(verifyAmountPaise)}?`}
description={`This marks ${detail.referral.contactName} verified and pays ₹${formatPaise(
verifyAmountPaise,
)} to ${
detail.partner?.name ??
detail.referral.partnerName ??
"the partner"
}. It cannot be undone from this screen — reversing a credit is a separate action, recorded against whoever does it.`}
confirmLabel={`Verify and credit ₹${formatPaise(verifyAmountPaise)}`}
onConfirm={() => handleVerify(detail.referral)}
onCancel={() => setConfirming(null)}
/>
<ConfirmDialog
open={
confirming?.kind === "convert" &&
confirming.id === detail.referral.id
}
title={`Credit ₹${formatPaise(detail.convertAmountPaise)}?`}
description={`This marks ${detail.referral.contactName} converted and pays ₹${formatPaise(
detail.convertAmountPaise,
)} to ${
detail.partner?.name ??
detail.referral.partnerName ??
"the partner"
}. Converted is the end of the road for a referral — nothing moves it afterwards, and taking the money back is a separate action in someone's name.`}
confirmLabel={`Convert and credit ₹${formatPaise(detail.convertAmountPaise)}`}
onConfirm={() =>
handleConvert(detail.referral, detail.convertAmountPaise)
}
onCancel={() => setConfirming(null)}
/>
<ConfirmDialog
open={
confirming?.kind === "handoff" &&
confirming.id === detail.referral.id
}
title="Hand this referral to a designer?"
description={`This raises a real enquiry for ${detail.referral.contactName} against ${
pros.find((p) => p.id === handoffProId)?.businessName ??
"that professional"
} and notifies them. It is a lead in their CRM from that moment — there is no undo on this screen.`}
confirmLabel="Hand over and notify"
onConfirm={() => handleHandoff(detail.referral)}
onCancel={() => setConfirming(null)}
/>
<ConfirmDialog
open={
confirming?.kind === "duplicate" &&
confirming.id === detail.referral.id
}
variant="destructive"
title="Mark as a duplicate?"
description={
detail.firstReferral
? `This closes the referral against ${detail.firstReferral.code}. Nothing is credited, and the partner sees it as a duplicate.`
: "This closes the referral as a repeat of an earlier one. Nothing is credited, and the partner sees it as a duplicate."
}
confirmLabel="Mark duplicate"
onConfirm={() => handleDuplicate(detail.referral)}
onCancel={() => setConfirming(null)}
/>
</>
)}
</div>
</div>
)}
</div>
);
}
export default ReferralQueuePage;
|