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 | 31x 31x 23x 31x 31x 98x 98x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 2x 2x 2x 2x 1x 3x 2x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 19x 1x 1x 1x 1x 2x 2x 1x 1x 2x 2x 2x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {
API_BASE_URL,
ApiError,
GENERIC_ERROR_MESSAGE,
request,
uploadFile,
} from "../base";
/**
* RRM — recruitment CRM for Hyderabad channel partners (F-21).
*
* This module is the CONTRACT between the six admin screens and
* `/api/admin/rrm/*`. It is written before the routes exist so both sides can
* be built against one shape rather than negotiated afterwards.
*
* Dates cross the wire as ISO strings. The API stores epoch seconds via
* Drizzle `mode:"timestamp"`; serialisation to ISO happens at the route
* boundary, so nothing in the portal ever handles a raw epoch.
*/
// ─────────────────────────────────────────────────────────────────────────────
// Vocabulary — mirrors apps/api/src/db/schema/enums.ts
// ─────────────────────────────────────────────────────────────────────────────
/** Forward-only except into the three terminal states. */
export type RrmStage =
| "sourced"
| "queued"
| "contacted"
| "delivered"
| "read"
| "replied"
| "interested"
| "intent_stated"
| "joined"
| "not_now"
| "unreachable"
| "do_not_contact";
export type RrmTier = "A" | "B" | "C" | "D";
export type RrmConsentBasis =
| "user_initiated"
| "form_submitted"
| "stated_in_chat"
| "none";
export type RrmSource =
| "maps"
| "justdial"
| "field"
| "referral"
| "manual"
| "organic";
export type RrmLocale = "en" | "te" | "te-Latn";
export type RrmTaskType = "call" | "followup" | "escalation" | "confirm_intent";
export type RrmTaskState = "open" | "done" | "cancelled";
// ─────────────────────────────────────────────────────────────────────────────
// Entities
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
// Money (FR-M). Every amount is an INTEGER number of paise — ₹100 is 10000.
// Rupees are a rendering decision, made once, in the component.
// ─────────────────────────────────────────────────────────────────────────────
export type FunnelStep = { key: string; referrals: number };
export type ReferralFunnel = {
from: string | null;
to: string;
partnerId: string | null;
steps: FunnelStep[];
byTier: Array<{ tier: string | null; steps: FunnelStep[] }>;
/**
* How much of the programme the TIER cut can see. Tier lives on the
* recruitment record, and a self-registered partner has none — so a tier
* chart covering 12 of 400 partners looks like a chart of the programme
* unless it carries this.
*/
tierCoverage: { recruitedPartners: number; totalPartners: number };
};
export type RrmPayoutState = "pending" | "sent" | "failed" | "cancelled";
export type AdminPayoutRow = {
id: string;
partnerId: string;
/** Nulls when the partner row was hard-deleted; the payout still shows. */
partnerName: string | null;
partnerFirmName: string | null;
partnerPhoneNorm: string | null;
amountPaise: number;
state: RrmPayoutState;
/** Where the operator is to send the money. */
upiId: string | null;
/** The UPI transaction reference, once settled. Required to settle. */
reference: string | null;
failureReason: string | null;
actorId: string | null;
dateCreated: string;
settledAt: string | null;
};
/** apps/api/src/db/schema/enums.ts RRM_EARNING_REVERSAL_REASONS. */
export type RrmReversalReason =
| "duplicate_referral"
| "unreachable_contact"
| "consent_denied"
| "operator_correction"
| "fraud";
export type AdminEarningRow = {
id: string;
partnerId: string;
referralId: string | null;
kind: "validated" | "converted" | "clawback";
amountPaise: number;
state: "accrued" | "released" | "paid" | "reversed";
holdUntil: string;
releasedAt: string | null;
reversedAt: string | null;
reversalReason: RrmReversalReason | null;
payoutId: string | null;
/** Who CREDITED it. Never overwritten by a reversal. */
actorId: string | null;
notes: string | null;
reversedByActorId: string | null;
reversalNotes: string | null;
/** Set only on a clawback row: the paid earning it offsets. */
reversedOf: string | null;
dateCreated: string;
};
export type RrmProspect = {
id: string;
phoneNorm: string;
name: string | null;
firmName: string | null;
tier: RrmTier | null;
microMarkets: string[] | null;
stage: RrmStage;
stageChangedAt: string;
locale: RrmLocale;
localeSource: "default" | "detected" | "stated" | null;
doNotContact: boolean;
dncReason: string | null;
source: string;
/** Provenance. "Where did you get my number?" must be answerable in one click. */
sourceDetail: {
listingUrl?: string;
scrapedAt?: string;
page?: number;
/** Organic rows only: the `?src=` slug of the post that brought them (e.g. `grp-madhapur-01`). */
sourceLabel?: string;
} | null;
ownerId: string | null;
snoozeUntil: string | null;
firstContactedAt: string | null;
lastContactedAt: string | null;
repliedAt: string | null;
firstVisitAt: string | null;
interestedAt: string | null;
intentStatedAt: string | null;
closingsPerMonth: number | null;
notes: string | null;
/** How we are allowed to message them — `form_submitted` for landing-page sign-ups. */
consentBasis: RrmConsentBasis;
/** Which consent text they agreed to, e.g. "2026-08-v1". Null for scraped rows. */
consentVersion: string | null;
consentAt: string | null;
dateCreated: string;
};
/**
* What a sign-up actually submitted on the partner page. Two CTAs: "I'm
* interested" (no contact attached) or "I have a contact to refer" (a
* homeowner's details, entered by the referrer). `sourceDetail` here is the
* `?src=` attribution slug carried through the form — NOT the same shape as
* `RrmProspect.sourceDetail`, which describes a scraped listing's provenance.
*/
export type RrmSubmissionSummary = {
id: string;
cta: "interest" | "have_contact";
contactName: string | null;
contactPhoneNorm: string | null;
contactProject: string | null;
contactConsentAsserted: boolean;
sourceDetail: string | null;
/** Set when an earlier submission already referred this same contact. */
duplicateOfSubmissionId: string | null;
locale: RrmLocale;
dateCreated: string;
};
/** A prospect plus the organic sign-up shape the Sign-ups screen reads. */
export type RrmSignup = RrmProspect & {
submissionCount: number;
/** Newest submission, or null for a prospect somehow listed with none. */
latestSubmission: RrmSubmissionSummary | null;
};
export type RrmEvent = {
id: string;
prospectId: string;
type: string;
channel: "whatsapp" | "web" | "call" | "system" | null;
payload: Record<string, unknown> | null;
actorType: "system" | "operator" | "prospect";
actorId: string | null;
occurredAt: string;
};
export type RrmMessage = {
id: number;
direction: "inbound" | "outbound";
body: string;
templateName: string | null;
status: string;
stepKey: string | null;
dateCreated: string;
};
/** One merged timeline: messages, visits, events and tasks in one column. */
export type RrmProspectDetail = {
prospect: RrmProspect;
timeline: RrmEvent[];
messages: RrmMessage[];
/** Null when the 24-hour window is closed — the reply box uses this. */
windowExpiresAt: string | null;
/** Newest first. Empty for a scraped prospect who never filled the form. */
submissions: RrmSubmissionSummary[];
};
export type RrmInboxConversation = {
prospectId: string;
name: string | null;
firmName: string | null;
phoneNorm: string;
locale: RrmLocale;
lastInboundAt: string;
/** Server-computed so every client agrees on who is oldest. */
waitingMinutes: number;
windowExpiresAt: string | null;
lastMessagePreview: string;
/** Ambiguous opt-out language: triage must not offer "interested" here. */
needsOptOutReview: boolean;
};
export type RrmTask = {
id: string;
prospectId: string | null;
prospectName: string | null;
type: RrmTaskType;
dueAt: string;
ownerId: string | null;
state: RrmTaskState;
outcomeCode: string | null;
notes: string | null;
/** For confirm_intent: the quote an operator is judging. */
evidence: string | null;
};
/** One gate condition, evaluated server-side so the UI cannot disagree with the engine. */
export type RrmGateCondition = {
key: string;
label: string;
pass: boolean;
value: string;
threshold: string;
/** Present when failing and one screen fixes it, e.g. the inbox. */
fixHref?: string;
};
export type RrmRampState = {
conditions: RrmGateCondition[];
canRelease: boolean;
blockingReason: string | null;
nextReleaseCount: number;
sendableRemaining: number;
reservePercentAfterRelease: number;
/** Rolling 24h unique recipients against the WABA tier. */
rollingWindow: { used: number; tier: number };
todayByHour: Array<{ hour: number; newOpeners: number; followUps: number }>;
dailyCap: number;
hourlyRate: number;
halted: boolean;
haltReason: string | null;
};
/**
* One WhatsApp template as the ramp screen needs it. Mirrors
* `RrmLadderTemplateSummary` in
* `apps/api/src/routes/admin/rrm/ladder.routes.ts`.
*
* `status` is a plain string, not a union: it is a member of the API's
* `RRM_TEMPLATE_STATUS` (PENDING / APPROVED / REJECTED / PAUSED / DISABLED)
* OR the synthetic `NOT_SUBMITTED` for a template Meta has never seen. Meta
* may add a verdict before we do, and a narrower type here would render a
* new one as a crash rather than as a status nobody recognises.
*/
export type RrmTemplateSummary = {
name: string;
language: string;
category: string;
status: string;
metaTemplateId: string | null;
/** Meta's own words for a REJECTED template. Persisted by the sync, so a
* later plain GET still says why. */
rejectedReason: string | null;
bodyPreview: string | null;
variableCount: number;
/** When we last read Meta's verdict — NOT when Meta decided. `null` means
* the template has never been synced. */
updatedAt: string | null;
};
export type RrmFunnel = {
stages: Array<{ stage: RrmStage; count: number }>;
/** The program's only success criterion: >=3 in 14 days. */
intentStated: number;
gateTarget: number;
daysElapsed: number;
gateWindowDays: number;
unansweredCount: number;
oldestWaitingMinutes: number | null;
optOuts: number;
blocks: number;
sentRolling24h: number;
/** The organic (landing-page) slice of the same funnel — week-1's real number. */
organic: {
signups: number;
replied: number;
intentStated: number;
joined: number;
unrepliedCount: number;
};
};
export type RrmImportResult = {
batchId: string;
rowsTotal: number;
rowsOk: number;
rowsRejected: number;
rejects: Array<{
row: number;
phone?: string;
reason: string;
detail?: string;
}>;
};
export type RrmProspectFilters = {
page?: number;
limit?: number;
stage?: RrmStage;
tier?: RrmTier;
/** `organic` = signed up through the landing page. */
source?: RrmSource;
microMarket?: string;
q?: string;
};
function toQuery(filters: Record<string, string | number | undefined>): string {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(filters)) {
if (value !== undefined && value !== "") params.set(key, String(value));
}
const qs = params.toString();
return qs ? `?${qs}` : "";
}
const BASE = "/api/admin/rrm";
// ── Partner programme (SRS-PP-001) ──────────────────────────────────────
//
// A REFERRAL is not a prospect and a PARTNER is not one either. The RRM types
// above describe recruitment — who we are trying to sign up, and how far we
// have got. These describe the programme they joined.
export type ReferralStatus =
| "draft"
| "forwarded"
| "engaged"
| "verified"
| "contacted"
| "quoted"
| "converted"
| "duplicate"
| "rejected"
| "expired"
| "lost"
| "opted_out";
export type AdminReferralRow = {
id: string;
code: string;
status: ReferralStatus;
contactName: string;
contactPhoneNorm: string;
society: string | null;
config: string | null;
mode: string;
dateCreated: string;
engagedAt: string | null;
partnerId: string;
partnerName: string | null;
partnerPhone: string | null;
};
/**
* What `POST /referrals/:id/advance` accepts.
*
* `to` is deliberately narrower than `ReferralStatus`: `converted` is the
* money route's (`/referrals/:id/outcome`) and the rest are written by the
* partner, the webhook or the expiry sweep. Widening this type would offer an
* operator a move the API answers with a 409.
*/
export type AdvanceReferralBody = {
to: "contacted" | "quoted" | "lost";
/** Required for `contacted` — the professional the inquiry is raised against. */
proId?: string;
/** Required for `lost`. Internal: the partner is not shown it. */
reason?: string;
};
export type AdminReferralDetail = {
referral: AdminReferralRow & {
possessionBand: string | null;
rejectedReason: string | null;
nudgeCount: number;
forwardedAt: string | null;
verifiedAt: string | null;
/** The inquiry this referral became, once it is one. */
inquiryId: string | null;
};
partner: {
id: string;
name: string;
firmName: string | null;
phoneNorm: string;
suspendedAt: string | null;
} | null;
events: Array<{
id: string;
type: string;
actorType: string;
actorId: string | null;
payload: string | null;
occurredAt: string;
}>;
/**
* The WHOLE ledger row, not a four-field summary — the endpoint selects
* every column of `rrm_earnings`, and this screen's withdrawal buttons need
* what the summary dropped: `state` and `payoutId` decide whether Reverse
* is even offered (the API refuses a row locked to a pending payout), and
* `reversedOf` says which paid row a clawback already offsets.
*/
earnings: AdminEarningRow[];
/**
* What verifying will actually pay, from the live programme config — NOT a
* constant in the client. The screen shows this before the click, and a
* hardcoded copy would go stale the moment ops changed the rate.
*/
verifyAmountPaise: number;
/**
* What a CONVERSION pays, from the live config the ledger prices it from —
* the same reasoning as `verifyAmountPaise`, one decision further on.
*/
convertAmountPaise: number;
/** The thread, so a decision needs one screen and not two (FR-A-1). */
conversation: { id: number; lastCustomerMessageAt: string | null } | null;
messages: Array<{
id: number;
direction: string;
messageType: string;
content: string | null;
createdAt: string;
}>;
firstReferral: { id: string; code: string; dateCreated: string } | null;
};
export type AdminPartnerRow = {
id: string;
name: string;
firmName: string | null;
phoneNorm: string;
prospectId: string | null;
shareCode: string | null;
source: string;
capPerDay: number | null;
capPerMonth: number | null;
cumulativePaidPaise: number;
/** Last four only — the full PAN is never stored (FR-M-7). */
panLast4: string | null;
/** Off means they have told us to stop — theirs, or an operator's Mute. */
notifyWhatsapp: boolean;
suspendedAt: string | null;
suspendedReason: string | null;
dateCreated: string;
referralCount: number;
verifiedCount: number;
};
export type Paged<K extends string, T> = {
[P in K]: T[];
} & { total: number; limit: number; offset: number };
export const adminRrmApi = {
// ── prospects ──────────────────────────────────────────────────────────
listProspects(filters: RrmProspectFilters = {}) {
return request<RrmProspect[]>(`${BASE}/prospects${toQuery(filters)}`);
},
/**
* The organic-only screen. The endpoint already filters to `source =
* "organic"` server-side, so no `source` filter is accepted here — passing
* one would just be a parameter the API ignores.
*/
listSignups(filters: { page?: number; limit?: number } = {}) {
return request<RrmSignup[]>(`${BASE}/signups${toQuery(filters)}`);
},
getProspect(id: string) {
return request<RrmProspectDetail>(`${BASE}/prospects/${id}`);
},
updateProspect(
id: string,
patch: Partial<
Pick<
RrmProspect,
"name" | "firmName" | "tier" | "ownerId" | "notes" | "locale"
>
>,
) {
return request<RrmProspect>(`${BASE}/prospects/${id}`, {
method: "PATCH",
body: patch,
});
},
/**
* The API re-runs the forward-only stage rule and MAY refuse. A refusal is
* a normal outcome, not an error — it comes back with the reason so the UI
* can say why nothing moved rather than appearing to do nothing.
*/
setStage(id: string, stage: RrmStage, reason: string) {
return request<{ changed: boolean; stage: RrmStage; reason?: string }>(
`${BASE}/prospects/${id}/stage`,
{ method: "POST", body: { stage, reason } },
);
},
markDnc(id: string, reason: string) {
return request<RrmProspect>(`${BASE}/prospects/${id}/dnc`, {
method: "POST",
body: { reason },
});
},
snooze(id: string, days: number) {
return request<RrmProspect>(`${BASE}/prospects/${id}/snooze`, {
method: "POST",
body: { days },
});
},
erase(id: string) {
return request<{ erased: true }>(`${BASE}/prospects/${id}/erase`, {
method: "POST",
});
},
/**
* One-click "Mark replied" for the Sign-ups row (3.4). The API may refuse
* with 409 for a terminal or do-not-contact prospect — `request` already
* turns that into an `ApiError`, which the caller surfaces inline.
*/
markReplied(id: string) {
return request<RrmProspect>(`${BASE}/prospects/${id}/reply`, {
method: "POST",
});
},
/**
* The untracked "sent the link by hand" send (1.4). `skipped` names why a
* given id did not move — the stage rule still applies per-row, so a mixed
* selection can partially succeed.
*/
bulkStage(body: { ids: string[]; stage: RrmStage; reason: string }) {
return request<{
moved: number;
skipped: { id: string; reason: string }[];
}>(`${BASE}/prospects/bulk-stage`, { method: "POST", body });
},
/**
* Hard delete for test data (3.6) — distinct from `erase`, which is the
* DPDP-compliant scrub and keeps the row. The contract returns a bare 204
* with no JSON body, which `request<T>` cannot parse (it requires a JSON
* content-type on every response), so this talks to `fetch` directly
* instead of going through the shared client.
*/
async deleteProspect(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}${BASE}/prospects/${id}`, {
method: "DELETE",
credentials: "include",
});
if (response.ok) return;
let code = "UNKNOWN_ERROR";
let message = GENERIC_ERROR_MESSAGE;
try {
const body = (await response.json()) as {
error?: { code?: string; message?: string };
};
code = body.error?.code ?? code;
message = body.error?.message ?? message;
} catch {
// Error responses without a JSON body fall back to the generic message.
}
throw new ApiError(code, message, response.status);
},
/**
* Bulk CSV import (multipart, field `file`). Nothing is retried here: a
* partial import is recoverable by re-uploading the same file, because every
* row already written comes back rejected as `already_prospect`.
*/
importProspects(file: File) {
return uploadFile<RrmImportResult>(`${BASE}/prospects/import`, file);
},
// ── inbox ──────────────────────────────────────────────────────────────
/**
* Server-ordered oldest-first. There is deliberately no sort parameter:
* backlog over 24h auto-pauses the campaign, so sorting away from
* oldest-first is not a feature.
*/
listInbox() {
return request<RrmInboxConversation[]>(`${BASE}/inbox?state=unanswered`);
},
sendMessage(prospectId: string, body: string) {
return request<RrmMessage>(`${BASE}/messages/send`, {
method: "POST",
body: { prospectId, body },
});
},
// ── tasks ──────────────────────────────────────────────────────────────
listTasks(
filters: { owner?: string; state?: RrmTaskState; type?: RrmTaskType } = {},
) {
return request<RrmTask[]>(`${BASE}/tasks${toQuery(filters)}`);
},
completeTask(id: string, outcomeCode: string, notes?: string) {
return request<RrmTask>(`${BASE}/tasks/${id}/complete`, {
method: "POST",
body: { outcomeCode, notes },
});
},
/**
* Confirms a stated referral intent. This is the ONLY path to
* `intent_stated` — a submitted contact note raises a task, it never sets
* the stage itself, because three of these decide whether Phase 2 is built
* and "maybe later" must not be able to count itself.
*/
confirmIntent(taskId: string, confirmed: boolean, evidence: string) {
return request<RrmTask>(`${BASE}/tasks/${taskId}/confirm-intent`, {
method: "POST",
body: { confirmed, evidence },
});
},
// ── ramp, halt, metrics ────────────────────────────────────────────────
getRamp() {
return request<RrmRampState>(`${BASE}/ramp`);
},
/**
* The only way sends are released. Refuses with the failing condition if the
* gate is unmet — unless `override` is passed, which forces past OUR policy
* gates and the halt.
*
* The override key is only sent when one was asked for: its mere presence
* makes the server stamp `overriddenBy` and `overrideReason` into the audit
* row, so sending `undefined` on an ordinary release would file a bogus
* override against the operator. The server re-checks the 20-character
* minimum; the screen checks it first so nobody types four words and waits
* for a round trip to be told.
*/
openRamp(
count: number,
acknowledgedMetrics: true,
override?: { reason: string },
) {
return request<{ released: number }>(`${BASE}/ramp/release`, {
method: "POST",
body: {
count,
acknowledgedMetrics,
...(override ? { override } : {}),
},
});
},
setHalt(on: boolean, reason: string) {
return request<{ halted: boolean }>(`${BASE}/halt`, {
method: "POST",
body: { on, reason },
});
},
// ── templates ──────────────────────────────────────────────────────────
/**
* Approval status as of the last sync. A local read — it does NOT ask
* Meta, so a template approved five minutes ago still reads as pending
* here until someone syncs.
*/
getTemplates() {
return request<RrmTemplateSummary[]>(`${BASE}/templates`);
},
/**
* Re-read Meta's verdict and store it. This does not submit anything and
* cannot approve anything — approval is a human act in WhatsApp Manager.
*
* Answers 503 when WhatsApp is not configured, because there is nothing to
* ask.
*/
syncTemplates() {
return request<RrmTemplateSummary[]>(`${BASE}/templates/sync`, {
method: "POST",
});
},
getFunnel(params: { from?: string; to?: string } = {}) {
return request<RrmFunnel>(`${BASE}/metrics/funnel${toQuery(params)}`);
},
// ── campaign copy, editable without a deploy ───────────────────────────
getCampaignConfig() {
return request<Record<string, string>>(`${BASE}/config`);
},
/**
* Change one config row. PATCH, not POST: the endpoint validates per key
* (numbers, booleans and the holiday list all have their own rules) and
* returns the FULL effective config afterwards — stored values over
* defaults — so the screen shows what will actually happen, not just the
* row that was written. `reason` is mandatory and audited.
*/
setCampaignConfig(
key: string,
value: string | number | boolean | string[],
reason: string,
) {
return request<Record<string, string>>(`${BASE}/config`, {
method: "PATCH",
body: { key, value, reason },
});
},
// ── Partner programme ────────────────────────────────────────────────
/**
* The verification queue by default — no `status` means `engaged` only,
* oldest first. Pass a comma-separated `status` for the full table, which
* switches to newest-first.
*/
listReferrals(
filters: {
status?: string;
partnerId?: string;
search?: string;
limit?: number;
offset?: number;
} = {},
) {
return request<Paged<"referrals", AdminReferralRow>>(
`${BASE}/referrals${toQuery(filters)}`,
);
},
getReferral(id: string) {
return request<AdminReferralDetail>(`${BASE}/referrals/${id}`);
},
/**
* Moves to `verified` AND credits ₹100, in that order.
*
* The note is optional and internal — the API attaches the conversation
* evidence by itself, so an operator with nothing to add sends no body at
* all rather than an empty string the audit log has to carry.
*/
verifyReferral(id: string, note?: string) {
return request<{ credited: boolean; creditReason: string | null }>(
`${BASE}/referrals/${id}/verify`,
{ method: "POST", ...(note ? { body: { note } } : {}) },
);
},
/**
* Record a paid OUTCOME on a referral — the only route that credits the
* ₹1,000 conversion (FR-M-3).
*
* `converted` moves the referral to `converted` first and refuses anything
* that is not `quoted`, so this is not interchangeable with `advance`. The
* note is optional and internal, like the verify one: an empty string is
* not a note, so it is left out of the body entirely.
*/
recordOutcome(id: string, kind: "validated" | "converted", notes?: string) {
return request<AdminEarningRow>(`${BASE}/referrals/${id}/outcome`, {
method: "POST",
body: notes ? { kind, notes } : { kind },
});
},
/** The reason is shown to the partner, so it is not optional. */
rejectReferral(id: string, reason: string) {
return request<unknown>(`${BASE}/referrals/${id}/reject`, {
method: "POST",
body: { reason },
});
},
markReferralDuplicate(id: string) {
return request<unknown>(`${BASE}/referrals/${id}/duplicate`, {
method: "POST",
});
},
/**
* The rest of the ladder — the handoff, the quote, and the dead end.
*
* `contacted` is the only one that needs a `proId`, because it is the only
* one that creates something: a real marketplace inquiry against that
* professional, which is why the operator has to pick one. `lost` needs a
* reason. The API refuses either omission, so the screen and the server
* agree on the same two rules.
*/
advanceReferral(id: string, body: AdvanceReferralBody) {
// `referral` is the raw row the endpoint echoes back — named so callers
// know it is there, `unknown` like its two siblings because nothing on
// this screen reads it and the shape is not the mapped admin row.
return request<{ referral: unknown; inquiryId: string | null }>(
`${BASE}/referrals/${id}/advance`,
{ method: "POST", body },
);
},
/**
* FR-I-3's funnel diagnostic. `partnerId` scopes it to one partner; without
* it the response covers the whole programme and adds a tier breakdown.
*/
referralFunnel(
filters: { from?: string; to?: string; partnerId?: string } = {},
) {
return request<ReferralFunnel>(
`${BASE}/referral-funnel${toQuery(filters)}`,
);
},
// ── Money ───────────────────────────────────────────────────────────────
/**
* The settle queue. Defaults to `pending` at the call site, not here — the
* unfiltered list is a real view (an audit of everything paid) and a hidden
* default would make it unreachable.
*/
listPayouts(filters: { state?: RrmPayoutState } = {}) {
return request<AdminPayoutRow[]>(`${BASE}/payouts${toQuery(filters)}`);
},
/**
* Record a UPI transfer that has ALREADY been made.
*
* The reference is required server-side (422 without one): a settled payout
* nobody can trace is a dispute with no evidence. The API also refuses this
* when the payment would cross the partner's TDS threshold for the year
* with no PAN on file (FR-M-7) — surface that message as written, it was
* composed for the operator to read.
*/
settlePayout(id: string, reference: string) {
return request<AdminPayoutRow>(`${BASE}/payouts/${id}/settle`, {
method: "POST",
body: { reference },
});
},
/** The transfer bounced. Detaches the earnings so they are payable again. */
failPayout(id: string, failureReason: string) {
return request<AdminPayoutRow>(`${BASE}/payouts/${id}/fail`, {
method: "POST",
body: { failureReason },
});
},
/**
* FR-M-6: a lead disputed AFTER the money was sent.
*
* Writes a negative row that offsets the partner's next payment. Never a
* demand for money back, and never an edit to the settled row. For an
* earning that has NOT been paid, use `reverseEarning` — the API says so in
* its 409.
*/
clawbackEarning(id: string, reason: RrmReversalReason, notes?: string) {
return request<AdminEarningRow>(`${BASE}/earnings/${id}/clawback`, {
method: "POST",
body: notes ? { reason, notes } : { reason },
});
},
/** Withdraw a credit that has not been paid yet. */
reverseEarning(id: string, reason: RrmReversalReason, notes?: string) {
return request<AdminEarningRow>(`${BASE}/earnings/${id}/reverse`, {
method: "POST",
body: notes ? { reason, notes } : { reason },
});
},
listPartners(
filters: {
search?: string;
suspended?: "true" | "false";
limit?: number;
offset?: number;
} = {},
) {
return request<Paged<"partners", AdminPartnerRow>>(
`${BASE}/partners${toQuery(filters)}`,
);
},
getPartner(id: string) {
return request<{
partner: AdminPartnerRow;
referrals: AdminReferralRow[];
earnings: Array<{
id: string;
kind: string;
amountPaise: number;
state: string;
}>;
payouts: Array<{ id: string; amountPaise: number; state: string }>;
prospect: { id: string; stage: string } | null;
}>(`${BASE}/partners/${id}`);
},
/** FR-F-7: never silent — the reason reaches the partner's login screen. */
suspendPartner(id: string, reason: string) {
return request<unknown>(`${BASE}/partners/${id}/suspend`, {
method: "POST",
body: { reason },
});
},
unsuspendPartner(id: string) {
return request<unknown>(`${BASE}/partners/${id}/unsuspend`, {
method: "POST",
});
},
/**
* A STOP that came back to the operator's own handset, where hand-sent
* invitations are answered and the webhook never looks. Turns off exactly
* what the partner's own STOP turns off.
*
* There is no unmute: the partner replies START. Their word closed the
* channel, so their word is what reopens it.
*/
mutePartner(id: string) {
return request<unknown>(`${BASE}/partners/${id}/mute`, {
method: "POST",
});
},
/**
* DPDP erasure. The partner asks over WhatsApp — the help screen in their
* app sends the message — and this is the only route that honours it.
*
* Anonymises, never deletes: the account keeps its id and its payment
* record, and loses everything that says who they were. Super-admin only,
* so a plain admin gets a 403 to show rather than a silent no-op.
*/
erasePartner(id: string) {
return request<{ erased: boolean }>(`${BASE}/partners/${id}/erase`, {
method: "POST",
});
},
/** null clears an override, returning them to the programme default. */
setPartnerCaps(
id: string,
caps: { capPerDay?: number | null; capPerMonth?: number | null },
) {
return request<unknown>(`${BASE}/partners/${id}/caps`, {
method: "POST",
body: caps,
});
},
/**
* The fallback for a PAN sent on WhatsApp (FR-M-7). The full PAN goes over
* once; the API keeps its last four and nothing else.
*/
setPartnerPan(id: string, pan: string) {
return request<unknown>(`${BASE}/partners/${id}/pan`, {
method: "POST",
body: { pan },
});
},
};
|