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 | 1x 1x 1x 1x 1x 1x 39x 3x 36x 73x 73x 73x 73x 73x 73x 73x 2x 8x 8x 8x 8x 3x 3x 3x 5x 5x 3x 3x 3x 3x 2x 2x 2x 1x 71x 29x 12x 3x 3x 7x 1x 42x 9x 3x 1x 1x 2x 1x 33x 12x 5x 39x 1x 5x 40x 40x 40x 40x 40x 39x 37x 40x 160x 3x 3x 39x | import { Link } from "@tanstack/react-router";
import { AlertTriangle, Banknote, IndianRupee } from "lucide-react";
import { type ReactNode, useState } from "react";
import { Button } from "../../../components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../../../components/ui/card";
import { 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 {
useRrmFailPayout,
useRrmPayouts,
useRrmSettlePayout,
} from "../../../hooks/queries/useRrmQueries";
import type {
AdminPayoutRow,
RrmPayoutState,
} from "../../../lib/api/admin/rrm";
import { ApiError, getErrorMessage } from "../../../lib/api/base";
import { formatPaise } from "../../../lib/currency-utils";
import { formatDateTime, formatRelative } from "./prospects";
/**
* The settle queue (F-21, FR-M-4).
*
* Until this screen existed the five money endpoints had no UI at all: an
* operator could credit a partner and then had no way to pay them. That is the
* gap it closes, and it is why every affordance here is about ONE payment
* rather than a batch — the owner's decision is "pay each one as it comes"
* (2026-08-31), so there is no batch file and no reconciliation step.
*
* The consequence of that decision is stated rather than hidden: a batch total
* that must match the sum of its rows is the control that catches a mis-keyed
* transfer, and paying one-by-one has no equivalent. The amount is therefore
* rendered large, next to the UPI id, and is never editable here.
*
* MONEY MOVES OUTSIDE THIS SCREEN. The operator pays by UPI in their banking
* app and comes back to record it. Nothing here initiates a transfer.
*/
const HEADER_CELL =
"px-4 py-3 text-left text-xs font-medium text-foreground-muted uppercase tracking-wider";
const COLUMN_COUNT = 6;
const SKELETON_KEYS = ["a", "b", "c", "d", "e"];
const STATE_LABEL: Record<RrmPayoutState, string> = {
pending: "Awaiting payment",
sent: "Paid",
failed: "Failed",
cancelled: "Cancelled",
};
const STATE_TONE: Record<RrmPayoutState, "warning" | "success" | "error"> = {
pending: "warning",
sent: "success",
failed: "error",
cancelled: "error",
};
const TABS: Array<{ value: RrmPayoutState | "all"; label: string }> = [
{ value: "pending", label: "To pay" },
{ value: "sent", label: "Paid" },
{ value: "failed", label: "Failed" },
{ value: "all", label: "Everything" },
];
/** `action`: the one thing the operator can do about it, when there is one. */
type Notice = {
tone: "success" | "error";
message: string;
action?: ReactNode;
};
/** Their name, their firm, and the number to check it against. */
function PartnerCell({ payout }: { payout: AdminPayoutRow }) {
// A hard-deleted partner still has to show — a money row missing from the
// operator's list is the worse failure, so the API left-joins.
if (!payout.partnerName && !payout.partnerFirmName) {
return (
<div data-testid="rrm-payouts-partner">
<p className="text-sm font-medium text-foreground-muted">
Partner record removed
</p>
<p className="font-mono text-xs text-foreground-subtle">
{payout.partnerId}
</p>
</div>
);
}
return (
<div data-testid="rrm-payouts-partner">
<p className="text-sm font-medium text-foreground-default">
{payout.partnerName ?? "Unnamed"}
</p>
{payout.partnerFirmName && (
<p className="text-xs text-foreground-muted">
{payout.partnerFirmName}
</p>
)}
{payout.partnerPhoneNorm && (
<p className="font-mono text-xs text-foreground-subtle">
{payout.partnerPhoneNorm}
</p>
)}
</div>
);
}
/**
* One row's actions.
*
* Owns its own mutations so pending state is per-row: a shared instance across
* the table disables every Settle button the moment any one of them is clicked,
* which on a money screen reads as the whole queue having been paid.
*/
function PayoutActions({
payout,
onNotice,
}: {
payout: AdminPayoutRow;
onNotice: (notice: Notice) => void;
}) {
const settle = useRrmSettlePayout();
const fail = useRrmFailPayout();
const [open, setOpen] = useState<"settle" | "fail" | null>(null);
const [reference, setReference] = useState("");
const [failureReason, setFailureReason] = useState("");
// One flag for both: an operator must not be able to start a failure while
// a settle for the same row is still in flight.
const busy = settle.isPending || fail.isPending;
if (payout.state !== "pending") {
return payout.reference ? (
<span
data-testid="rrm-payouts-reference"
className="font-mono text-xs text-foreground-muted"
title={payout.settledAt ? formatDateTime(payout.settledAt) : undefined}
>
{payout.reference}
</span>
) : (
<span className="text-sm text-foreground-muted">
{payout.failureReason ?? "—"}
</span>
);
}
async function handleSettle() {
const trimmed = reference.trim();
// The button is disabled while this is empty; the guard is what any
// second caller would hit. The API refuses a blank one too — a settled
// payout nobody can trace is a dispute with no evidence.
Iif (!trimmed || busy) return;
try {
await settle.mutateAsync({ id: payout.id, reference: trimmed });
setOpen(null);
setReference("");
onNotice({
tone: "success",
message: `Recorded $₹{formatPaise(payout.amountPaise)} to ${payout.partnerName ?? "the partner"}.`,
});
} catch (err) {
// Surfaced as the server wrote it. PAN_REQUIRED (FR-M-7) explains a
// tax rule with both numbers in it, and REFERENCE_REQUIRED says
// exactly what is missing — rewording either loses the operator the
// only thing they can act on.
//
// PAN_REQUIRED also gets the way out: the partner enters it in their
// app, and when it came on WhatsApp instead the operator records it
// on the partner's row. The link searches by phone, the one column
// that is unique. A hard-deleted partner has no row to land on.
const panRequired =
err instanceof ApiError &&
err.code === "PAN_REQUIRED" &&
payout.partnerPhoneNorm !== null;
onNotice({
tone: "error",
message: getErrorMessage(err),
action: panRequired ? (
<Link
to="/admin/rrm/partners"
search={{ search: payout.partnerPhoneNorm }}
className="font-medium underline"
data-testid="rrm-payouts-pan-link"
>
Record {payout.partnerName ? `${payout.partnerName}'s` : "their"}{" "}
PAN on the partners screen
</Link>
) : undefined,
});
}
}
async function handleFail() {
const trimmed = failureReason.trim();
Iif (!trimmed || busy) return;
try {
await fail.mutateAsync({ id: payout.id, failureReason: trimmed });
setOpen(null);
setFailureReason("");
onNotice({
tone: "success",
message:
"Marked as failed. The earnings are payable again, so the partner can request them.",
});
} catch (err) {
onNotice({ tone: "error", message: getErrorMessage(err) });
}
}
if (open === "settle") {
return (
<div
className="flex flex-col gap-2"
data-testid="rrm-payouts-settle-form"
>
<label
htmlFor={`ref-${payout.id}`}
className="text-xs font-medium text-foreground-muted"
>
UPI transaction reference
</label>
<Input
id={`ref-${payout.id}`}
data-testid="rrm-payouts-reference-input"
value={reference}
autoFocus
placeholder="e.g. 431203847722"
onChange={(e) => setReference(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void handleSettle();
Iif (e.key === "Escape") setOpen(null);
}}
/>
<div className="flex gap-2">
<Button
size="sm"
data-testid="rrm-payouts-settle-confirm"
// Disabled while in flight, so a second click cannot send a
// second settle for money that has already been recorded.
disabled={busy || reference.trim().length === 0}
onClick={() => void handleSettle()}
>
{settle.isPending ? "Recording…" : "Record payment"}
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => setOpen(null)}
>
Cancel
</Button>
</div>
</div>
);
}
if (open === "fail") {
return (
<div className="flex flex-col gap-2" data-testid="rrm-payouts-fail-form">
<label
htmlFor={`fail-${payout.id}`}
className="text-xs font-medium text-foreground-muted"
>
What went wrong?
</label>
<Input
id={`fail-${payout.id}`}
data-testid="rrm-payouts-fail-input"
value={failureReason}
autoFocus
placeholder="e.g. UPI id does not exist"
onChange={(e) => setFailureReason(e.target.value)}
onKeyDown={(e) => {
Eif (e.key === "Enter") void handleFail();
Iif (e.key === "Escape") setOpen(null);
}}
/>
<div className="flex gap-2">
<Button
size="sm"
variant="destructive"
data-testid="rrm-payouts-fail-confirm"
disabled={busy || failureReason.trim().length === 0}
onClick={() => void handleFail()}
>
{fail.isPending ? "Saving…" : "Mark failed"}
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => setOpen(null)}
>
Cancel
</Button>
</div>
</div>
);
}
return (
<div className="flex gap-2">
<Button
size="sm"
data-testid="rrm-payouts-settle"
disabled={busy}
onClick={() => setOpen("settle")}
>
I have paid this
</Button>
<Button
size="sm"
variant="ghost"
data-testid="rrm-payouts-fail"
disabled={busy}
onClick={() => setOpen("fail")}
>
It bounced
</Button>
</div>
);
}
function PayoutRow({
payout,
onNotice,
}: {
payout: AdminPayoutRow;
onNotice: (notice: Notice) => void;
}) {
return (
<tr data-testid="rrm-payouts-row" data-payout-id={payout.id}>
<td className="px-4 py-3 whitespace-nowrap text-sm text-foreground-muted">
<span title={formatDateTime(payout.dateCreated)}>
{formatRelative(payout.dateCreated)}
</span>
</td>
<td className="px-4 py-3">
<PartnerCell payout={payout} />
</td>
<td className="px-4 py-3">
{/* Large, and never editable here. With no batch total to
reconcile against, this figure is the only thing standing
between a typo and the wrong amount leaving the bank. */}
<p
data-testid="rrm-payouts-amount"
className="text-lg font-semibold tabular-nums text-foreground-default"
>
₹{formatPaise(payout.amountPaise)}
</p>
</td>
<td className="px-4 py-3">
{payout.upiId ? (
<span
data-testid="rrm-payouts-upi"
className="font-mono text-sm text-foreground-default"
>
{payout.upiId}
</span>
) : (
<span className="text-sm text-foreground-muted">No UPI id</span>
)}
</td>
<td className="px-4 py-3">
<span data-testid="rrm-payouts-state">
<StatusBadge
status={STATE_LABEL[payout.state]}
variant={STATE_TONE[payout.state]}
/>
</span>
</td>
<td className="px-4 py-3">
<PayoutActions payout={payout} onNotice={onNotice} />
</td>
</tr>
);
}
function SkeletonRows() {
return (
<>
{SKELETON_KEYS.map((key) => (
<tr key={key} data-testid="rrm-payouts-skeleton-row">
<td colSpan={COLUMN_COUNT} className="px-4 py-3">
<div className="h-8 bg-background-muted rounded animate-pulse" />
</td>
</tr>
))}
</>
);
}
export function PayoutsPage() {
const [tab, setTab] = useState<RrmPayoutState | "all">("pending");
const [notice, setNotice] = useState<Notice | null>(null);
const { data, isLoading, error } = useRrmPayouts(
tab === "all" ? undefined : tab,
);
const payouts = data?.data ?? [];
const owedPaise = payouts
.filter((p) => p.state === "pending")
.reduce((sum, p) => sum + p.amountPaise, 0);
return (
<div className="space-y-6" data-testid="rrm-payouts-page">
<PageHeader
title="Payouts"
description="Partners who have asked to be paid. Send the money by UPI, then record the reference here."
/>
{notice && (
<div
data-testid="rrm-payouts-notice"
data-tone={notice.tone}
className={
notice.tone === "success"
? "rounded-md border border-success/30 bg-success/10 px-4 py-3 text-sm text-success"
: "rounded-md border border-error/30 bg-error/10 px-4 py-3 text-sm text-error"
}
>
{notice.message}
{notice.action && <span className="ml-2">{notice.action}</span>}
</div>
)}
<Card>
<CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<CardTitle className="text-lg" data-testid="rrm-payouts-owed">
{isLoading
? "Loading payouts…"
: tab === "pending"
? `₹${formatPaise(owedPaise)} owed across ${payouts.length} ${payouts.length === 1 ? "request" : "requests"}`
: `${payouts.length} ${payouts.length === 1 ? "payout" : "payouts"}`}
</CardTitle>
<div className="flex gap-1" data-testid="rrm-payouts-tabs">
{TABS.map((option) => (
<Button
key={option.value}
size="sm"
variant={tab === option.value ? "default" : "ghost"}
data-testid={`rrm-payouts-tab-${option.value}`}
aria-pressed={tab === option.value}
onClick={() => {
setTab(option.value);
// A success line about a payout that is no longer on
// screen reads as being about one that is.
setNotice(null);
}}
>
{option.label}
</Button>
))}
</div>
</CardHeader>
<CardContent className="p-0">
{error ? (
<div
data-testid="rrm-payouts-error"
className="flex items-start gap-2 p-6 text-sm text-error"
>
<AlertTriangle className="h-4 w-4 shrink-0" aria-hidden="true" />
<span>
Could not load payouts. Refresh the page to try again — nothing
has been paid or changed.
</span>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm" data-testid="rrm-payouts-table">
<thead className="bg-background-subtle border-b border-border-default">
<tr>
<th className={HEADER_CELL}>Requested</th>
<th className={HEADER_CELL}>Partner</th>
<th className={HEADER_CELL}>Amount</th>
<th className={HEADER_CELL}>Send to</th>
<th className={HEADER_CELL}>Status</th>
<th className={HEADER_CELL}>
{tab === "pending" ? "Action" : "Reference"}
</th>
</tr>
</thead>
<tbody className="divide-y divide-border-default">
{isLoading ? (
<SkeletonRows />
) : payouts.length === 0 ? (
<tr>
<td colSpan={COLUMN_COUNT} className="px-4 py-12">
<EmptyState
icon={tab === "pending" ? Banknote : IndianRupee}
title={
tab === "pending"
? "Nobody is waiting to be paid"
: "Nothing here yet"
}
description={
tab === "pending"
? "Partners appear here when they request a payout — which they can only do once their earnings clear the hold and reach the threshold."
: "No payouts in this state."
}
/>
</td>
</tr>
) : (
payouts.map((payout) => (
<PayoutRow
key={payout.id}
payout={payout}
onNotice={setNotice}
/>
))
)}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
);
}
export default PayoutsPage;
|