01 Actors & API surfaces
| Actor | Frontend | Backend surface | What they do |
| Borrower / customer | los-webv1 | web | Applies for a loan, completes KYC/onboarding, views status, repays |
| Internal staff (Sales, Credit, Sanction, Loan Ops, Collections, NPA, Admin) | los-partner | partner | Works the entire loan pipeline through one shared CRM, gated by role + permission |
| Channel-partner / DSA staff | los-partner (same app, brand-scoped) | partner | Same CRM, same role/permission model — distinguished by brand/role, not a separate app |
| Machine integrators (marketplace, affiliates e.g. loanwalle) | server-to-server | api-key / credential | Auto-login, lead handoff |
| SSO super-admin | via separate sso-los-login service | accepted on any non-public route | Cross-cutting platform override |
02 End-to-end loan lifecycle
Every loan moves along two independent axes: status (what the loan is) and currentStage (who currently owes work on it). They move independently except at specific handoff points. loan_tasks is the append-only history of every stage entered.
Loan stage pipeline (currentStage axis)
flowchart LR
A["APPLICATION
loan created, status=PENDING"] --> BRE{"BRE auto-screen
Smart/CRIF/Neetix/Marketing"}
BRE -- "BRE_APPROVED /
SOFT+allow_restart" --> SALES["SALES
queue work"]
BRE -- "DELETED / DORMANT" --> A
BRE -- "HARD_REJECTED" --> TERM(["terminal
super-admin revert only"])
SALES --> CREDIT["CREDIT desk
(migration 110)"]
CREDIT --> FV{"FIELD_VISIT
brand-gated, default off"}
FV -- "enabled" --> MGR["MANAGER
CAM + evaluation review"]
FV -- "disabled" --> MGR
MGR -- "Approve" --> ESIGN["ESIGN
agreement signing"]
MGR -- "Reject" --> TERM2(["SOFT / HARD / BRE_REJECTED"])
ESIGN -.optional.-> ESTAMP["ESTAMP
stamp duty (off by default)"]
ESIGN -.optional.-> MANDATE["MANDATE
UPI Autopay wait"]
ESTAMP --> DISB
MANDATE --> DISB
ESIGN --> DISB["DISBURSEMENT
status=AWAITING_DISBURSEMENT"]
DISB --> POST["POST_DISBURSEMENT
status=ACTIVE"]
POST -- "repayments" --> CLOSE(["CLOSED
COMPLETED / SETTLED / WRITE_OFF"])
POST -- "delinquent" --> COLL["COLLECTION_FIELD_VISIT"]
COLL --> CLOSE
Application created
Borrower applies → loans row inserted, status=PENDING, currentStage=APPLICATION. Loan sequence stamped atomically by a DB trigger.
BRE auto-screen (the gate)
Runs only on PENDING loans, through whichever engines the brand has enabled. Outcomes: BRE_APPROVED, SOFT_REJECTED, BRE_REJECTED, HARD_REJECTED, DELETED, DORMANT. HARD_REJECTED is terminal unless a super-admin reverts it.
SALES
Application enters the sales queue. Worked PENDING/ASSIGNED → IN_PROGRESS → QUERY? → COMPLETED. Loan status unchanged throughout.
CREDIT not in old docs
Credit desk underwrites the completed file before a borrower visit or sanction — reached by explicit workflow move, loan stays PENDING.
FIELD_VISIT
Underwriting visit, brand-gated (default off — skips straight to MANAGER if off). Distinct from COLLECTION_FIELD_VISIT, which is post-disbursement.
MANAGER — the decision point
Reviews CAM calculator, evaluations, credit/BSA reports. This is where loans.status actually changes. Approve → task closes APPROVED, approvalDate stamped. Reject → SOFT/HARD/BRE_REJECTED.
ESIGN its own stage since migration 128
Approved file waits on borrower signature. One loan_agreements row per entry in the brand's signing package. Annexures never block completion.
Optional — ESTAMP / MANDATE
ESTAMP: stamp-duty step, off by default, not yet routed to in production. MANDATE: if the brand runs UPI Autopay and the customer hasn't authorized it yet, the loan waits here.
DISBURSEMENT
Once every signature-requiring agreement is SIGNED, status=AWAITING_DISBURSEMENT. Payout is a separate queued step (AutoDisbursementJob) — the stage-advance itself must never trigger money movement.
POST_DISBURSEMENT (active)
On successful disbursal, status=ACTIVE. As repayments arrive: PARTIALLY_PAID → closure (COMPLETED/SETTLED/WRITE_OFF) or DEFAULTED/NPA if delinquent (may pick up COLLECTION_FIELD_VISIT).
CLOSED
Terminal stage.
Documentation drift this page corrects
The team's own md/loan-workflow.md only documents APPLICATION → SALES → FIELD_VISIT → MANAGER → DISBURSEMENT → POST_DISBURSEMENT. The real pipeline has three additional stages (CREDIT, ESIGN as its own stage, MANDATE) plus an optional fourth (ESTAMP) that aren't in that doc.
03 Reloan (repeat-borrower) automation
Fully rule-based — no manual step unless explicitly routed to manual review. Every decision, eligible or not, is logged for RBI-compliance audit.
Reloan decision flow
flowchart TD
START(["Repeat-borrower requests reloan"]) --> PRE{"Pre-checks:
missing data or
migrated record?"}
PRE -- yes --> MANUAL["MANUAL_REVIEW_REQUIRED"]
PRE -- no --> HARD{"Hard stops:
prev loan not COMPLETED,
WRITE_OFF/SETTLEMENT,
or DPD > 30d?"}
HARD -- yes --> REJECT(["REJECTED"])
HARD -- no --> RECENCY{"> 90 days since
previous disbursement?"}
RECENCY -- yes --> MANUAL2["MANUAL_REVIEW
(MORE_90_DAYS)"]
RECENCY -- no --> AABUCKET{"AA approval date
bucket"}
AABUCKET -- "≥ 90 days" --> MANUAL3["MANUAL_REVIEW
(MORE_90_DAYS)"]
AABUCKET -- "< 90 days" --> DUEDATE{"Due date within
±3 days of
reference date?"}
DUEDATE -- no --> MANUAL4["MANUAL_REVIEW"]
DUEDATE -- yes --> AACHECK{"AA data
available?"}
AACHECK -- no --> MANUAL5["MANUAL_REVIEW
(BANK_STATEMENT_REQUIRED)"]
AACHECK -- yes --> AMOUNT{"Requested amount ≤
max(min(prev×1.1, salary×0.6), prev)?"}
AMOUNT -- yes --> APPROVE(["AUTO-APPROVED
(AUTOMATED_FLOW)"])
AMOUNT -- no --> MANUAL6["MANUAL_REVIEW
(AMOUNT_INCREASE)"]
04 Disbursement & UPI Autopay
Disbursement → recurring collection
sequenceDiagram
participant Loan as Loan (APPROVED)
participant Sign as Agreements
participant Disb as AutoDisbursementJob
participant Pay as payment_request
participant Mand as UPI Mandate
participant Cron as Daily 8am cron
Loan->>Sign: wait for all signature-required agreements SIGNED
Sign-->>Loan: status = AWAITING_DISBURSEMENT
Loan->>Disb: queue payout (if brand auto_disbursement_enabled)
Disb->>Pay: create PaymentDisbursalTransaction (1 leg, or N legs for consolidation)
Pay-->>Loan: on success, status = ACTIVE
Loan->>Mand: partner triggers mandate creation
Mand->>Mand: customer authorizes via ₹1 checkout (Cashfree/Razorpay/PhonePe)
Mand-->>Loan: webhook confirms ACTIVE (or BANK_APPROVAL_PENDING)
Cron->>Mand: find loans due tomorrow with active mandate
Cron->>Mand: trigger debit
Mand-->>Loan: webhook resolves success/failure
Loan->>Loan: auto-approve collection if COLLECTION_AUTO_APPROVE_ENABLED
Design rule (deliberate)
Money movement is decoupled from workflow stage-advance transitions by design — the loan-workflow doc explicitly warns against letting any stage-advance trigger a payout directly. Manual collection is frozen while a debit is in flight to prevent double-collection.
05 WhatsApp & chat — what's actually live
Two live systems, one unrelated proxy that shares a confusingly similar name, and one feature that is real but not merged into this branch yet. Easy to conflate — keep them distinct.
WhatsApp Flows
In-chat loan application · live
Meta's encrypted Flow protocol — collects bank account, runs DigiLocker + AA consent, submits a loan application without leaving WhatsApp. Only loads if PRIVATE_KEY_PATH is set.
Web chatbot
Plain OpenAI widget · live
Intent-classified conversational widget on the public web for EMI calc, eligibility, apply, track. Uses gpt-4o-mini via standard api.openai.com — not Azure, despite a stale code comment.
crm-chatbot unrelated
Partner-staff AI assistant · live
A thin proxy from the CRM to a separate "Central Chatbot" microservice so staff can ask it questions. No WhatsApp, no LLM logic in this backend — just forwards the request. Shares no code with the two rows above.
WhatsApp CRM (staff inbox)
Two-way conversation tooling · not merged
Real feature with a full commit history (WTP client, sender accounts, templates, inbound webhook, RBAC) — but it all lives on origin/feature/whatsapp-crm-abhi, which is not an ancestor of this branch. Only the Prisma schema (whatsapp_crm_enabled etc.) has landed here; no application code consumes it yet.
06 Collections, reminders & sign-in codes
- Reminders —
BrandReminderConfig/Rule define per-brand cadence; SQS-backed dispatch runs only on the cron-worker to avoid duplicate sends across the PM2 cluster; delivered via email/SMS/WhatsApp.
- Collections — staff work the
COLLECTION_FIELD_VISIT stage, logging promise-to-pay (PTP) via CollectionRemarks (also consumed by the Coin system's PTP-kept/broken rules). DPD is snapshotted daily at 06:00 and drives NPA classification (default 90 days).
- Partner sign-in code flow (staff account recovery) — admin generates a 12-char code in the CRM → shares out-of-band → user selects "Sign-in code" at login → single-use, consumed atomically → session created. Disallowed for ADMIN/SUPER_ADMIN accounts to prevent impersonation; re-validated at login time so a code issued before a role change is safely invalidated.
07 Business rules & risks worth knowing
Permission model
Access is permission-driven, never role-name-driven — a user with role "Other" but the right permissions has full access; a user with role "Sales" but no permissions has none. Allocation checks both role and permission together, and supervisory roles are deliberately excluded from receiving new-work allocations even if they hold the permission.
EMI pricing engine — live, test-pinned traps
Documented against a 3,600-randomised-loan test suite: (1) exclusive fees configured but never actually collected (High); (2) broken-period interest can be double-charged if bpi_mode isn't left at NONE (High); (3) a moratorium/EMI-holiday is effectively free under one day-count convention but priced under another — same product behaves very differently depending on one field (High); (4) two active interest rows on one product price randomly between requests (Medium).
A consistent engineering principle
"Money-safety" patterns repeat deliberately across the codebase: e-stamp has a NEEDS_REVIEW terminal state specifically for "vendor call outcome unknown" rather than guessing/retrying; UPI Autopay never auto-retries an ambiguous debit; the loan workflow explicitly forbids a stage-advance from triggering a payout. Worth treating as a company engineering value, not a one-off.
Coin system is additive-only
Reads loan_status_history/loan_tasks/payment tables as an event source and can never block or roll back a business transaction. No public ingestion endpoint exists on purpose (prevents coin-minting abuse). All ledger tables are append-only — DB triggers reject UPDATE/DELETE.