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 | 23x 23x 5x 5x 1x 1x 6x 6x 4x 4x 189x 53x 62x 62x 62x 57x 5x 5x 113x 34x 28x 28x 28x 232x 30x 30x 30x 5x 5x 5x 7x 7x 7x 7x 6x 5x 5x 4x 1x 1x 13x 30x 30x 18x 44x 44x 29x 29x 29x 28x 31x 28x 6x 22x 22x 22x 22x 22x 24x 22x 22x 22x 22x 22x 22x 22x 9x 9x 8x 7x 4x 3x 2x | import { and, desc, eq, gte, inArray, isNull, lte, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../../db/schema";
import type {
RRM_CREDITABLE_EARNING_KINDS,
RRM_EARNING_KINDS,
RRM_EARNING_REVERSAL_REASONS,
} from "../../db/schema/enums";
import type { RrmEarning, RrmPayout } from "../../db/schema/rrm";
import { generateId } from "../../lib/ids";
import { holdUntilFrom } from "../../lib/rrm/earnings";
const EARNINGS = schema.rrmEarnings;
const PAYOUTS = schema.rrmPayouts;
export type EarningKind = (typeof RRM_EARNING_KINDS)[number];
/**
* The kinds an operator can credit. `clawback` is deliberately absent — it is
* written only by `clawback()`, never through the outcome endpoint, and it is
* the one kind with no configured price.
*/
export type CreditableEarningKind =
(typeof RRM_CREDITABLE_EARNING_KINDS)[number];
export type ReversalReason = (typeof RRM_EARNING_REVERSAL_REASONS)[number];
/** A referral already earned this kind. The unique index is the real guard. */
export class DuplicateEarningError extends Error {
constructor(referralId: string, kind: CreditableEarningKind) {
super(`Referral ${referralId} already has a ${kind} earning`);
this.name = "DuplicateEarningError";
}
}
/** A partner may hold only one unsettled payout request at a time. */
export class PayoutAlreadyPendingError extends Error {
constructor(payoutId: string) {
super(`Payout ${payoutId} is already pending for this partner`);
this.name = "PayoutAlreadyPendingError";
}
}
export class BelowThresholdError extends Error {
constructor(availablePaise: number, thresholdPaise: number) {
super(
`Available ${availablePaise} is below the threshold ${thresholdPaise}`,
);
this.name = "BelowThresholdError";
}
}
export class PayoutNotFoundError extends Error {
constructor(id: string) {
super(`Payout ${id} not found`);
this.name = "PayoutNotFoundError";
}
}
export class RrmEarningsDal {
constructor(private db: DrizzleD1Database<typeof schema>) {}
/** Every earning for one partner, newest first. Drives the balance. */
async listForPartner(partnerId: string): Promise<RrmEarning[]> {
return this.db
.select()
.from(EARNINGS)
.where(eq(EARNINGS.partnerId, partnerId))
.orderBy(desc(EARNINGS.dateCreated));
}
/**
* Credit a referral.
*
* The unique index on (referral_id, kind) is what actually prevents a
* double credit — an operator double-clicking "mark validated" hits it at
* the database, not at a check-then-write race in application code. This
* translates that constraint violation into a named error so callers can
* report "already credited" rather than a 500.
*/
async accrue(input: {
partnerId: string;
referralId: string;
kind: CreditableEarningKind;
amountPaise: number;
holdDays: number;
actorId?: string | null;
now?: Date;
notes?: string | null;
}): Promise<RrmEarning> {
const now = input.now ?? new Date();
try {
const rows = await this.db
.insert(EARNINGS)
.values({
id: `ern_${generateId()}`,
partnerId: input.partnerId,
referralId: input.referralId,
kind: input.kind,
amountPaise: input.amountPaise,
state: "accrued",
holdUntil: holdUntilFrom(now, input.holdDays),
actorId: input.actorId ?? null,
notes: input.notes ?? null,
dateCreated: now,
})
.returning();
return rows[0];
} catch (err) {
Eif (/UNIQUE constraint failed/i.test(String(err))) {
throw new DuplicateEarningError(input.referralId, input.kind);
}
throw err;
}
}
/**
* Move every `accrued` row whose hold has expired to `released`.
*
* Set-based rather than read-then-write per row: this runs on a cron over a
* table that only grows, and a loop would issue one statement per earning.
* The `state = 'accrued'` predicate is also what makes it safe to re-run —
* a reversed row can never be picked up, whatever its hold date says.
*
* @returns the number of rows released.
*/
async releaseDue(now = new Date()): Promise<number> {
const due = await this.db
.select({ id: EARNINGS.id })
.from(EARNINGS)
.where(and(eq(EARNINGS.state, "accrued"), lte(EARNINGS.holdUntil, now)));
if (due.length === 0) return 0;
// D1 caps bound parameters at 100 per statement; the due set grows with
// send volume, so chunk it the way the scheduler's cohort query does.
const CHUNK = 90;
let released = 0;
for (let i = 0; i < due.length; i += CHUNK) {
const ids = due.slice(i, i + CHUNK).map((r) => r.id);
await this.db
.update(EARNINGS)
.set({ state: "released", releasedAt: now })
.where(and(inArray(EARNINGS.id, ids), eq(EARNINGS.state, "accrued")));
released += ids.length;
}
return released;
}
/**
* Withdraw an earning, with a reason.
*
* Never a delete. A partner who was told they earned something and later
* sees it gone is owed an explanation, and only a surviving row can give
* one. Guarded on the current state so a `paid` earning cannot be reversed
* out from under a settled payout — that is a refund, not a reversal, and
* it is not a thing this system does.
*/
async reverse(input: {
earningId: string;
reason: ReversalReason;
actorId: string;
notes?: string | null;
now?: Date;
}): Promise<RrmEarning | null> {
const now = input.now ?? new Date();
const rows = await this.db
.update(EARNINGS)
.set({
state: "reversed",
reversedAt: now,
reversalReason: input.reason,
// Both of these are the REVERSAL's fields. `actorId` and
// `notes` belong to the credit and are left alone: this used to
// write the reverser over the crediting operator and the
// reversal note over the accrual note, so the one row whose job
// is explaining both the credit and the withdrawal could only
// ever explain the withdrawal.
reversedByActorId: input.actorId,
reversalNotes: input.notes ?? null,
})
.where(
and(
eq(EARNINGS.id, input.earningId),
inArray(EARNINGS.state, ["accrued", "released"]),
// NOT while it is locked to a pending payout. The payout row
// carries an amount fixed at request time; reversing one of
// its earnings underneath would leave the operator paying a
// total that no longer matches what it covers, with nothing
// recording the difference. Fail the payout first, which
// detaches everything, then reverse.
isNull(EARNINGS.payoutId),
),
)
.returning();
return rows[0] ?? null;
}
/**
* Claw back an earning that was already PAID (FR-M-6).
*
* `reverse()` deliberately refuses a `paid` row — you cannot un-pay money
* that left the bank. So a dispute after settlement is represented the only
* honest way: a NEW negative row that offsets the partner's next request.
* Never a demand for money back, and never an edit to the paid row, which
* records something that genuinely happened.
*
* Shape, and why:
*
* kind `clawback`, not the original's kind. The partial unique index
* on (referral_id, kind) still counts the `paid` original —
* `'paid' != 'reversed'` — so reusing its kind collides. A
* distinct kind sidesteps that AND buys "one live clawback per
* referral" from the same index.
* state `released`. It must reduce the requestable balance now; an
* `accrued` clawback would sit behind a hold while the partner
* withdrew the money it was meant to offset.
* holdUntil `now`. The column is NOT NULL and `isReleasable` only ever
* looks at `accrued` rows, so this touches neither the release
* sweep nor the hold logic.
*/
async clawback(input: {
earningId: string;
reason: ReversalReason;
actorId: string;
notes?: string | null;
now?: Date;
}): Promise<
| { ok: true; earning: RrmEarning; original: RrmEarning }
| { ok: false; reason: "not_found" | "not_paid" | "already_clawed_back" }
> {
const now = input.now ?? new Date();
const originals = await this.db
.select()
.from(EARNINGS)
.where(eq(EARNINGS.id, input.earningId))
.limit(1);
const original = originals[0];
if (!original) return { ok: false, reason: "not_found" };
// Only a settled earning. Anything still live is `reverse()`'s job —
// routing it here would leave the original spendable and add a negative
// row beside it, halving the balance twice.
if (original.state !== "paid") return { ok: false, reason: "not_paid" };
try {
const rows = await this.db
.insert(EARNINGS)
.values({
id: `ern_${generateId()}`,
partnerId: original.partnerId,
referralId: original.referralId,
kind: "clawback",
amountPaise: -original.amountPaise,
state: "released",
holdUntil: now,
releasedAt: now,
reversalReason: input.reason,
reversedOf: original.id,
// This row's own author and explanation. It has no accrual
// behind it, so `notes` is the clawback's reason rather than
// something a reversal would overwrite.
actorId: input.actorId,
notes: input.notes ?? null,
dateCreated: now,
})
.returning();
return { ok: true, earning: rows[0], original };
} catch (err) {
// The unique index doing the work again: one live clawback per
// referral, enforced at the database rather than by a read-then-write
// race two operators can both win.
Eif (/UNIQUE constraint failed/i.test(String(err))) {
return { ok: false, reason: "already_clawed_back" };
}
throw err;
}
}
// ── Payouts ─────────────────────────────────────────────────────────────
/**
* "…and the payout is still pending", for the earnings half of the settle
* and fail batches. The payout UPDATE carries the same guard, so this keeps
* both writes conditional on the one fact, rather than moving earnings for
* a payout that some other call already settled or failed.
*/
private payoutIsPending(payoutId: string) {
return sql`exists (select 1 from ${PAYOUTS} where ${PAYOUTS.id} = ${payoutId} and ${PAYOUTS.state} = 'pending')`;
}
/**
* What this partner has actually BEEN PAID since `since` — for the TDS
* threshold (FR-M-7), whose year starts on 1 April.
*
* Summed over settled payouts rather than `paid` earnings, because the
* question is when the money left, and only the payout carries that date.
* `partners.cumulative_paid_paise` cannot answer it at all: it is all-time,
* so it has no financial year in it.
*/
async paidSince(partnerId: string, since: Date): Promise<number> {
const rows = await this.db
.select({
total: sql<number>`coalesce(sum(${PAYOUTS.amountPaise}), 0)`,
})
.from(PAYOUTS)
.where(
and(
eq(PAYOUTS.partnerId, partnerId),
eq(PAYOUTS.state, "sent"),
gte(PAYOUTS.settledAt, since),
),
);
return rows[0]?.total ?? 0;
}
async listPayouts(partnerId: string): Promise<RrmPayout[]> {
return this.db
.select()
.from(PAYOUTS)
.where(eq(PAYOUTS.partnerId, partnerId))
.orderBy(desc(PAYOUTS.dateCreated));
}
async pendingPayout(partnerId: string): Promise<RrmPayout | null> {
const rows = await this.db
.select()
.from(PAYOUTS)
.where(
and(eq(PAYOUTS.partnerId, partnerId), eq(PAYOUTS.state, "pending")),
)
.limit(1);
return rows[0] ?? null;
}
/**
* A partner asks to be paid. Money does NOT move here.
*
* The transfer is done by hand over UPI (owner decision, 2026-08-30), so
* this records the request, locks the amount, and hands the operator
* something to act on. Settlement is `settlePayout` once the money is sent.
*
* Locking matters: the released earnings are stamped with the payout id at
* request time, so a referral that releases tomorrow does not silently
* inflate a request the operator is midway through paying.
*
* One pending request per partner. Without that, a partner tapping twice
* creates two requests over the same earnings and the operator pays both.
*
* Written with `db.batch` — D1 rejects `BEGIN TRANSACTION`, and this is
* exactly the fixed list of independent statements batch exists for.
*/
async requestPayout(input: {
partnerId: string;
upiId: string;
thresholdPaise: number;
now?: Date;
}): Promise<RrmPayout> {
const now = input.now ?? new Date();
const existing = await this.pendingPayout(input.partnerId);
if (existing) throw new PayoutAlreadyPendingError(existing.id);
// Only released, unattached earnings are payable.
const payable = await this.db
.select({ id: EARNINGS.id, amountPaise: EARNINGS.amountPaise })
.from(EARNINGS)
.where(
and(
eq(EARNINGS.partnerId, input.partnerId),
eq(EARNINGS.state, "released"),
isNull(EARNINGS.payoutId),
),
);
const amountPaise = payable.reduce((sum, e) => sum + e.amountPaise, 0);
if (amountPaise < input.thresholdPaise) {
throw new BelowThresholdError(amountPaise, input.thresholdPaise);
}
const payoutId = `pay_${generateId()}`;
const insert = this.db.insert(PAYOUTS).values({
id: payoutId,
partnerId: input.partnerId,
amountPaise,
state: "pending",
upiId: input.upiId,
dateCreated: now,
});
// Chunked for D1's bound-parameter cap, same reason as releaseDue.
const CHUNK = 90;
const attachments = [];
for (let i = 0; i < payable.length; i += CHUNK) {
const ids = payable.slice(i, i + CHUNK).map((e) => e.id);
attachments.push(
this.db
.update(EARNINGS)
.set({ payoutId })
.where(
and(
inArray(EARNINGS.id, ids),
eq(EARNINGS.state, "released"),
// Only claim earnings nobody else has. Without this a
// concurrent request overwrites the first payout's
// `payout_id` and both rows name the same money.
isNull(EARNINGS.payoutId),
),
),
);
}
// The amount was summed from a SELECT taken before the batch, but the
// attach above re-checks `state = 'released'` — an earning reversed in
// between is excluded from the attach while still counted in the sum,
// and the operator pays more than the payout covers. Recompute it from
// the rows that actually carry the payout id, as the last statement of
// the same batch so the two can never disagree.
// ponytail: a reversal racing the request can land a payout below the
// threshold (₹0 in the limit). The operator fails it; not worth a
// rollback path D1 cannot give us anyway.
const reconcile = this.db
.update(PAYOUTS)
.set({
amountPaise: sql`(select coalesce(sum(${EARNINGS.amountPaise}), 0) from ${EARNINGS} where ${EARNINGS.payoutId} = ${payoutId})`,
})
.where(eq(PAYOUTS.id, payoutId));
// `[first, ...rest]` rather than a cast: db.batch's type demands a
// non-empty tuple, and `as never` would silence that check instead of
// satisfying it. Same shape as RrmEventsDal.appendMany. `first` is always
// the insert here, so the guard is belt — but a cast that hides a real
// empty-batch bug is exactly what it would hide.
const [first, ...rest] = [insert, ...attachments, reconcile];
try {
Eif (first) await this.db.batch([first, ...rest]);
} catch (err) {
// `rrm_payouts_one_pending_per_partner` — the racing request lost.
// Report it as the same "already pending" the pre-check reports, so
// a double-tap reads identically whichever path catches it.
if (/UNIQUE constraint failed/i.test(String(err))) {
const current = await this.pendingPayout(input.partnerId);
throw new PayoutAlreadyPendingError(current?.id ?? "unknown");
}
throw err;
}
const rows = await this.db
.select()
.from(PAYOUTS)
.where(eq(PAYOUTS.id, payoutId))
.limit(1);
return rows[0];
}
/**
* The operator has sent the money. Marks the payout settled and every
* attached earning `paid`.
*
* `reference` is the UPI transaction id, typed in by the operator. It is
* the only proof the transfer happened, so it is required rather than
* optional — a settled payout nobody can trace is a dispute waiting to
* happen.
*/
async settlePayout(input: {
payoutId: string;
reference: string;
actorId: string;
now?: Date;
}): Promise<RrmPayout> {
const now = input.now ?? new Date();
// Both writes in one batch. Split, a crash between them stranded the
// earnings permanently: `released` with a payout_id, so excluded from
// every future payout yet still counted as available — money the
// partner can see and never withdraw. Re-running settle could not
// repair it either, because the payout is no longer `pending` and the
// re-run throws PayoutNotFoundError before reaching the earnings.
//
// Earnings first, payout second: the earnings predicate below asks
// whether the payout is still pending, and flipping it first would
// answer its own question.
const [, updated] = await this.db.batch([
this.db
.update(EARNINGS)
.set({ state: "paid" })
.where(
and(
eq(EARNINGS.payoutId, input.payoutId),
eq(EARNINGS.state, "released"),
this.payoutIsPending(input.payoutId),
),
),
this.db
.update(PAYOUTS)
.set({
state: "sent",
reference: input.reference,
actorId: input.actorId,
settledAt: now,
})
.where(
and(eq(PAYOUTS.id, input.payoutId), eq(PAYOUTS.state, "pending")),
)
.returning(),
]);
if (!updated[0]) throw new PayoutNotFoundError(input.payoutId);
return updated[0];
}
/**
* The transfer did not go through. Detaches the earnings so they are
* payable again rather than stranded against a dead payout.
*/
async failPayout(input: {
payoutId: string;
failureReason: string;
actorId: string;
}): Promise<RrmPayout> {
// Batched, earnings first — same reasoning as settlePayout. Stranded
// the other way round, the earnings read as available, the dashboard
// says "ready", and requestPayout then finds nothing payable (they
// still carry the dead payout id) and refuses below-threshold forever.
const [, updated] = await this.db.batch([
this.db
.update(EARNINGS)
.set({ payoutId: null })
.where(
and(
eq(EARNINGS.payoutId, input.payoutId),
eq(EARNINGS.state, "released"),
this.payoutIsPending(input.payoutId),
),
),
this.db
.update(PAYOUTS)
.set({
state: "failed",
failureReason: input.failureReason,
actorId: input.actorId,
})
.where(
and(eq(PAYOUTS.id, input.payoutId), eq(PAYOUTS.state, "pending")),
)
.returning(),
]);
if (!updated[0]) throw new PayoutNotFoundError(input.payoutId);
return updated[0];
}
}
|