Modules / los-backend

los-backend TECH

Scalable, multi-tenant NestJS API that powers every 8byte LOS surface — the borrower app (los-webv1), the staff back-office CRM (los-partner), WhatsApp/voice channels, and machine-to-machine partner integrations.

Ground truth as of 2026-09-30 · repo first commit 2025-04-16 · 3,981 commits since the last doc refresh (2026-04-07)
How to read this page This document was rebuilt directly from the current codebase (module structure, Prisma schema, route guards, git history) rather than from older internal notes, because the previous docs were six months stale. Where an internal md/*.md doc conflicted with the code, the code won — conflicts are called out inline.

01 Stack & architecture

A single NestJS service, deployed as two PM2 process groups, sitting in front of one large multi-tenant PostgreSQL database shared by ~15+ lending brands.

Framework
NestJS 11 (Express)
TypeScript, global api prefix, URI versioning
ORM / DB
Prisma 6 → PostgreSQL
248 models · 146 enums · 8,860-line schema · 240+ migrations
Cache / sessions
Redis (ioredis)
Toggle via REDIS_ENABLED; brand & master-data caches
Async / queues
AWS SQS (12 queues)
+ Trigger.dev for background jobs; RabbitMQ exists only as an unused prototype
Storage
AWS S3 (public + private)
Private bucket for PII/financial documents
Secrets
AWS Secrets Manager
Pre-loaded into process.env before Nest boots; fails fast if DATABASE_URL missing
PII protection
Field-level encryption
src/core/crypto · separate PII_DEK_1/PII_INDEX_KEY secret path
Runtime
PM2, 2 process groups
4-worker API cluster + 1 single-fork cron-worker

Multi-tenant by design

This is not a single-brand backend. main.ts's CORS allowlist alone names 15+ distinct lending brands (Qualoan, PaisaPop, Minutes Loan, Zepto Finance, Salary4Sure, FastSalary, SalaryBolt, SalaryBaba, JhatpatCash, CredNidhi, ShubLakshmi, PaisaAnytime, ToofanLoan, MySalaryLoan, SwiftPaisa, ExpressoLoan, DezireLoan). Brand is the tenant boundary in the schema, and nearly every business rule — BRE engines, field-visit requirement, reminder cadence, reloan config, workflow steps, coin program, auto-disbursement — is independently toggleable per brand via BrandConfig / brand_providers.

High-level architecture
graph TB subgraph Clients WEB["los-webv1
(borrower app)"] PARTNER["los-partner
(staff CRM)"] WA["WhatsApp / Voice
(Flows, CRM, Sphoro)"] MKT["Marketplace / affiliate
API integrators"] end GUARD["Global AuthGuard
@AuthType: public / web / partner / api-key / credential"] subgraph los-backend [los-backend — NestJS] APPWEB["app/web/**
borrower surface"] APPPARTNER["app/partner/**
staff + DSA surface"] FEATURES["features/**
~35 domain modules"] EXTERNAL["external/**
~35 vendor clients"] CORE["core/**
aws · crypto · queue · cron · communication"] end DB[("PostgreSQL
248 models, Brand-scoped")] REDIS[("Redis
cache / sessions")] SQS[("AWS SQS
12 queues")] VENDORS["Bureaus · KYC · e-sign
Payments · Telephony · WhatsApp"] WEB --> GUARD PARTNER --> GUARD WA --> GUARD MKT --> GUARD GUARD --> APPWEB GUARD --> APPPARTNER APPWEB --> FEATURES APPPARTNER --> FEATURES FEATURES --> EXTERNAL EXTERNAL --> VENDORS FEATURES --> CORE FEATURES --> DB CORE --> REDIS CORE --> SQS

02 Module / folder map

src/ top-level directories and what lives in each.

DirectoryPurpose
app/webBorrower/customer HTTP surface (@AuthType("web")). Sub-areas: bank, blogs, consolidation-lines, employment, guarantors, home, kyc, other-documents, personal-details.
app/partnerStaff CRM + channel-partner HTTP surface (@AuthType("partner")). Sub-areas: admin, brand, collection, completed, crm-chatbot, customers, dashboard, global-search, lender-options, loans, pan-search, report, role-groups, settings, users, users-reminders.
app/commonShared HTTP utilities (e.g. signed-URL endpoint).
common/Cross-cutting guards, filters, interceptors, decorators, logger, health checks.
core/awsS3 (public/private), SQS, Secrets Manager clients.
core/communicationMulti-provider email / SMS / WhatsApp dispatch abstraction.
core/cryptoField-level PII encryption + PII vault.
core/cronScheduled jobs — active only on the cron-worker PM2 process.
core/queueReminder queue dispatcher, SQS-backed.
core/redis, core/jwt, core/pdf, core/documents, core/workersInfra services.
core/brand-provider-keysPer-brand credential resolution for external vendors.
core/provider-alertsAlerting when a vendor integration starts failing.
external/*~35 third-party vendor HTTP clients — no Prisma access, pure integration layer.
features/*~35 domain features: loans, bre, esign, estamp, payment, coins, allocation, attendance, grievance, whistleblower, telephony, leads, referral, collectionRemarks, underwriting-analysis, and more.
shared/*Cross-feature domain services: user, brands, documents, loans read-models, devices, master-data cache, loginToken, partner-activity.
prisma/Schema (8,860 lines) + 240+ numbered migrations.
SAP/SAP GL accounting-export engineering spec + UAT export samples (AR_CU/AR_GL) — new capability, see §04.
deploy/rabbitmq/Prototype only. 3-node RabbitMQ cluster for a possible future SQS replacement — nothing in production publishes to it today.
wallet/Coin & Wallet Engagement System spec — source-of-truth for the features/coins implementation.
Loans domain decomposition features/loans/ was recently split into sub-modules (allocation, application, automation, cam, credibility, pd, queries, repayment, screening) — evidence of a significant refactor away from one large loans.service.ts.

03 API surface & auth

There is no literal api-web/api-partner/api-admin URL-prefix split in the code today. The real mechanism is a global AuthGuard driven by an @AuthType(...) decorator — a route with no decorator is unreachable (throws UnauthorizedException), so every route is deliberately classified.

AuthTypeWhoNotes
webBorrower/customer (los-webv1)Customer JWT. Onboarding KYC, home/tracking, blogs.
partnerInternal staff and channel-partner users (los-partner)The single largest surface — both actor types share it, disambiguated by role + permission, not by URL. Loans pipeline, customers, collections, completed loans, dashboards, reports, settings, role-groups, users, global search, CRM chatbot.
api-key / credentialMachine-to-machine integratorsx-api-key / x-api-credential headers — marketplace auto-login, affiliate lead handoff (e.g. loanwalle).
publicNo token101 public routes as of 2026-09-30 — see risk callout below.
Known risk — public surface Grouped: Auth (20 — login/OTP/SSO), Account Aggregator (28 — entire AA controller is public at class level), Payments (12 — webhooks + OTP-gated "Repay Now"), Grievance (3) & Whistleblower (3) — both added 2026-09-17, very recent — Webhooks & Health (20), Web & Misc (16). Flagged risks from the team's own md/public-routes/README.md: an unintentionally-public customer address endpoint, AA's blanket public decorator, unaudited webhook signature verification, and no ownership check on :userId routes generally.

Auth & permissions mechanism

  • AuthGuard (global) — JWT per surface via LoginTokenService/JwtService; an SSO SUPER_ADMIN token from a separate sso-los-login service is accepted on any non-public route ahead of normal auth.
  • PunchInGuard — second global guard enforcing staff attendance punch-in before certain partner actions.
  • RBAC is permission-driven, not role-driven. Role (Sales, Sales Manager, Credit Executive, Sanction Manager, Loan Ops, Collection Executive, NPA Executive…) drives allocation-eligibility only. Permission (fine-grained — CUSTOMER, LOANS, DISBURSE_LOAN, LOAN_OPS, BRAND_SETTINGS…) is the actual access gate. CUSTOMER auto-expands to 8 bucket permissions. Reports are independent permissions, not tied to role.
  • Partner sign-in codes — passwordless staff-recovery path: admin issues a 12-char one-time code (~59 bits entropy, SHA-256 hashed at rest), 15min/1hr/24hr expiry, single-use, revocable, explicitly blocked for ADMIN/SUPER_ADMIN accounts. One of the highest migration numbers in the schema — very recent.
  • Field-level PII encryption — src/core/crypto/, loaded via a secret independent of the main Secrets Manager fetch.

04 Third-party integrations

Vendor / capabilityPurposeModule
CIBIL (Signzy + native), CIR Pro V2, EquifaxCredit bureau reportsexternal/cibil, crif-bre, external/equifax
Neetix Bureau EvaluateAdditional bureau-evaluation BRE engineexternal/neetix-bureau-evaluate
Smart BRE (in-house)Rule-based risk scoring → approved amount/risk gradeexternal/smart-bre, orchestrated by features/underwriting-analysis
Signzy, Digitap, ScoreMePAN/KYC verification with fallback chain, DigiLockerfeatures/pan-details-plus, external/digiLocker2.0
SignDesk, Signzy v3, Digitap eSign, Doqfye-signature providers for loan agreementsfeatures/esign
DoqfyE-stamping of agreementsfeatures/estamp
Account Aggregator (Finduit/FIU + Xaler)Bank-statement consent & pull for underwritingexternal/aa
Cashfree, Razorpay (+v2), Easebuzz, PayU, PaytringOne-time payment collectionfeatures/payment/collection
Cashfree / Razorpay / PhonePe UPI AutopayRecurring EMI debit mandatesfeatures/payment/autopay
LendboxCo-lending partner (credit + disbursal UTR webhooks)features/lendbox-v1
HDFC, YES Bank (+ IDFC/ICICI implied)Disbursement banking railsmd/Integrations/*.md
AcefoneHuman-agent telephony/dialerexternal/acefone, features/telephony
Sphoro VoiceAI voice agent — outbound AI-dialed calls and in-browser AI voice chat, per-brand + per-telecaller caller-IDexternal/sphoro-voice, features/sphoro-voice
AiSensy, Meta WhatsApp Cloud, GupshupWhatsApp messaging providerscore/communication/providers/whatsapp
Meta WhatsApp FlowsFull conversational loan-application journey inside WhatsApp itselfexternal/flows
OpenAI (plain, not Azure)In-house web chatbot — intent classification only (step-driven chat flow, LLM just decides which step a free-text message maps to), gpt-4o-mini via the standard api.openai.com endpointexternal/chatbot
Central Chatbot (internal microservice)Separate AI assistant proxy for partner-staff Q&A inside the CRM — this backend runs no LLM logic itself, just forwards to CENTRAL_CHATBOT_URL. Unrelated to WhatsApp despite living in a directory named crm-chatbotapp/partner/crm-chatbot
Brevo, ZeptoMail, MSG91 / Gupshup / TrustSignal / SMSGatewayHub / NimbusitEmail / SMS deliverycore/communication
RiskcovryInsurance product integrationexternal/riskcovry
JuicyScore, fraud-detectorDevice / behavioral fraud scoringexternal/juicyscore, external/fraudDetector
AWS Rekognition, face-verificationSelfie / liveness KYC checkexternal/aws-face-liveness, external/face-verification
UCICCross-brand customer identity resolutionexternal/ucic
SAP GL NEWExports AR/GL accounting entries to SAP — stateful sync with reversalsapp/partner/report/sap-gl-export/*
AWS S3, SQS, Secrets ManagerStorage, async messaging, secretscore/aws

05 Database schema — domain summary

248 models · 146 enums, 8,860-line schema.prisma, unusually well documented with design-rationale doc-comments explaining why, not just what. Grouped by domain — see DB Reference for the full legacy field-level catalogue.

Loan lifecycle core
Loan, LoanDetails, LoanStatusHistory, LoanTask, LoanGuarantor, LoanConsolidationLine, Repayment, Tenure, LoanRule
EMI / repayment
LoanEmiSchedule, LoanLedger, LoanInstallmentAllocation, CostSummary, Deduction, EarlyRepaymentDiscount
KYC / verification
UserCibilReport, EquifaxCreditReport, BankAccountStatement, AaConsentRequest/DataSession/FinancialInsight, DigitapKycLog
Underwriting / BRE
LoanUnderwritingAssessment (shared by all engines), Evaluation/EvaluationItem, CamCalculator, ValidationExecution
e-Sign / e-Stamp
LoanAgreement, LoanAgreementReference, LoanEstampOrder, UnsignedDataAgreement
Payments / ledger
PaymentRequest, PaymentAutopayTransaction, PaymentDisbursalTransaction, Disbursement, AutoDisbursementJob
Partner / staff org
PartnerUser, PartnerUserBrandRole, PartnerRoleGroup+Permission, PartnerUserSignInCode, PartnerUserAttendanceDay
Users / customers
User, UserDetails, UserBankAccount, UserDevice, UserReminder, UserReloan, Employment, Payslip
Brand / multi-tenant
Brand, BrandConfig, BrandTheme, BrandProvider+Key, BrandReminderConfig, BrandReloanConfig, BrandWorkflowStep
Allocation
AllocationEvent, AllocationPolicy, LeadAllottedPartnerUserLog, LoanCollectionAllocatedPartnerLog
Leads / marketing
Lead, LeadComment, LeadUpload(Batch/Error), LeadOtpVerification, UTMTracking
Coin / gamification NEW
CoinWallet, CoinJournal, CoinGrant/LotConsumption (FIFO), CoinRule, CoinRedemption, CoinPayoutBatch
WhatsApp CRM SCHEMA ONLY
whatsapp_conversations/messages/templates, WhatsappReminderConfig, Brand.whatsapp_crm_enabled
Models exist in the schema but nothing in src/ references them — see the correction callout in §07.
SAP GL export NEW
SapCustomerAccount, SapExportBatch, SapExportState, SapGlVoucher, SapLoanBaseline
Grievance / compliance NEW
BrandGrievanceComplaint, BrandWhistleblowerReport, ComplaintOtpVerification (Sept 2026)
Master data
MasterBank, MasterNBFC, MasterState/District/Pincode, MasterValue (generic lookup)
Audit / ops infra
BrandAuditLog, ExternalApiLog (every vendor call logged), IdempotencyKey, QueueJobTrace, AsyncReportJob

Key enums

EnumValues / meaning
loan_status_enumWhat the loan is: PENDING, APPROVED, ACTIVE, PARTIALLY_PAID, DEFAULTED, REJECTED, CANCELLED, COMPLETED, SETTLED, WRITE_OFF, ON_HOLD, AWAITING_DISBURSEMENT, BRE_APPROVED, BRE_REJECTED, HARD_REJECTED, SOFT_REJECTED, DELETED, DORMANT.
loan_stage_enumWho currently owes work on it (independent axis): APPLICATION, SALES, CREDIT, FIELD_VISIT, MANAGER, ESTAMP, ESIGN, DISBURSEMENT, POST_DISBURSEMENT, COLLECTION_FIELD_VISIT, CLOSED, MANDATE.
smart_bre_status_enumAPPROVED, REJECTED, MANUAL_REVIEW, ERROR
estamp_order_status_enumPENDING, SUBMITTING, SUBMITTED, STAMPED, FAILED, CANCELLED, NEEDS_REVIEW
BrandUserWorkflowEnumBorrower onboarding steps: MOBILE_OTP, PAN_VERIFY, EMAIL_VERIFICATION, BANK_VERIFICATION, ACCOUNT_AGGREGATOR, EMPLOYMENT_DETAILS, AADHAAR_VERIFICATION, PHOTO_UPLOAD, VIDEO_UPLOAD, LOAN_APPLICATION
Doc drift caught here loan_stage_enum's CREDIT, ESTAMP, ESIGN (as its own stage) and MANDATE stages are all absent from the team's own md/loan-workflow.md, which only documents APPLICATION → SALES → FIELD_VISIT → MANAGER → DISBURSEMENT → POST_DISBURSEMENT. The real pipeline has at least three more stages than that doc describes — see the full lifecycle on the Product page.

06 Deployment & infrastructure

LayerDetail
ContainersDockerfile.dev, Dockerfile.production at repo root
Process managerPM2 — ecosystem.config.cjs: 4-worker API cluster (los-backend-api) + 1 single-fork cron-worker (los-backend-cron-worker, CRON_WORKER=true). CronGuardService stops all @Cron jobs on non-cron instances.
CI/CDGitHub Actions — be-deploy-uat-dev.yml (dev/UAT), deploy-prod.yml (production)
Queues12 distinct SQS queues in production (ap-south-1): audit-logs, loan-allocation, loan-screening, noc, onboarding-fanout, user-remindar, and more
RabbitMQPROTOTYPE ONLY 3-node RabbitMQ 4.1 cluster behind HAProxy — a possible future SQS replacement. Nothing in production publishes to it yet.
CacheRedis (ioredis), toggle REDIS_ENABLED — dedicated BrandCacheModule and MasterDataCacheModule
PDF / imagingpdf-lib, pdfjs-dist, pdfkit, puppeteer, sharp — agreement/statement generation
Background jobsTrigger.dev alongside NestJS @Cron
Ops scriptsscripts/ — baseline-db.ts, backfill-phone-encryption.ts, per-master seeders (banks/NBFCs/states/pincodes), create-readonly-nopii-role.ts (PII-redacted read-replica DB role)

07 What's new since the last documentation pass (~April 2026)

Git shows 95 new *.module.ts files added since 2026-04-07 — most of the current business-feature surface postdates the old docs.

Correction — WhatsApp CRM is not live on this branch An earlier pass of this doc listed a "WhatsApp CRM" staff inbox as a shipped feature, based on Prisma schema models (whatsapp_conversations, whatsapp_messages, whatsapp_sender_accounts, Brand.whatsapp_crm_enabled) and real, detailed commit history. That history exists only on an unmerged branch, origin/feature/whatsapp-crm-abhi — it is not an ancestor of the branch this documentation was built from (verified via git merge-base --is-ancestor). Nothing in the current src/ tree references those models. The schema change appears to have landed ahead of the feature code. Treat WhatsApp CRM as in-development, not live, until that branch merges. Also corrected here: the web chatbot uses plain OpenAI, not Azure OpenAI (a stale code comment was the source of that error), and app/partner/crm-chatbot is an unrelated AI-assistant proxy for partner staff, not a WhatsApp feature.
  • Coin & Wallet gamification system — full engagement/rewards engine for CRM roles, 35 rule versions, FIFO coin lots with expiry, redemption + payroll batch flow. Entirely absent from old docs.
  • SAP GL export — rebuilt as a stateful sync with reversals; exports customer accounts (AR) and GL vouchers to SAP.
  • Sphoro Voice — AI voice agent for outbound calls and in-browser AI voice chat, alongside the pre-existing Acefone human-dialer telephony.
  • CREDIT / ESIGN / ESTAMP / MANDATE loan-stage additions — significantly more granular pipeline than documented previously.
  • Partner sign-in codes — passwordless staff-recovery login (one of the highest migration numbers — very recent).
  • Grievance & Whistleblower reporting — public, OTP-gated complaint forms shipped 2026-09-17.
  • Debt Consolidation loan product — multi-leg disbursement against consolidation lines, distinct from a single-leg plain loan.
  • UPI Autopay — 3-provider abstraction (Cashfree/Razorpay/PhonePe) for recurring EMI debits.
  • Reloan automation — full rule engine auto-deciding approve/pending/reject for repeat borrowers.
  • Underwriting-analysis unification — Smart BRE, CRIF BRE, Neetix BRE and Marketing Analysis now run through one orchestrator with a brand-driven engine resolver; /bre/smart-bre is now a deprecated alias.
  • Field-level PII encryption rollout across customer data.
  • EMI pricing engine hardening — 9 documented pricing traps verified against a 3,600-randomised-loan test suite (see risk callout on the Product page).