8byte.ai
📙 Part 3 of 3 — Combined Architecture & Flow

8byte LOS
Full Platform Work Flow

The complete picture: how the frontend and backend work together, every user journey from start to finish, the full data flow, system architecture, and how every piece connects.

12
Loan Stages
15+
Staff Roles (los-partner)
35+
Vendor Integrations
15+
Lending Brands
5
Payment Gateways
🎯

About the Platform

The complete picture in one place

8byte LOS (Loan Origination System) is a production-ready, multi-brand lending platform for Indian NBFCs and fintech companies. It manages the complete loan lifecycle — from a customer's first registration, through KYC and credit checks, to disbursement, repayment, and final closure — with full automation, multi-channel communication, and a comprehensive internal operations portal for lending staff.
⚠ Repo-naming correction — read this before the flows below The two frontend repo names in this platform are easy to misread, and earlier drafts of this document got them backwards. They are the opposite of what their names suggest:
  • los-webv1 is the borrower/customer-facing app — the loan applicant's own phone-OTP login, KYC/liveness onboarding wizard, loan application, and repayment experience. It is white-labelled across ~15 lending brands, with up to ~30 UI template variants per onboarding step.
  • los-partner is not an external DSA/channel-partner submission portal despite its name. It is the internal staff back-office CRM — used by each lending brand's own employees (sales, credit, sanctioning, disbursement ops, collections, HR) to run the entire loan lifecycle. "Partner" here refers to each lending brand being a tenant/partner of the 8byte platform, not to external referrers.
los-backend (NestJS) serves both apps from one API, via a global AuthGuard/@AuthType mechanism — web for los-webv1, partner for los-partner — plus WhatsApp/voice channels and machine-to-machine partner/marketplace integrations. Every flow section below should be read with this in mind: steps described as "customer" or "borrower" actions happen in los-webv1; steps described as staff/executive/manager actions happen in los-partner. For full per-repo technical and product detail with flowcharts, see the module deep-dive hub.

👥 Two User Worlds

Borrowers/customers interact via los-webv1 (the web API surface). Internal staff — sales, credit, sanctioning, loan ops, collections, HR, admin — interact via los-partner, the staff CRM (the partner API surface). These are completely separate authenticated systems, each with its own JWT and login flow.

🏷️ Multi-Brand Platform

A single codebase serves 15+ white-label lending brands simultaneously: Qualoan, PaisaPop, Minutes Loan, Zepto Finance, Salary4Sure, FastSalary, SalaryBolt, SalaryBaba, JhatpatCash, CredNidhi, ShubLakshmi, PaisaAnytime, ToofanLoan, MySalaryLoan, SwiftPaisa, ExpressoLoan, DezireLoan, and more. Each brand has its own loan rules, theme, communication templates, staff, and settings — but shares the same infrastructure. Nearly every business rule described below (BRE engines, field visit requirement, reminder cadence, workflow steps, auto-disbursement) is independently toggleable per brand.

🔄 Full Lifecycle Coverage

From customer acquisition (UTM tracking, lead forms) → onboarding (KYC) → BRE auto-screen → sales → credit underwriting → sanction → e-sign → disbursement → repayment → collections → closure. Every step is tracked, logged, and auditable.

🏗️

Full System Architecture

Every layer of the platform and how they connect

Client Layer

los-webv1 — Borrower SPA (React 19 + Vite 6) los-partner — Staff CRM SPA (React 19 + Vite 6) Redux Toolkit State Axios API Client React Router v7 TailwindCSS 4 + Framer Motion AWS Amplify Liveness (los-webv1) Acefone / Sphoro Voice Widget (los-partner) FingerprintJS (both apps)

API Layer — los-backend, NestJS 11 (PM2: API Cluster + Cron-Worker)

Global AuthGuard (@AuthType: web / partner / public / api-key / credential) Role + Permission Guard (permission-driven, not role-driven) Throttle Rate Limiter Validation Pipe (class-validator) Compression Middleware Helmet Security Headers ~35 Domain Features 248 Prisma Models / 146 Enums Request/Response Interceptors BigInt Serializer Global Exception Filter Field-Level PII Encryption

Auth & Identity

Web Auth (OTP) Partner Auth (Password) JWT + bcrypt Device Fingerprint Session Tracking

Loan Engine

Loan CRUD Status Machine Auto-Allocation Evaluation v1/v2 BRE Reloan Automation

Payment Engine

Razorpay Cashfree Paytring IDFC Disbursal ICICI Disbursal Autopay Mandate

Database

PostgreSQL Prisma ORM GIN/TRGM Indexes Migrations

Cache & Queues

Redis Cache RabbitMQ Jobs AWS SQS Audit AWS SQS NOC Trigger.dev

File Storage

AWS S3 Public AWS S3 Private Presigned URLs PDF Generation

External API Integrations (25+)

Digitap (KYC) Equifax (Credit) CIBIL (Credit) CIR Pro V2 (BRE) CART (BSA) Finbox (BSA) ScoreMe (BSA+Score) Account Aggregator Penny Drop Signzy (eSign) SignDesk (eSign) DigiLocker 2.0 EPFO/UAN Acefone (VoIP) Lendbox (CoLend) SendGrid/Brevo/Zepto MSG91/Gupshup/NimbusIT AiSensey (WhatsApp) Google Maps
🏷️

Multi-Brand Model

How one codebase serves many lending brands

Every route in los-partner is scoped to a brandId: /:brandId/loans, /:brandId/dashboard, etc. The backend extracts this brandId from the URL, validates that the logged-in partner user has access to that brand, and then filters all database queries by that brandId. Two staff at different brands cannot see each other's data even if they use the same app. los-webv1 resolves its brand from the request hostname instead (each brand is served on its own domain/subdomain) and applies the matching theme/workflow config at runtime.
15+ lending brands on one platform The CORS allowlist in los-backend names the current tenant set: Qualoan, PaisaPop, Minutes Loan, Zepto Finance, Salary4Sure, FastSalary, SalaryBolt, SalaryBaba, JhatpatCash, CredNidhi, ShubLakshmi, PaisaAnytime, ToofanLoan, MySalaryLoan, SwiftPaisa, ExpressoLoan, DezireLoan. Each is a distinct Brand tenant row — its own theme, logo, loan rules, BRE engine selection, field-visit requirement, reminder cadence, and workflow steps, all independently configurable.

🎨 Brand Isolation

Each brand has its own: logo, color theme, loan rules (min/max amounts, tenures, interest rates), evaluation criteria, email templates, SMS templates, partner staff, and customers. Complete data isolation at the database level via brandId foreign keys.

⚙️ Brand Config Flow

On login, the partner portal fetches brand config via GET /settings/brand. This is stored in the Redux brand slice. The ThemeProviderContext injects the brand's colors as CSS variables. All subsequent API calls include the brandId automatically.

🔐 Brand Access Control

A partner user can be assigned to one or multiple brands (stored in PartnerUserBrandRole). They log in once and can switch between their brands. The Super Admin can access all brands via the /admin portal without brand scoping.

👤

Complete Customer Journey

Every step from signup to loan closure

Lanes 1–5 and 8 (partially) run on los-webv1, the borrower's own app. Lanes 6, 7, and the staff-side halves of 9–11 run on los-partner, the staff CRM. See KYC Flow and Loan Application Flow below for the current, more granular stage breakdown — this swimlane is a simplified narrative view.
Customer Journey — Step by Step
1. Acquisition
Sees ad (UTM tracked)
→
Lands on brand website
→
Clicks Apply
→
UTM params saved to DB
2. Registration
Enters phone number
→
OTP sent via SMS
→
Verify OTP
→
User record created
→
JWT issued
3. KYC
Enter PAN
→
Digitap verifies PAN
→
Aadhaar OTP
→
Upload selfie + docs
→
Docs to S3
4. Employment
Enter employer details
→
Enter UAN
→
EPFO verification
→
Upload payslips
5. Bank
Add bank account
→
Penny drop verify
→
Upload bank statement
→
BSA analysis runs
6. Evaluation
Credit report fetched
→
BRE hard rules check
→
Evaluation scoring
→
Loan auto-allocated to executive
7. Approval
Credit executive reviews
→
Sanction manager approves
→
Sanction head confirms
→
Status → SANCTIONED
8. eSign
Agreement PDF generated
→
Sent to Signzy/SignDesk
→
Customer signs digitally
→
Webhook → SIGNED
9. Disbursement
Bank details re-verified
→
Transfer via IDFC/ICICI
→
Status → DISBURSED
→
Repayment timeline created
→
Confirmation SMS/Email
10. Repayment
Reminders 3 days before due
→
Customer pays via Razorpay/Cashfree
→
Outstanding updated
→
Receipt sent
11. Closure
All EMIs paid
→
Status → COMPLETED
→
NDC (No-Due Certificate) generated
→
Reloan eligibility check
🆔

KYC / Onboarding Wizard Flow

los-webv1's borrower onboarding wizard, step by step

This entire wizard runs in los-webv1 (WorkflowPage + features/workflow/*), not in the staff CRM. Every step below is brand-configurable — a brand can skip, require, or reorder steps via BrandUserWorkflowEnum / workflow_steps config — and each step renders through one of up to ~30 per-brand UI templates (t1…t30). The order below is the typical current sequence; treat it as a default, not a fixed contract.
1

Basic Info + Mobile OTP

Borrower enters phone number, passes Cloudflare Turnstile captcha, receives and submits OTP → account/session created, access + refresh tokens issued.

2

Email Verification

Borrower enters email → OTP/link verification confirms ownership.

3

Geo-location

Browser geolocation permission prompt captures the borrower's current location — feeds fraud/risk signals and address stability checks.

4

PAN / KYC Details

Borrower enters PAN → verified through a fallback vendor chain (Digitap → ScoreMe → Signzy, "PAN Details Plus") with per-vendor answer caching and duplicate-PAN guarding → name/DOB pre-filled.

5

Bank Account Verification

Borrower enters account number + IFSC → penny-drop verification confirms the account holder name matches the PAN name.

6

Income Proof

Either a bank-statement upload (parsed for salary credits/EMI obligations) or an Account Aggregator consent flow (RBI-framework, via Finduit/FIU + Xaler) — brand-configurable which is offered. See Account Aggregation Flow.

7

Aadhaar Verification

DigiLocker pull via Digitap v2 or Signzy (redirect-based flow) fetches Aadhaar/official documents directly from government sources — bypasses manual document review.

8

Liveness Capture

AWS Amplify face-liveness capture (ui-react-liveness) plus a webcam selfie/video, checked via AWS Rekognition — confirms a live person matching the KYC photo, not a static image.

9

Employment Details

Employer name, UAN, salary, joining date — cross-checked against EPFO where available.

10

Alternate Phone Number

Borrower adds a secondary contact number — used for collections/verification if the primary is unreachable.

11

Documents Upload

Remaining supporting documents (payslips, address proof, etc.) uploaded to S3 private bucket, status PENDING until staff review.

12

Existing-Loan / Debt-Consolidation Declaration

Borrower declares existing loans with other lenders — feeds the debt-consolidation product path (LoanConsolidationLine) if applicable.

13

Add Guarantor(s)

If required, borrower invites a guarantor by phone number. The guarantor logs in with their own OTP session (UserRoleEnum.GUARANTOR) and completes only their own KYC/consent subset — they never see the borrower's /apply screen.

14

BRE Wait Screen

Borrower sees a waiting screen while the underwriting-analysis orchestrator auto-screens the file. Outcome routes the borrower to /rejected (hard/BRE-reject), /review (soft-reject, manual pending), or onward to the loan-amount/tenure offer step. See Loan Application Flow.

📄

Loan Application Flow — The Core Pipeline

The full stage pipeline a loan moves through, application to closure

This is the single biggest piece of drift fixed in this refresh A loan is driven by two independent axes: status (what the loan is — PENDING, APPROVED, ACTIVE, REJECTED, etc.) and currentStage (who currently owes work on it). The stage pipeline below has grown significantly since this doc was last accurate — it is missing a standalone CREDIT stage (migration 110), ESIGN as its own stage rather than folded into approval (migration 128), and the optional ESTAMP and MANDATE stages, in older drafts. The current pipeline is shown below.
APPLICATION
Loan created, status PENDING
BRE Auto-Screen
Smart/CRIF/Neetix/Marketing BRE — the gate
SALES
los-partner queue, status unchanged
CREDIT
Migration 110 — underwrites before visit/sanction
↓ explicit workflow move
FIELD_VISIT
Brand-gated, default off — skips to MANAGER if off
MANAGER
Decision point — status actually changes here (Approve/Reject)
ESIGN
Migration 128 — own stage, not folded into approval
↓ optional branches, then all agreements SIGNED
ESTAMP (optional)
Migration 177/178 — per-loan opt-in, off by default
MANDATE (optional)
Migration 172 — UPI Autopay authorization wait
DISBURSEMENT
status → AWAITING_DISBURSEMENT, then payout queued
POST_DISBURSEMENT
status → ACTIVE
CLOSED
COMPLETED / SETTLED / WRITE_OFF

📋 Stages vs. Status

loan_stage_enum (who owes work): APPLICATION, SALES, CREDIT, FIELD_VISIT, MANAGER, ESTAMP, ESIGN, DISBURSEMENT, POST_DISBURSEMENT, COLLECTION_FIELD_VISIT, CLOSED, MANDATE. loan_status_enum (what the loan is): PENDING, BRE_APPROVED, APPROVED, ACTIVE, PARTIALLY_PAID, AWAITING_DISBURSEMENT, DEFAULTED, REJECTED, SOFT_REJECTED, HARD_REJECTED, BRE_REJECTED, CANCELLED, COMPLETED, SETTLED, WRITE_OFF, ON_HOLD, DORMANT, DELETED. loan_tasks is the append-only history of every stage entered — at most one open task per (loan, stage).

🚦 BRE Auto-Screen Branches

Path A (BRE_APPROVED, or SOFT/BRE_REJECTED if the brand's allow_restart flag permits) → straight to the human pipeline (SALES or FIELD_VISIT, brand-configured). Path B (DELETED, DORMANT) → back to PENDING, re-screened. Path C (HARD_REJECTED) → terminal; only a super-admin can revert it (hard_reject_revert_super_admin_only), which then rejoins Path B.

📊 Bank Statement / Income-Proof Analysis (feeds CREDIT)

During onboarding, the borrower supplies income proof either as a bank-statement upload (analyzed by CART, Finbox, or ScoreMe depending on brand config — salary credits, EMI debits, balance trends, stored as a BdaReport/BSA report) or via an Account Aggregator consent flow. This data is available to CREDIT_EXECUTIVE staff during the CREDIT stage and feeds the CAM Calculator (see CAM Calculator Flow).

🧮

Credit Assessment Flow

The unified underwriting orchestrator, run by CREDIT_EXECUTIVE staff in los-partner

Underwriting is now a unified multi-engine orchestrator (src/features/underwriting-analysis), not a single BRE call. Four engines can run against a brand's configuration: Smart BRE, CRIF BRE, Neetix BRE (all auto-run) and Marketing Analysis (manual trigger only). All four write into one shared assessment table (loan_underwriting_assessment), and a brand picks which engines are active via brand_providers BRE_ENGINE rows — a brand with zero engines configured runs zero BRE checks (a silent no-op worth flagging operationally).
Loan reaches CREDIT stage
Status: PENDING
Fetch Credit Reports
CIBIL (Signzy+native), CIR Pro V2, Equifax
Run Enabled BRE Engines
Smart / CRIF / Neetix (auto) + Marketing (manual)
APPROVED / REJECTED / MANUAL_REVIEW
+ approved amount, risk grade A–F
↓ one evaluation record per loan
Evaluation Checklist
Each item ELIGIBLE / NOT_ELIGIBLE
CAM Calculator
FOIR, avg salary, eligible amount
CREDIT_EXECUTIVE Override
Human can override any engine's verdict, with comment
Forwarded to MANAGER
Decision point — see Loan Application Flow
Sanctioning is a separate step after credit assessment — see Sanction Approval Flow below. This BRE pipeline is the internal credit team's decisioning tool, run inside los-partner; it is not a self-serve pre-qualification widget exposed to borrowers.
✅

Sanction Approval Flow

A separate MANAGER-stage review step, after CREDIT has produced its evaluation

Sanctioning happens at the MANAGER stage — it is a distinct step from the CREDIT stage's BRE/evaluation work (see Credit Assessment Flow). This is where loans.status actually changes: approve closes the task APPROVED and stamps approvalDate; reject sets SOFT_REJECTED/HARD_REJECTED/BRE_REJECTED and closes the task REJECTED. (Open question carried over from the underlying schema: whether this is a single-tier or two-tier CX-then-SM/SH approval — the schema keeps separate CX and SM/SH approval + amount columns, so brand configuration may determine which applies.)
Sanction Workflow — Role by Role (all in los-partner)
Credit Executive
Opens /:brandId/credit-executive
→
Reviews BRE outcome, CAM, bureau report
→
May override evaluation items with comment
→
Forwards loan to MANAGER stage
Sanction Manager
Opens /:brandId/sanction-manager
→
Reviews all loan docs, credit exec notes, CAM
→
Can approve (with conditions) or reject
→
Escalates to Sanction Head if required
Sanction Head
Final authority review (brand-configured threshold)
→
Approves → loans.status = APPROVED
→
approvalDate stamped
→
Notification sent to borrower
System (los-backend)
Creates LoanStatusHistory / loan_tasks entry
→
Loan moves to ESIGN stage (own stage since migration 128)
→
LoanAgreementProvisioner creates agreement records
→
SMS/Email: "Your loan is approved"
✍️

E-Signature Flow

ESIGN is its own pipeline stage (migration 128) — one or more agreements per brand's signing package

Once MANAGER approves, the loan moves into the ESIGN stage. LoanAgreementProvisioner creates one loan_agreements row per entry in the brand's configured signing_package — a brand can require multiple documents (main agreement + annexures), each routed to a provider independently. Annexures marked requiresSignature = false never block stage completion. Optional ESTAMP (stamp duty, off by default) and MANDATE (UPI Autopay authorization) stages can sit between ESIGN and DISBURSEMENT.
1

Agreement PDF Generated

Backend uses PDFKit/Puppeteer to generate each required loan agreement PDF with borrower details, loan amount, tenure, interest rate, repayment schedule, T&C. Saved to S3 private bucket.

2

E-Sign Request Sent

Backend routes each agreement to the brand-configured provider — SignDesk, Signzy v3, Digitap eSign, or Doqfy — with the PDF. Provider sends a signing link to the borrower's registered mobile/email.

3

Borrower Signs (in los-webv1 or via link)

Borrower opens the link, reviews the agreement, signs with Aadhaar OTP-based e-signature. The signature is legally valid under India's IT Act.

4

Webhook Confirmation

Provider sends a webhook to los-backend with signing status per agreement. Once every signature-requiring agreement in the package is SIGNED, the ESIGN stage completes and status = AWAITING_DISBURSEMENT — see Disbursement Flow.

💸

Disbursement Flow

A deliberately separate, queued step from the workflow's stage-advance

Deliberate design rule — money-safety pattern Disbursement is a separate queued job (AutoDisbursementJob, gated by BrandConfig.auto_disbursement_enabled) from the workflow's stage-advance transition — by design, a stage-advance must never itself trigger a payout. Once every signature-requiring ESIGN agreement is SIGNED (and optional ESTAMP/MANDATE steps clear), status becomes AWAITING_DISBURSEMENT; actual money movement happens as a separately-triggered payment_request (type DISBURSEMENT). This same "don't let the automatic step move money" principle also shows up in e-stamp's NEEDS_REVIEW terminal state and UPI Autopay's no-auto-retry-on-ambiguous-debit rule.
Disbursement Process (los-partner: LOAN_OPS staff)
Loan Ops Staff
Opens :brandId/loans-ops/pending-disbursement
→
Sees pending disbursement queue
→
Verifies bank details + penny drop
→
Approves / rejects, or bulk-disburses
los-backend
AutoDisbursementJob picks up queued payout
→
Bank transfer initiated (disbursement banking rails)
→
Creates PaymentDisbursalTransaction leg(s), tracked in a disbursement batch with UTR
→
On success: status → ACTIVE (POST_DISBURSEMENT stage)
Post-Disbursement
loan_emi_schedule created (amortization plan)
→
SMS: "Loan disbursed ₹X"
→
loan_ledger entry created
→
UPI Autopay mandate offered if brand enabled

🔀 Single-Leg vs. Multi-Leg Disbursement

A plain loan disburses as one leg. A debt-consolidation loan (loan_type_id = 98, is_debt_consolidation_enabled per brand) disburses as multiple ordered legs (leg_index) against each loan_consolidation_line — e.g. paying off several existing lender balances directly before any remainder reaches the borrower. Each leg is tracked independently in the disbursement batch with its own status (PENDING → INITIATED → SUCCESS/FAILED/RETRYING/TIMEOUT/PARTIALLY_SETTLED) and UTR.

💼

Collection Flow (Collection V2)

Repayment management from pre-due to write-off, queued by stage in los-partner

Collections is organized as five stage-based queues in los-partner: all, pre-collection, post-collection, NPA-collection, and legal-action-collection, plus a follow-up calendar and dedicated field-visit workflows (collection-field-visits). This COLLECTION_FIELD_VISIT stage is distinct from the pre-disbursement FIELD_VISIT stage covered in the Loan Application Flow — a single loan can pass through both over its lifetime, worked by different teams.
Active Loan
Disbursed, repaying
Pre-Collection Queue
Days before/around due date
Reminders Sent
Per-brand cadence — SMS + WhatsApp + Email
Customer Pays?
Manual, or UPI Autopay debit
EMI Marked Paid
loan_ledger updated
↓ No payment
Post-Collection Queue
Past due date, DPD accruing
COLLECTION_EXECUTIVE Assigned
Three-tier allocation model — see Auto-Allocation
Call / Follow-up Calendar
Acefone (human) or Sphoro Voice (AI dialer)
PTP Logged
Promise-to-pay in CollectionRemarks
↓ DPD ≥ npa_min_dpd (default 90 days)
NPA Collection Queue
NPA_EXECUTIVE staff
Legal-Action Collection Queue
Collection Head reviews escalated cases
Settlement Offer
Reduced amount, status → SETTLED
Write-Off
status → WRITE_OFF, if unrecoverable

📞 Telephony in Collection

Collection executives dial via Acefone (human-agent telephony, click-to-dial from the loan/user profile) or, increasingly, Sphoro Voice — an AI voice agent that both places outbound AI-dialed calls (no human) and offers in-browser AI voice chat, configured per-brand and per-telecaller caller-ID. Both share the user_calls schema. Backend creates a UserCall record per call; events (connected, ended, etc.) trigger UserCallEvent records; recordings link back to the customer's profile.

💳

Payment Processing Flow

How money flows through the system — one-time collection vs. recurring Autopay

One-time repayment goes through Cashfree, Razorpay (+v2), Easebuzz, PayU, or Paytring (brand-configurable). Recurring EMI collection can instead use UPI Autopay (Cashfree / Razorpay / PhonePe mandates): a mandate is created, the borrower authorizes it via a ₹1 payment, and a daily 8am IST cron finds loans due the next day with an active mandate and triggers the debit automatically — manual collection is frozen while a debit is in flight to prevent double-collection.
1

Payment Initiated

Borrower pays via the gateway checkout page (from los-webv1). OR a collection agent triggers a payment link from los-partner. OR an UPI Autopay mandate debit fires from the cron. Creates PaymentRequest record with PENDING status.

2

Gateway Processing

Payment gateway processes the transaction. Customer authorizes via UPI, card, or netbanking. Gateway holds the transaction in PROCESSING state.

3

Webhook Callback

Gateway sends a webhook to POST /partner/brand/:brandId/payment/webhook. Backend validates webhook signature. If SUCCESS: creates PaymentCollectionTransaction, updates Loan.outstandingAmount, marks EMI as paid in RepaymentTimeline.

4

Approval Queue (if applicable)

Certain payment types require manual approval. Loan Ops staff see these in the /:brandId/payment-approval queue. They review UTR number, amount, and approve or reject.

5

Ledger + Notifications

Creates LoanLedgerEntry for financial tracking. Sends payment receipt via SMS + email. If all EMIs paid: triggers loan closure flow → NDC generation → NOC email sent via SQS queue.

🔐

Authentication Flow (Both Sides)

los-webv1: OTP-only. los-partner: five distinct login methods.

These are very different flows — don't conflate them los-webv1 (borrower) has exactly one login method: phone OTP behind a Turnstile captcha. los-partner (staff) supports five selectable identifier+credential flows, rendered across eight per-brand visual login-page variants (loginV1…loginV8).

los-webv1 — Borrower Auth (Phone OTP + Turnstile)

1

Enter phone number on /phone-verification, pass Cloudflare Turnstile captcha

2

Backend generates OTP → sends via SMS (MSG91/Gupshup/TrustSignal/SMSGatewayHub/Nimbusit)

3

Borrower enters OTP → validated → access + refresh tokens issued (cookie + Redux)

4

A shared axios interceptor silently refreshes on 401; on refresh failure, force-logout + redirect to /phone-verification. This is the only login method — no password/TOTP/SSO exists on this app.

los-partner — Staff Auth (5 methods, 8 UI variants)

1

Password: POST /auth/partner/login — identifier + password + deviceId, bcrypt-compared.

2

OTP: send-login-otp → verify-login-otp.

3

TOTP (authenticator app): checks enrollment → issues a QR code to scan if not enrolled → verify-totp-login thereafter.

4

Admin-issued sign-in code: a 12-char one-time code an ADMIN/SUPER_ADMIN generates for a staff member (15min/1hr/24hr expiry, single-use, SHA-256 hashed at rest, blocked for ADMIN/SUPER_ADMIN accounts themselves to prevent impersonation).

5

Reset: send-reset-password-email → reset-password, plus change-password while authenticated.

6

Every method sends deviceId (FingerprintJS) for device tracking. Token stored in sessionStorage; a 403 PUNCH_IN_REQUIRED response can block the whole UI until the staff member punches in for attendance (brand-configurable).

📢

Notification & Communication Flow

How messages reach customers and staff

Multi-Channel Communication Pipeline
Trigger
Cron job fires
→
API event (loan status change, payment received, etc.)
→
Manual trigger from portal
Queue
Job published to RabbitMQ
→
Job includes: userId, channel, templateId, params
→
Worker picks up job
Channel Select
SMS → Gupshup / MSG91 / Hub / NimbusIT
|
Email → SendGrid / Brevo / Zepto
|
WhatsApp → AiSensey
Delivery
Primary provider called
→
Failed? → Failover to next provider
→
Log delivery in DB
→
Create UserNotification record
What's actually live across WhatsApp/chat — corrected 2026-10-01
  1. WhatsApp Flows (live) — a full conversational loan-application journey inside WhatsApp itself, using Meta's encrypted Flow protocol (direct calls to graph.facebook.com/v21.0/{PHONE_NUMBER_ID}/messages). Collects bank account, runs DigiLocker + Account Aggregator consent, and submits a loan application without the borrower ever leaving WhatsApp.
  2. Web chatbot widget (live) — an intent-classified chat widget on the public web (EMI calculation, eligibility check, loan application, tracking), using plain OpenAI (gpt-4o-mini via api.openai.com) — not Azure, despite a stale code comment claiming otherwise.
  3. crm-chatbot (live, unrelated) — a thin proxy from los-partner to a separate "Central Chatbot" microservice so staff can ask an AI assistant questions inside the CRM. No WhatsApp involvement despite the directory name.
  4. WhatsApp CRM staff inbox (not merged) — a two-way conversation/inbox for staff to message borrowers directly has a full, real commit history, but it lives entirely 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. Treat as in-development.
Outbound WhatsApp message delivery (reminders, etc.) goes through AiSensy only — it is the sole registered provider in the generic WhatsApp delivery abstraction. Meta Cloud API is used solely by the separate WhatsApp Flows feature above; Gupshup's provider in this codebase is SMS-only and has no WhatsApp code path.
🎯

Auto-Allocation Flow

How work is assigned to staff — a three-tier permission model

Allocation-eligibility runs on a three-tier permission model, separate for fresh vs. repeat work: FRESH_ALLOCATION / REPEAT_ALLOCATION (a user can receive newly-allocated work), ALLOCATE_FRESH / ALLOCATE_REPEAT (a user can assign currently-unowned work to someone else), and REALLOCATE_FRESH / REALLOCATE_REPEAT (a user can move work that's already owned by someone). These are independent permissions layered on top of role — allocation checks role and permission together, and supervisory roles (managers/heads) are deliberately excluded from receiving allocations even if they hold the permission.

📋 Lead / Sales Auto-Allocation

When a lead converts or a loan application is submitted, the allocation engine assigns it to an available SALES-role user with FRESH_ALLOCATION permission, using round-robin/workload balancing. Checks PartnerUnavailabilityDate to skip staff on leave. Managers with ALLOCATE_FRESH/RELOCATE_LEAD can manually reassign unowned leads.

🔁 Reallocation

A manager or head holding REALLOCATE_FRESH/REALLOCATE_REPEAT can move a loan or lead away from its current owner to another eligible staff member — distinct from assigning previously-unowned work, and a stronger permission (moving someone else's active work). Applies symmetrically on the sales and collection desks.

💼 Collection Auto-Allocation

When a loan becomes overdue, the collection allocation engine assigns it to a COLLECTION_EXECUTIVE with FRESH_ALLOCATION/REPEAT_ALLOCATION based on: geographic proximity, current collection load, and performance ratings from partner_user_rating_matrix. NPA and legal-action queues follow the same permission tiers.

🗺️

Complete Data Flow Map

Where data comes from and where it goes

📥 Inbound Data Sources

Customer web app inputs Partner portal actions Payment gateway webhooks E-sign webhooks (Signzy/SignDesk) Digitap KYC responses CIBIL/Equifax credit reports CART/Finbox BSA results EPFO employment data Penny drop verification Account Aggregator data Acefone call events

📤 Outbound Data Flows

API responses → React frontend KYC documents → S3 private Brand logos → S3 public Loan agreement PDFs → S3 + eSign SMS → Multiple providers Email → SendGrid/Brevo/Zepto WhatsApp → AiSensey Audit events → SQS Job payloads → RabbitMQ Disbursements → IDFC/ICICI Reports CSV → Client browser
🔒

Roles × Features Access Matrix

los-partner's staff roles — full lifecycle coverage, not just loan ops + collections

Access is permission-driven, not role-driven A Role (Sales, Credit Executive, Sanction Manager, etc.) drives classification and allocation-eligibility only. A separate, fine-grained Permission (~100 distinct values, e.g. CUSTOMER, LOANS, DISBURSE_LOAN, LOAN_OPS, BRAND_SETTINGS) is the actual access gate. A user with role "Sales" but no matching permission has no access at all; a user with an unusual role but the right permission can still get in. The matrix below shows the typical role↔feature mapping, but treat it as a simplification of the real permission system.
Feature Super Admin Admin Sales Sales Mgr/Head Credit Exec Sanction Mgr/Head Loan Ops Coll. Exec Coll. Mgr/Head NPA Exec HR
Dashboard ✓✓✓✓ ✓✓✓✓ ✓✓✓
Leads Queue ✓✓✓✓ ———— ———
Customer / Loans List ✓✓✓✓ ✓——— ———
Credit / BRE Evaluation (CREDIT stage) ✓✓—— ✓——— ———
Sanction / MANAGER stage ✓✓—— —✓—— ———
Disbursement Queue ✓✓—— ——✓— ———
Pre-/Post-Collection Queues ✓✓—— ———✓ ✓——
NPA / Legal-Action Collection ✓✓—— ———— ✓✓—
Write-Off Authority ✓✓—— ———— ✓——
Coin Wallet (staff incentive, private beta) ✓✓✓✓ ✓✓—✓ ✓——
Attendance / Punch-In Admin ✓✓—— ———— ——✓
Settings / Brand Config ✓✓—— ———— ———
Reports (per-report permission) ✓✓—✓ ———— ✓——
Staff Management (sign-in codes, roles) ✓✓—— ———— ———

Reports are always assigned as independent permissions, not tied to role. CUSTOMER is a parent permission that auto-expands to 8 bucket permissions (pending/active/on-hold/BRE-rejected/hard-rejected/deleted/dormant/soft-rejected) — most users get CUSTOMER alone rather than individual buckets.

🔌

Integrations Map

Which external API is used at which stage

🆔 KYC Stage

Digitap — PAN verify Digitap — Aadhaar OTP DigiLocker 2.0 — Official docs Penny Drop — Bank verify Mobile-to-PAN — Fraud check Mobile-to-Address — Verify EPFO/UAN — Employment Google Maps — Geocoding

📊 Credit Assessment Stage

Equifax — Credit report CIBIL — Credit score CIR Pro V2 — BRE CART — Bank statement analysis Finbox — BSA (alternate) ScoreMe — Credit scoring + BDA Account Aggregator — Bank data

✍️ Approval & eSign Stage

Signzy V3 — e-Signature SignDesk — e-Signature (alt) PDFKit/Puppeteer — Agreement PDF AWS S3 — Document storage

💸 Disbursement Stage

IDFC Bank — Transfer ICICI Bank — Transfer (alt) Penny Drop — Final verify Lendbox — Co-lending

💳 Repayment/Collection Stage

Razorpay — Collection Cashfree — Collection (alt) Paytring — Collection (alt) Razorpay Autopay — Mandate Acefone — VoIP calls Stringee — Call center

📱 Communication (All Stages)

SMS Gateway Hub Gupshup MSG91 NimbusIT SendGrid Brevo Zepto AiSensey (WhatsApp)
🔒

Security Layers

Every security mechanism in the platform

Known risk areas, current as of 2026-09-30 los-backend exposes 101 public (unauthenticated) routes — grouped as Auth (20, login/OTP/SSO), Account Aggregator (28), Payments (12, webhook callbacks + OTP-gated public repayment inquiry), Grievance Redressal (3) and Whistleblower Reporting (3, added 2026-09-17), Webhooks & Health (20), and Web/Misc (16). Two flagged risks worth carrying into any security review: the entire Account Aggregator controller is public at class level (not just specific consent-callback routes), and there is generally no ownership check on :userId routes — worth confirming before treating any :userId-scoped endpoint as safe by default.

🔏 Data Protection (new)

Field-level PII encryption (PII_DEK_1 / PII_INDEX_KEY) Independent secret pre-load, separate from AWS Secrets Manager fetch Read-replica DB roles: standard + PII-redacted

🔑 Authentication

JWT access + refresh tokens bcrypt (12 salt rounds) OTP with 5min TTL Token blacklisting on logout

🛡️ Authorization

Permission-driven (~100 fine-grained permissions), not role-driven Global AuthGuard + @AuthType (web/partner/public/api-key/credential) brandId isolation Route-level guards + PunchInGuard

🌐 Network Security

Helmet HTTP headers CORS whitelist Rate limiting (ThrottleGuard) HTTPS enforced

📦 Data Security

S3 private bucket encryption Presigned URLs (time-limited) 50MB upload limit Input validation (class-validator)

📱 Device & Session

Device fingerprinting (FingerprintJS) Activity session tracking Inactivity alerts Login logs

📝 Audit & Compliance

All API calls logged Audit events to AWS SQS User action tracking Webhook signature validation
⚡

Performance Architecture

How the platform handles scale

🚀 Frontend Performance

Vite build (code splitting) React 19 (concurrent features) lodash.debounce on search inputs Pagination on all lists Lazy loading of routes Redux for minimal re-renders

⚡ Backend Performance

PM2 cluster × 2 instances Redis caching (TTL-based) PostgreSQL GIN/TRGM indexes gzip compression Async queue processing BigInt serializer

📊 Database Performance

Prisma optimized queries GIN indexes for text search TRGM for fuzzy name matching Foreign key indexes Connection pooling

🔄 Async Performance

RabbitMQ decouples heavy operations AWS SQS for durable queues Trigger.dev for managed jobs Cron worker on separate process Graceful shutdown handling

🏁 Summary — The Complete 8byte LOS Platform

This platform is a full-stack, production-grade loan origination system that covers every aspect of the Indian NBFC lending process:

Multi-brand isolation Role-based access (9 roles) Complete KYC automation (10+ providers) Credit assessment (CIBIL + Equifax + BRE) Multi-gateway payments (5 gateways) Digital e-signature (Signzy + SignDesk) VoIP call center integration Multi-channel communication (8 providers) AWS cloud infrastructure Real-time dashboards Comprehensive audit logging Background job processing Auto-allocation algorithms PM2 cluster deployment

The React frontend and NestJS backend are tightly coupled via a well-defined REST API, with JWT authentication, brand scoping, and role-based access enforced at every layer — from the Redux store and React Router guards in the frontend, all the way down to Prisma database queries filtered by brandId on the backend.

🔗

Account Aggregation (AA) Flow

RBI-framework consent-based financial data fetch via FINDUIT / CART providers

Account Aggregation (AA) is an RBI-mandated framework that lets users share their bank statement / financial data with lenders through a regulated consent journey — without sharing credentials. 8byte integrates with AA providers (Finduit/FIU and Xaler) via a dedicated module (src/external/aa). This flow can be initiated either by los-partner staff during underwriting (as described below) or directly by the borrower inside the los-webv1 onboarding wizard's income-proof step — see KYC Flow.
1

Credit Executive Initiates AA

From the loan detail page, a credit exec clicks "Initiate Account Aggregation". The frontend calls POST /partner/brand/:id/aa/consent-request with userId + loanId. Backend creates an AAConsentRequest record with status PENDING.

2

Consent Link Sent to Customer

Provider (FINDUIT/CART) generates a consent URL and sends it to the customer via SMS/WhatsApp. The AA consent record stores consentId, txnId, and the redirect URL for tracking.

3

Customer Approves Consent

Customer opens the link on their phone, authenticates with their bank's AA app (e.g. PhonePe, Perfios), and approves sharing 6–12 months of bank statement data. Consent status updates to APPROVED via webhook.

4

Data Fetch & Analysis

Backend automatically fetches the financial data from the AA provider once consent is approved. The data is stored and the credit exec can view the Bank Statement Analysis (BSA) report inside the loan profile — salary credits, EMI obligations, spending patterns.

5

Credit Assessment Integration

AA data feeds into the CAM Calculator (average salary, obligations) and the overall credit decision. The consent request list is available via GET /partner/brand/:id/aa/consent-requests with pagination and status filtering.

Provider: Finduit/FIU / Xaler Consent-based (RBI AA Framework) AAConsentRequest DB model Webhook status update Feeds into CAM Calculator
📋

Lead Management Flow

Facebook Ad leads → CSV import → match to users → auto-process

Lead Management handles inbound leads from Facebook Ad campaigns. Admins/Sales download lead CSVs from Facebook Ads Manager and upload them to the portal. The system matches, deduplicates, and processes leads.
1

CSV Upload

Admin or Sales team downloads the leads CSV from Facebook Ads Manager and uploads it via POST /partner/brand/:id/lead-forms/upload (multipart/form-data). Backend parses rows and stores each as a LeadForm record with status PENDING.

2

Deduplication Check

On upload, the system checks for duplicate entries (same phone/email within the same brand). Duplicates are marked with status DUPLICATE and excluded from further processing.

3

Sync / Process

Staff trigger sync via POST /partner/brand/:id/lead-forms/sync. The backend attempts to match each PENDING lead to an existing platform user by phone number. Matched leads get PROCESSED status; unmatched or errored leads get FAILED with an error message.

4

View & Filter

The Leads page shows paginated lead forms with search, status filter (PENDING / PROCESSED / FAILED / DUPLICATE), and stats cards (total / pending / processed / failed / duplicates). Staff can drill into each lead to see campaign info (ad ID, ad set, form name) and lead responses (salary, PAN, employment type).

5

Export & Bulk Delete

Leads can be exported as CSV (GET /lead-forms/export) for external use. Bulk delete is available via DELETE /lead-forms/bulk with an array of IDs. Organic leads (isOrganic=true) are tracked separately from paid campaign leads.

Source: Facebook Ads CSV upload → parse → store Status: PENDING / PROCESSED / FAILED / DUPLICATE LeadForm DB model Campaign tracking (adId, adsetId, campaignId)
🧮

CAM Calculator Flow

Credit Appraisal Memo — how credit executives assess loan eligibility

CAM (Credit Appraisal Memo) is the credit underwriting worksheet filled by a credit executive to formally compute the customer's loan eligibility. It captures salary data, FOIR (Fixed Obligation to Income Ratio), recommended loan amount, and repayment projections.
1

Open CAM Form

Credit executive opens the loan profile and navigates to the CAM Calculator tab. The frontend fetches any existing CAM via GET /loans/cam-calculator/:loanId — if one exists, the form is pre-populated.

2

Enter Salary Data

Exec enters up to 3 months of salary credit dates and amounts (salaryCreditDate1-3, salaryAmount1-3). The system auto-calculates avgSalary. The next pay date (nextPayDate) is also captured for disbursement planning.

3

Compute Eligibility

Based on avg salary and existing obligations (obligations), the system computes: eligibleFoir (allowed FOIR%), foirAchieved (current FOIR%), proposedFoir (after new loan), eligibleLoan (max loan based on FOIR), and roi (rate of interest).

4

Set Recommended Amount

Exec enters loanRecommended (which may differ from the customer's requested loanApplied). Disbursal date, repayment date, and tenure are also set. The repaymentData JSON captures the full EMI/repayment schedule.

5

Save & Submit

On save, the frontend calls POST /loans/brand/:brandId/cam-calculator/save. Backend upserts the CAMCalculator record linked to loanId + userId + partnerUserId. The saved CAM becomes part of the loan file reviewed by sanction managers.

Role: Credit Executive CAMCalculator DB model Fields: avgSalary, FOIR, eligibleLoan, ROI Linked to loanId + userId Feeds into sanction decision
⏰

Reminder Scheduling Flow

How staff create, schedule, and track customer reminders

Reminders are targeted, scheduled messages sent to specific customers through a chosen channel (SMS, WhatsApp, Email) at a future time. They're created by collection or ops staff and tracked centrally in the Reminders module.
1

Create Reminder

Staff opens the Reminders page and clicks "Create Reminder". They select a user (customer), choose a channel (SMS / WhatsApp / Email), pick a message template (templateCode), set a future scheduledAt timestamp, and optionally fill template variables in the payload map.

2

Store in DB

The frontend calls POST /partner/brand/:id/user-reminders. Backend creates a UserReminder record with status PENDING. The record stores userId, channel, templateCode, scheduledAt, and payload.

3

Cron Job Dispatch

A background cron runs every minute (@Cron(CronExpression.EVERY_MINUTE)) and polls for reminders where scheduledAt ≤ now and status = PENDING. It dispatches the message via the appropriate provider (MSG91, Gupshup for SMS; AiSensey for WhatsApp; SendGrid for Email) using the template code.

4

Status Update

After dispatch attempt, status updates to SENT (success) or FAILED (error). If a providerMessageId was specified during creation, it's stored for delivery tracking. Every status change is audit-logged.

5

Monitor & Audit

Staff views all reminders via GET /partner/brand/:id/user-reminders with filters: channel, status, date range, search. The Audit Log for each reminder (GET /user-reminders/:id/audit-logs) shows every state transition with timestamps and actor.

Channels: SMS / WhatsApp / Email UserReminder DB model Status: PENDING → SENT / FAILED Cron-based dispatch Full audit log per reminder
📞

Acefone VoIP Click-to-Dial Flow

End-to-end flow: staff initiates a call to a customer from the partner portal

Acefone (and Stringee as secondary) is the VoIP provider integrated into the partner portal. Staff can make calls directly from any loan/user profile without leaving the browser. Calls are logged automatically with duration, disposition, and call recording links.
1

Brand Enables Dialer

Admin enables dialer via Brand Settings → Acefone configuration (API credentials, extension numbers). The AcefoneDialerProvider in the React app wraps the entire application and initializes the dialer SDK on mount.

2

Staff Clicks Call Button

On any user/loan profile page, staff clicks the phone icon next to the customer's number. The useAcefoneDialer hook calls initiateCall() which posts to /acefone/dialer/initiate with userId, partnerUserId, brandId, and optional loanId.

3

Acefone API Call

The backend forwards the click-to-call request to Acefone's API using the configured credentials. Acefone bridges the call — first calling the agent's extension, then dialing the customer when the agent answers.

4

Call Logs Auto-Saved

After the call ends, Acefone sends a webhook to POST /acefone/dialer/outbound. Backend stores the call log — duration, call status (answered/missed/busy), recording URL — linked to the user/loan.

5

View History

Call logs are viewable per user (GET /acefone/dialer/user/:userId/calls) and per partner agent (GET /acefone/dialer/partner/:partnerUserId/calls). Individual call details via GET /acefone/dialer/call/:callId. Stats per user/agent via the /stats endpoints.

Provider: Acefone (primary) / Stringee (secondary) Click-to-call from portal Auto call-log via webhook AcefoneDialerProvider context CDR reporting
📊

Report Generation Flow

How reports are generated, what types exist, and how they're exported

The Reports module provides data exports for analytics, compliance, and collections follow-up. All reports are date-range filtered and available as both paginated views and CSV downloads. Reports are restricted to Admin / Super Admin roles.
The backend exposes 29 report types across three categories: User/Loan, Collection, and Marketing/Credit.

📋 User & Loan Reports

master-report — full user+loan dump (PAN, Aadhaar, employment, bank, references, all loan statuses).

disbursed-loan-report, non-disbursed-loan-report, disburse-non-disburse-report — disbursement tracking.

active-loans-by-due-date-report, completed-loan-with-no-repet-report, loan-close-report, outstanding-data-report, reject-report, total-approve-sanction-report, affiliate-report, login-sessions-report.

💼 Collection Reports

master-collection-report — overdue loans, amounts, agent assignments.

collection-loan-report, collection-due-report, collection-loan-report-by-approved-date — per-loan collection views.

collection-allocation-executive-report, credit-executive-allocation-report, collection-remarks-report, total-recovery-report, field-visit-report.

📣 Marketing & Credit Reports

marketing-report, internal-marketing-report, internal-marketing-analysis-report — lead funnel and campaign data.

daily-marketing-mis-report — daily MIS snapshot.

lead-total-report, cic-report (CIBIL/Equifax bureau pulls), equifax-credit-report, transunion-report.

1

Select Report Type & Date Range

Admin opens the Reports page, selects report type from dropdown (e.g. master-report, marketing-report, collection-loan-report, disbursed-loan-report), and sets fromDate / toDate. There are 29 report types total.

2

Fetch Data

Frontend calls GET /partner/brand/:id/report/:reportType?fromDate=&toDate=. Backend queries the DB with date filters and returns typed arrays — MasterReportUser[], MarketingReportItem[], CompletedNoRepaymentReportItem[], or BaseReportItem[] for other types.

3

Display & Export

Data renders in a table. Staff can export as CSV via GET /report/:reportType/csv or download via GET /report/:reportType/download. Both return a stream — browser triggers file download. The master report also supports POST /master-report/email for email delivery of large datasets.

29 Report Types Date-range filtered CSV + download export Admin / Super Admin only Streaming response for large datasets
🔁

Reloan Automation Flow

A fully rule-based repeat-borrower decision engine — no manual step unless it routes there

New capability — no manual credit step for most repeat borrowers When an existing borrower who completed a previous loan applies again, the ReloanAutomationService auto-decides APPROVED / PENDING / REJECTED without a human in the loop, unless the file routes to manual review. Every decision — eligible or not — is logged to loan_automation_decision (automation_type = RELOAN) for RBI-compliance audit purposes.
1

Pre-checks & hard stops

Missing required data or a migrated previous-loan record routes to manual review. Immediate REJECTED if: the previous loan wasn't COMPLETED, its closure wasn't NORMAL (i.e. WRITE_OFF/SETTLEMENT), or DPD on the previous loan exceeded 30 days.

2

Recency & AA-approval time bucket

More than 90 days since the previous disbursement → manual review even if otherwise eligible. Time bucket is measured from the AA approval date (not disbursement date): under 90 days continues the automated path; 90+ days routes to manual review.

3

Due-date validation & AA availability

Requested due date must fall within ±3 days of a computed reference date, else manual review. No AA data on file → manual review, flagged BANK_STATEMENT_REQUIRED.

4

Salary-based amount cap

cap = max(min(prevAmount × 1.1, avgSalary × 0.6), prevAmount). Within cap → auto-APPROVED. Exceeds cap → manual review, flagged AMOUNT_INCREASE.

ReloanAutomationService ReloanBucketEnum: LESS_90_DAYS / MORE_90_DAYS loan_automation_decision (shared with fresh-loan BRE screening) Brand-configurable reloan settings
🔄

UPI Autopay Flow

Recurring EMI mandate collection — Cashfree / Razorpay / PhonePe

New capability UPI Autopay lets a brand collect EMIs automatically via a recurring debit mandate, instead of relying on the borrower to pay manually each cycle. A 3-provider abstraction (AutopayService.resolveProvider) picks between Cashfree, Razorpay, and PhonePe per brand.
1

Mandate created

A los-partner staff member triggers mandate creation on an active loan (or it's offered at disbursement time).

2

Borrower authorizes

Borrower completes a ₹1 authorization payment on a Cashfree/Razorpay/PhonePe checkout link. Webhook confirms mandate status ACTIVE (or BANK_APPROVAL_PENDING, which still allows disbursement to proceed if the loan is at that stage — see the optional MANDATE stage in Loan Application Flow).

3

Daily debit cron

An 8am IST cron finds loans due the next day with an active, not-yet-initiated mandate and triggers a debit.

4

Webhook resolves outcome

On success, the collection transaction can auto-approve (if COLLECTION_AUTO_APPROVE_ENABLED), unblocking ledger posting/closure logic. Manual collection is frozen while a debit is in flight to prevent double-collection — an ambiguous debit is never auto-retried (same money-safety principle as e-stamp's NEEDS_REVIEW state).

Cashfree / Razorpay / PhonePe PaymentAutopayTransaction / PaymentAuthState MANDATE loan stage (migration 172) Daily 8am IST debit cron
🪙

Coin Wallet Incentive Flow

A gamified staff rewards engine — additive only, never a write path into loan data

New capability (private beta), migration 233 Staff in SALES/SALES_MANAGER/CREDIT_EXECUTIVE/SANCTION_MANAGER/COLLECTION_EXECUTIVE/COLLECTION_MANAGER roles earn coins for actions like closing loans and successful collections, into a wallet tracking locked / available / reserved / debt / net balances. This is the platform's closest analogue to a "commission" system — an internal staff incentive program, not an external-partner payout ledger.
1

Coins earned

The coin engine reads loan_status_history/loan_tasks/payment tables as an event source (35 rule versions, FIFO coin lots with expiry) — it is strictly additive to CRM truth and can never block or roll back a business transaction. There is deliberately no public ingestion endpoint (prevents coin-minting abuse), and every coin ledger table is append-only (DB triggers reject UPDATE/DELETE).

2

Grant approval chain

Grant statuses: AWAITING_CONFIRMATION → UNDER_REVIEW/PENDING → CREDITED/APPLIED (or REVERSED/VOIDED). Discretionary/manual grants go through a maker-checker flow with velocity-review anti-gaming checks.

3

Redemption

Coins redeem via CASH_PAYROLL, VOUCHER, MERCHANDISE, or EXPERIENCE channels. Redemption statuses: PENDING_MANAGER → PENDING_FINANCE → APPROVED → IN_PAYOUT → FULFILLED (or REJECTED/CANCELLED/FAILED).

4

Wallet, leaderboard & admin

los-partner exposes a wallet view, a leaderboard, a manager/finance approvals queue, and brand-level coin-admin configuration (rate, min redemption, monthly cap, auto-approve threshold, tier system) — all gated behind CoinBetaRoute, a per-request server decision rather than a static permission check.

CoinWallet / CoinJournal (append-only) FIFO coin lots + expiry Maker-checker discretionary grants Private beta — CoinBetaRoute