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 | 2x 2x 30x 9x 12x 2x 2x 2x 2x 33x 33x 6x 6x 6x 47x 47x 1x 61x 56x 34x 32x 2x 16x 16x 16x 16x 15x 15x 9x 12x 12x 5x 3x 2x 1x 1x 7x 16x 9x 2x 6x 6x 6x 6x 6x 5x 3x 2x 2x 1x 1x 5x 2x 6x 6x 6x 6x 6x 5x 4x 3x 1x 2x 1x 1x 1x 5x 2x 5x 5x 5x 5x 4x 2x 1x 2x 19x 19x 19x 19x 18x 19x 4x 14x 14x 14x 12x 10x 9x 9x 7x 9x 10x 2x 5x 5x 5x 5x 3x 1x 4x 9x 9x 9x 9x 8x 7x 7x 1x 1x 9x 9x 9x 9x 12x 12x 9x 9x 8x 8x 1x 12x 12x 12x 12x 2x 14x 14x 14x 14x 12x 12x 12x 12x 2x 5x 3x 10x 10x | /**
* Operator controls for the partner earnings ledger and payouts (F-21).
*
* Mounted under `/api/admin/rrm`, where the parent admin router has already
* run `contextMiddleware` and `requirePlatformAdmin`. Nothing here re-applies
* a guard — a second one would quietly diverge from the parent's the first
* time the parent changes.
*
* These five endpoints are the only way money changes state by hand:
*
* POST /referrals/:referralId/outcome credit a referral
* POST /earnings/:earningId/reverse withdraw a credit, with a reason
* POST /earnings/:earningId/clawback offset one already PAID (FR-M-6)
* GET /payouts?state=pending the settle queue
* POST /payouts/:payoutId/settle record a UPI transfer
* POST /payouts/:payoutId/fail the transfer bounced
*
* Two rules have teeth here rather than in the UI, because the UI is not what
* a dispute is argued from: settling REQUIRES a traceable reference, and
* reversing REQUIRES a reason from the enum. Both are rejected server-side.
*
* Every mutation stamps the acting operator's id. `user` is nullable in the
* Env type, so each one fails closed rather than writing a null actor onto a
* money row.
*/
import { desc, eq } from "drizzle-orm";
import type { Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import { PROGRAM_CONFIG_KEYS } from "../../../dal/partners/config.dal";
import {
IllegalTransitionError,
ReferralsDal,
} from "../../../dal/partners/referrals.dal";
import { PayoutNotFoundError, RrmEarningsDal } from "../../../dal/rrm";
import {
rrmEarnings as EARNINGS,
partners as PARTNERS,
rrmPayouts as PAYOUTS,
} from "../../../db/schema";
import {
RRM_CREDITABLE_EARNING_KINDS,
RRM_EARNING_REVERSAL_REASONS,
RRM_PAYOUT_STATES,
} from "../../../db/schema/enums";
import type { RrmEarning, RrmPayout } from "../../../db/schema/rrm";
import {
AppError,
ConflictError,
NotFoundError,
UnauthorizedError,
ValidationError,
} from "../../../lib/errors";
import { notifyPartnerReferralUpdate } from "../../../lib/partners/notify";
import { tdsGate } from "../../../lib/partners/tds";
import { twoPersonBreach } from "../../../lib/partners/two-person";
import { handleError, success } from "../../../lib/response";
import { fyLabel, fyStart } from "../../../lib/rrm/time";
import type { Services } from "../../../services";
import { recordOutcome } from "../../../services/rrm/earnings.service";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
const earnings = new Hono<Env>();
/**
* The settle queue is a work list, not an archive. A hundred pending payouts
* is already a backlog nobody is clearing today; the cap keeps one operator's
* page load from scanning a table that only grows.
*/
const MAX_PAYOUT_ROWS = 200;
// ─────────────────────────────────────────────────────────────────────────────
// Serialisation
// ─────────────────────────────────────────────────────────────────────────────
/** Drizzle hands back `Date` (epoch seconds in D1); the contract is ISO. */
function iso(value: Date | null): string | null {
return value === null ? null : value.toISOString();
}
function serializeEarning(row: RrmEarning) {
return {
id: row.id,
partnerId: row.partnerId,
referralId: row.referralId,
kind: row.kind,
// Paise, integer, all the way to the wire. Rupees are a rendering
// decision and are made once, in the client.
amountPaise: row.amountPaise,
state: row.state,
holdUntil: row.holdUntil.toISOString(),
releasedAt: iso(row.releasedAt),
reversedAt: iso(row.reversedAt),
reversalReason: row.reversalReason,
payoutId: row.payoutId,
// Both sides of the row's story. `actorId`/`notes` are the CREDIT's —
// they used to be overwritten by a reversal, and carrying only them is
// what made "who decided this partner had earned it" unanswerable.
actorId: row.actorId,
notes: row.notes,
reversedByActorId: row.reversedByActorId,
// Operator free-text. Admin-only on purpose: the partner is owed the
// REASON for a withdrawal (`reversalReason`, which they do get), not an
// internal note about how it was discovered.
reversalNotes: row.reversalNotes,
/** Set only on a clawback row: the paid earning it offsets. */
reversedOf: row.reversedOf,
dateCreated: row.dateCreated.toISOString(),
};
}
type PayoutPartner = {
name: string | null;
firmName: string | null;
phoneNorm: string | null;
};
function serializePayout(row: RrmPayout, partner: PayoutPartner) {
return {
id: row.id,
partnerId: row.partnerId,
// Who is being paid, and on what number — an operator about to move
// real money should not have to open a second screen to check.
partnerName: partner.name,
partnerFirmName: partner.firmName,
partnerPhoneNorm: partner.phoneNorm,
amountPaise: row.amountPaise,
state: row.state,
upiId: row.upiId,
reference: row.reference,
failureReason: row.failureReason,
actorId: row.actorId,
dateCreated: row.dateCreated.toISOString(),
settledAt: iso(row.settledAt),
};
}
// ─────────────────────────────────────────────────────────────────────────────
// Validation
// ─────────────────────────────────────────────────────────────────────────────
const outcomeSchema = z.object({
// Creditable kinds only. `clawback` is a kind in the column but not an
// outcome an operator can credit — it is only ever written by the clawback
// endpoint, as a negative row against an already-paid earning.
kind: z.enum(RRM_CREDITABLE_EARNING_KINDS),
notes: z.string().trim().max(1000).optional(),
});
/**
* `reason` is the enum, not free text. SQLite does not enforce a text enum, so
* an unconstrained string here writes a value into `reversal_reason` that no
* report and no partner-facing explanation has ever heard of — on the one
* column whose whole job is explaining a withdrawal months later.
*/
const reverseSchema = z.object({
reason: z.enum(RRM_EARNING_REVERSAL_REASONS),
notes: z.string().trim().max(1000).optional(),
});
const failSchema = z.object({
failureReason: z.string().trim().min(1).max(500),
});
const listQuerySchema = z.object({
state: z.enum(RRM_PAYOUT_STATES).optional(),
});
/** `handleError` has no ZodError branch, so validation failures are named here. */
function parseOrThrow<T>(schema: z.ZodType<T>, value: unknown): T {
const result = schema.safeParse(value);
if (result.success) return result.data;
const detail = result.error.issues
.map((issue) => `${issue.path.join(".") || "body"}: ${issue.message}`)
.join("; ");
throw new ValidationError(detail);
}
async function readJson(c: Context<Env>): Promise<unknown> {
try {
return await c.req.json();
} catch {
throw new ValidationError("Request body must be valid JSON");
}
}
/**
* Every write in this file lands on a money row, and "who did this" is the
* first question asked about any of them. The parent router already
* guarantees a session; this is what makes a null one fail closed instead of
* stamping `null` into `actor_id`.
*/
function requireActorId(user: { id: string } | null): string {
if (!user) throw new UnauthorizedError("Operator session required");
return user.id;
}
/**
* DAL and service errors are transport-agnostic on purpose. This is the single
* place they are given HTTP meaning.
*/
function toHttpError(err: unknown): unknown {
if (err instanceof PayoutNotFoundError) return new NotFoundError("Payout");
return err;
}
// ─────────────────────────────────────────────────────────────────────────────
// Routes
// ─────────────────────────────────────────────────────────────────────────────
// POST /api/admin/rrm/referrals/:referralId/outcome
//
// The credit itself — amount, hold window, and the partner the referral
// belongs to — is the earnings service's job. This route is the operator
// boundary: authenticate, validate the kind, attribute the action.
earnings.post("/referrals/:referralId/outcome", async (c) => {
try {
const dal = c.get("dal");
const actorId = requireActorId(c.get("user"));
const body = parseOrThrow(outcomeSchema, await readJson(c));
const referralId = c.req.param("referralId");
// A `converted` outcome must MOVE the referral, not just credit it.
//
// Without this the row's status stayed wherever it was — so
// `referrals.status` never once reached `converted`, and any funnel or
// count keyed on it answered zero forever while the money went out
// normally. The event and the earning were both written; only the state
// was not, which is exactly the kind of gap nothing fails loudly on.
//
// Transition FIRST, then credit — the same order as verify, because
// `recordOutcome` refuses a referral that is not in an earning state.
if (body.kind === "converted") {
await transitionToConverted(c, referralId);
}
const result = await recordOutcome(
{ db: dal.db },
{ referralId, kind: body.kind, actorId, notes: body.notes ?? null },
);
// The service refuses by returning, not by throwing — an operator
// double-clicking "mark validated" is the common case, and it has to
// read as "already credited" rather than a 500.
if (!result.ok) {
if (result.reason === "already_credited") {
throw new ConflictError(
`Already credited — referral ${referralId} has a ${body.kind} earning`,
);
}
if (result.reason === "not_earnable") {
// A duplicate, rejected, expired or opted-out referral. Refusing
// here is the point: it never earns, so it must not be credited
// and then reversed off a partner's dashboard.
throw new ConflictError(
`Referral ${referralId} is not in an earning state`,
);
}
throw new NotFoundError("Referral", referralId);
}
// Announced because the credit LANDED — `result.ok` false has already
// thrown above, so reaching here means money moved and the partner is
// owed the news.
//
// Both kinds, not just `converted`. `validated` normally arrives through
// `/:id/verify`, which announces it itself — but that is a convention,
// not a constraint: this endpoint accepts `validated` directly, and a
// caller using it would otherwise credit ₹100 in silence. It cannot
// double-send, because a referral verified first answers
// `already_credited` here and throws.
c.executionCtx.waitUntil(
notifyPartnerReferralUpdate(
{ db: dal.db, env: c.env, dal },
{
referral: referralId,
state: body.kind === "converted" ? "converted" : "verified",
},
),
);
return success(c, serializeEarning(result.earning));
} catch (err) {
return handleError(c, toHttpError(err));
}
});
// POST /api/admin/rrm/earnings/:earningId/reverse
earnings.post("/earnings/:earningId/reverse", async (c) => {
try {
const dal = c.get("dal");
const actorId = requireActorId(c.get("user"));
const earningId = c.req.param("earningId");
const body = parseOrThrow(reverseSchema, await readJson(c));
const reversed = await new RrmEarningsDal(dal.db).reverse({
earningId,
reason: body.reason,
actorId,
notes: body.notes ?? null,
});
// `reverse` guards on state, so `null` means one of two very different
// things: no such earning, or one that is `paid`/already `reversed`.
// Reporting both as 404 would tell an operator their row vanished when
// it is sitting there settled. One extra read buys the true answer.
if (!reversed) {
const rows = await dal.db
.select({ state: EARNINGS.state })
.from(EARNINGS)
.where(eq(EARNINGS.id, earningId))
.limit(1);
if (!rows[0]) throw new NotFoundError("Earning", earningId);
throw new ConflictError(
`Cannot reverse an earning in state '${rows[0].state}'`,
);
}
return success(c, serializeEarning(reversed));
} catch (err) {
return handleError(c, toHttpError(err));
}
});
// POST /api/admin/rrm/earnings/:earningId/clawback
//
// The dispute that arrives AFTER the money was sent (FR-M-6). `reverse` refuses
// a `paid` earning deliberately — you cannot un-pay a UPI transfer — so this
// writes a negative row that offsets the partner's next request instead. Never
// a demand for money back, and never an edit to the settled row, which records
// something that actually happened.
earnings.post("/earnings/:earningId/clawback", async (c) => {
try {
const dal = c.get("dal");
const actorId = requireActorId(c.get("user"));
const earningId = c.req.param("earningId");
// Same shape as a reversal: the reason is the enum, never free text, on
// the one column whose job is explaining this to a partner months later.
const body = parseOrThrow(reverseSchema, await readJson(c));
const result = await new RrmEarningsDal(dal.db).clawback({
earningId,
reason: body.reason,
actorId,
notes: body.notes ?? null,
});
if (!result.ok) {
if (result.reason === "not_found") {
throw new NotFoundError("Earning", earningId);
}
if (result.reason === "not_paid") {
// The distinction matters to the operator: still-live money is
// reversed, not clawed back, and the reverse endpoint is right
// there. Telling them "not found" would send them looking for a
// row that is on the screen in front of them.
throw new ConflictError(
`Earning ${earningId} has not been paid — reverse it instead`,
);
}
throw new ConflictError(
`Earning ${earningId} has already been clawed back`,
);
}
return success(c, serializeEarning(result.earning));
} catch (err) {
return handleError(c, toHttpError(err));
}
});
// GET /api/admin/rrm/payouts?state=pending
//
// Read directly rather than through `RrmEarningsDal.listPayouts`, which is
// scoped to one partner: this is the cross-partner settle queue. Left join, so
// a payout whose partner row was hard-deleted still appears — a money row
// silently missing from the operator's list is the worse failure.
earnings.get("/payouts", async (c) => {
try {
const dal = c.get("dal");
const { state } = parseOrThrow(listQuerySchema, cleanQuery(c.req.query()));
const rows = await dal.db
.select({
payout: PAYOUTS,
name: PARTNERS.name,
firmName: PARTNERS.firmName,
phoneNorm: PARTNERS.phoneNorm,
})
.from(PAYOUTS)
.leftJoin(PARTNERS, eq(PARTNERS.id, PAYOUTS.partnerId))
.where(state ? eq(PAYOUTS.state, state) : undefined)
.orderBy(desc(PAYOUTS.dateCreated))
.limit(MAX_PAYOUT_ROWS);
return success(
c,
rows.map((row) =>
serializePayout(row.payout, {
name: row.name,
firmName: row.firmName,
phoneNorm: row.phoneNorm,
}),
),
);
} catch (err) {
return handleError(c, toHttpError(err));
}
});
// POST /api/admin/rrm/payouts/:payoutId/settle
earnings.post("/payouts/:payoutId/settle", async (c) => {
try {
const dal = c.get("dal");
const actorId = requireActorId(c.get("user"));
const body = (await readJson(c)) as { reference?: unknown } | null;
// Hand-checked rather than run through zod, because the status code is
// the point: a settled payout nobody can trace is a dispute with no
// evidence, so a missing, empty, whitespace-only or non-string
// reference is 422 — the request was understood and refused, not
// malformed.
const reference =
typeof body?.reference === "string" ? body.reference.trim() : "";
if (!reference) {
throw new AppError(
422,
"REFERENCE_REQUIRED",
"A UPI transaction reference is required to settle a payout",
);
}
const payoutId = c.req.param("payoutId");
const earningsDal = new RrmEarningsDal(dal.db);
// FR-M-7, on the side where the money actually moves. The partner's own
// request carries the same check, but a request made while under the
// threshold can still be sitting here after the threshold is lowered or
// after another payout has been settled — and this is the last point at
// which refusing is cheaper than recovering.
await requireTdsClearance(c, earningsDal, payoutId);
// FR-A-9. After the TDS gate, because a payout that cannot go out at all
// is a more useful thing to be told than who is allowed to send it.
await requireSecondPairOfEyes(c, actorId, payoutId);
// The trimmed value is what is stored — trailing whitespace pasted from
// a banking app must not become part of the reference an operator later
// searches for.
const payout = await earningsDal.settlePayout({
payoutId,
reference,
actorId,
});
// FR-I-1. AFTER the settle, and never in the same failure path: the
// money is recorded either way, and a timeline that lags by one event is
// recoverable while a settle that did not happen is not.
const paidReferralIds = await recordPaidOnTimelines(c, payoutId, reference);
// "…and when you are paid" — the last of the four promises the partner
// app makes. One message per referral, matching the timeline's own
// granularity: "so what happened to the ₹100 for Priya?" is asked on a
// referral's page, and a payout-level message would not answer it.
//
// Outside `recordPaidOnTimelines`'s silent try/catch on purpose: a throw
// from `c.executionCtx` in there would abandon the remaining
// `payout.paid` events with nothing logged.
//
// ponytail: a payout covering ten referrals sends ten templates. Batch
// into one summary template if partners say it is noise.
for (const referralId of paidReferralIds) {
c.executionCtx.waitUntil(
notifyPartnerReferralUpdate(
{ db: dal.db, env: c.env, dal },
{
partner: payout.partnerId,
referral: referralId,
state: "payout_paid",
},
),
);
}
return success(c, serializePayout(payout, await partnerFor(dal, payout)));
} catch (err) {
return handleError(c, toHttpError(err));
}
});
// POST /api/admin/rrm/payouts/:payoutId/fail
earnings.post("/payouts/:payoutId/fail", async (c) => {
try {
const dal = c.get("dal");
const actorId = requireActorId(c.get("user"));
const body = parseOrThrow(failSchema, await readJson(c));
// The DAL detaches the earnings on the way out, so they are payable
// again rather than stranded against a dead payout.
const payout = await new RrmEarningsDal(dal.db).failPayout({
payoutId: c.req.param("payoutId"),
failureReason: body.failureReason,
actorId,
});
return success(c, serializePayout(payout, await partnerFor(dal, payout)));
} catch (err) {
return handleError(c, toHttpError(err));
}
});
/**
* Move a referral to `converted` before crediting the conversion.
*
* The state machine only allows `quoted -> converted`, deliberately: a
* conversion we never quoted for is a gap in the record, not a shortcut. So an
* operator recording this against a referral that has not reached `quoted` is
* told which state it is in rather than having the transition forced — the
* money is the same either way, and the history is the thing worth protecting.
*
* An ALREADY-converted referral is not an error. That is what a double-click
* looks like, and `recordOutcome` below answers `already_credited` for it.
*/
async function transitionToConverted(
c: Context<Env>,
referralId: string,
): Promise<void> {
const dal = c.get("dal");
const actorId = requireActorId(c.get("user"));
const referral = await dal.referrals.findById(referralId);
if (!referral) throw new NotFoundError("Referral", referralId);
if (referral.status === "converted") return;
try {
await dal.referrals.transition({
referral,
to: "converted",
actorType: "ops",
actorId,
// The partner-facing line comes from `recordOutcome`, which carries
// the ₹1,000. Same reasoning as `referral.verified.transition`: two
// events here would say it twice, once without the money.
eventType: "referral.converted.transition",
});
} catch (error) {
Iif (!(error instanceof IllegalTransitionError)) throw error;
throw new ConflictError(
`Cannot convert a referral that is '${referral.status}' — mark it quoted first`,
);
}
}
/**
* Put "paid" on the timeline of every referral this payout covered (FR-I-1).
*
* One event per referral rather than one per payout, because the partner's
* timeline is per referral — that is the screen where "so what happened to the
* ₹100 for Priya?" gets asked, and a payout-level row would not appear on it.
*
* Swallows its own failure. The transfer has already been made and recorded;
* failing the request now would tell the operator the settle did not happen,
* and the recovery from THAT is far worse than a missing timeline line.
*
* Returns the referrals it wrote a line for, so the caller can tell the same
* partners on WhatsApp without reading the ledger a second time. An empty array
* on failure — nothing was recorded, so nothing is announced.
*/
async function recordPaidOnTimelines(
c: Context<Env>,
payoutId: string,
reference: string,
): Promise<string[]> {
try {
const dal = c.get("dal");
const rows = await dal.db
.select({ referralId: EARNINGS.referralId })
.from(EARNINGS)
.where(eq(EARNINGS.payoutId, payoutId));
const referralIds = [
...new Set(
rows
.map((r) => r.referralId)
// A manual adjustment has no referral behind it, and a
// clawback's negative row points at one already paid.
.filter((id): id is string => id !== null),
),
];
const referrals = new ReferralsDal(dal.db);
for (const referralId of referralIds) {
await referrals.addEvent({
referralId,
type: "payout.paid",
actorType: "ops",
actorId: c.get("user")?.id ?? null,
// The reference, so a partner asking "when did this arrive" has
// the same trace the operator does. No amount — the earning rows
// already carry that, and duplicating it invites the two to drift.
payload: { payoutId, reference },
});
}
return referralIds;
} catch {
// Deliberately silent. See the doc comment.
return [];
}
}
/**
* FR-A-9: refuse a settle by the same account that credited the money.
*
* The identity comes from `rrm_earnings.actor_id`, which `recordOutcome`
* already stamps with the operator who verified the referral — so this needs
* no new column and no new role. See `lib/partners/two-person.ts` for why the
* threshold is per accrual rather than per payout.
*
* 409, not 403: nothing is wrong with the operator's permissions and nothing
* about the request is malformed. The payout is in a state THIS person cannot
* move it out of, and anybody else on the team can.
*/
async function requireSecondPairOfEyes(
c: Context<Env>,
settlingActorId: string,
payoutId: string,
): Promise<void> {
const dal = c.get("dal");
const [earnings, thresholdPaise] = await Promise.all([
dal.db
.select({
id: EARNINGS.id,
amountPaise: EARNINGS.amountPaise,
actorId: EARNINGS.actorId,
})
.from(EARNINGS)
.where(eq(EARNINGS.payoutId, payoutId)),
dal.programConfig.getNumber(PROGRAM_CONFIG_KEYS.twoPersonThresholdPaise),
]);
const breach = twoPersonBreach({
earnings,
settlingActorId,
thresholdPaise,
});
if (!breach) return;
throw new AppError(
409,
"SECOND_APPROVER_REQUIRED",
`You verified ${breach.earningIds.length === 1 ? "the earning" : `${breach.earningIds.length} earnings`} in this payout, including one of ₹${breach.largestPaise / 100}. Someone else has to settle it — anything above ₹${breach.thresholdPaise / 100} needs a second pair of eyes.`,
);
}
/**
* Refuse to settle a payment that would take a partner past the TDS threshold
* for the financial year with no PAN on file (FR-M-7).
*
* 422 rather than 409: the request was understood and is refused on a rule, and
* the body carries the numbers so the operator can tell the partner exactly what
* is needed rather than "the system says no".
*/
async function requireTdsClearance(
c: Context<Env>,
earningsDal: RrmEarningsDal,
payoutId: string,
): Promise<void> {
const dal = c.get("dal");
const rows = await dal.db
.select({
partnerId: PAYOUTS.partnerId,
amountPaise: PAYOUTS.amountPaise,
panLast4: PARTNERS.panLast4,
})
.from(PAYOUTS)
.leftJoin(PARTNERS, eq(PARTNERS.id, PAYOUTS.partnerId))
.where(eq(PAYOUTS.id, payoutId))
.limit(1);
// No payout, or one whose partner row is gone. Both are `settlePayout`'s
// to report — it owns the not-found and not-pending answers, and second-
// guessing them here would give the same condition two different errors.
const row = rows[0];
if (!row) return;
const now = new Date();
const [thresholdPaise, fyPaidPaise] = await Promise.all([
dal.programConfig.getNumber(PROGRAM_CONFIG_KEYS.tdsThresholdPaise),
earningsDal.paidSince(row.partnerId, fyStart(now)),
]);
const gate = tdsGate({
fyPaidPaise,
requestPaise: row.amountPaise,
thresholdPaise,
hasPan: Boolean(row.panLast4),
});
if (!gate.blocked) return;
throw new AppError(
422,
"PAN_REQUIRED",
`Cannot settle: this takes ${row.partnerId} to ₹${gate.wouldTotalPaise / 100} paid in FY ${fyLabel(now)}, past the ₹${gate.thresholdPaise / 100} TDS threshold, with no PAN on file`,
);
}
/** Query params arrive as strings; an empty one means "unset", not "invalid". */
function cleanQuery(raw: Record<string, string>): Record<string, string> {
return Object.fromEntries(
Object.entries(raw).filter(([, value]) => value !== ""),
);
}
/**
* The partner fields the list already carries, for the single-payout responses
* — so the row the UI swaps in after settling has the same shape as the one it
* replaces. A hard-deleted partner yields nulls rather than an error.
*/
async function partnerFor(dal: Dal, payout: RrmPayout): Promise<PayoutPartner> {
const rows = await dal.db
.select({
name: PARTNERS.name,
firmName: PARTNERS.firmName,
phoneNorm: PARTNERS.phoneNorm,
})
.from(PARTNERS)
.where(eq(PARTNERS.id, payout.partnerId))
.limit(1);
return rows[0] ?? { name: null, firmName: null, phoneNorm: null };
}
export default earnings;
|