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.
md/*.md doc conflicted with the code, the code won — conflicts are called out inline.
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.
api prefix, URI versioningREDIS_ENABLED; brand & master-data cachesprocess.env before Nest boots; fails fast if DATABASE_URL missingsrc/core/crypto · separate PII_DEK_1/PII_INDEX_KEY secret pathThis 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.
src/ top-level directories and what lives in each.
| Directory | Purpose |
|---|---|
app/web | Borrower/customer HTTP surface (@AuthType("web")). Sub-areas: bank, blogs, consolidation-lines, employment, guarantors, home, kyc, other-documents, personal-details. |
app/partner | Staff 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/common | Shared HTTP utilities (e.g. signed-URL endpoint). |
common/ | Cross-cutting guards, filters, interceptors, decorators, logger, health checks. |
core/aws | S3 (public/private), SQS, Secrets Manager clients. |
core/communication | Multi-provider email / SMS / WhatsApp dispatch abstraction. |
core/crypto | Field-level PII encryption + PII vault. |
core/cron | Scheduled jobs — active only on the cron-worker PM2 process. |
core/queue | Reminder queue dispatcher, SQS-backed. |
core/redis, core/jwt, core/pdf, core/documents, core/workers | Infra services. |
core/brand-provider-keys | Per-brand credential resolution for external vendors. |
core/provider-alerts | Alerting 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. |
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.
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.
| AuthType | Who | Notes |
|---|---|---|
| web | Borrower/customer (los-webv1) | Customer JWT. Onboarding KYC, home/tracking, blogs. |
| partner | Internal 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 / credential | Machine-to-machine integrators | x-api-key / x-api-credential headers — marketplace auto-login, affiliate lead handoff (e.g. loanwalle). |
| public | No token | 101 public routes as of 2026-09-30 — see risk callout below. |
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.
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.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.src/core/crypto/, loaded via a secret independent of the main Secrets Manager fetch.| Vendor / capability | Purpose | Module |
|---|---|---|
| CIBIL (Signzy + native), CIR Pro V2, Equifax | Credit bureau reports | external/cibil, crif-bre, external/equifax |
| Neetix Bureau Evaluate | Additional bureau-evaluation BRE engine | external/neetix-bureau-evaluate |
| Smart BRE (in-house) | Rule-based risk scoring → approved amount/risk grade | external/smart-bre, orchestrated by features/underwriting-analysis |
| Signzy, Digitap, ScoreMe | PAN/KYC verification with fallback chain, DigiLocker | features/pan-details-plus, external/digiLocker2.0 |
| SignDesk, Signzy v3, Digitap eSign, Doqfy | e-signature providers for loan agreements | features/esign |
| Doqfy | E-stamping of agreements | features/estamp |
| Account Aggregator (Finduit/FIU + Xaler) | Bank-statement consent & pull for underwriting | external/aa |
| Cashfree, Razorpay (+v2), Easebuzz, PayU, Paytring | One-time payment collection | features/payment/collection |
| Cashfree / Razorpay / PhonePe UPI Autopay | Recurring EMI debit mandates | features/payment/autopay |
| Lendbox | Co-lending partner (credit + disbursal UTR webhooks) | features/lendbox-v1 |
| HDFC, YES Bank (+ IDFC/ICICI implied) | Disbursement banking rails | md/Integrations/*.md |
| Acefone | Human-agent telephony/dialer | external/acefone, features/telephony |
| Sphoro Voice | AI voice agent — outbound AI-dialed calls and in-browser AI voice chat, per-brand + per-telecaller caller-ID | external/sphoro-voice, features/sphoro-voice |
| AiSensy, Meta WhatsApp Cloud, Gupshup | WhatsApp messaging providers | core/communication/providers/whatsapp |
| Meta WhatsApp Flows | Full conversational loan-application journey inside WhatsApp itself | external/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 endpoint | external/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-chatbot | app/partner/crm-chatbot |
| Brevo, ZeptoMail, MSG91 / Gupshup / TrustSignal / SMSGatewayHub / Nimbusit | Email / SMS delivery | core/communication |
| Riskcovry | Insurance product integration | external/riskcovry |
| JuicyScore, fraud-detector | Device / behavioral fraud scoring | external/juicyscore, external/fraudDetector |
| AWS Rekognition, face-verification | Selfie / liveness KYC check | external/aws-face-liveness, external/face-verification |
| UCIC | Cross-brand customer identity resolution | external/ucic |
| SAP GL NEW | Exports AR/GL accounting entries to SAP — stateful sync with reversals | app/partner/report/sap-gl-export/* |
| AWS S3, SQS, Secrets Manager | Storage, async messaging, secrets | core/aws |
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.
src/ references them — see the correction callout in §07.| Enum | Values / meaning |
|---|---|
loan_status_enum | What 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_enum | Who 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_enum | APPROVED, REJECTED, MANUAL_REVIEW, ERROR |
estamp_order_status_enum | PENDING, SUBMITTING, SUBMITTED, STAMPED, FAILED, CANCELLED, NEEDS_REVIEW |
BrandUserWorkflowEnum | Borrower onboarding steps: MOBILE_OTP, PAN_VERIFY, EMAIL_VERIFICATION, BANK_VERIFICATION, ACCOUNT_AGGREGATOR, EMPLOYMENT_DETAILS, AADHAAR_VERIFICATION, PHOTO_UPLOAD, VIDEO_UPLOAD, LOAN_APPLICATION |
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.
| Layer | Detail |
|---|---|
| Containers | Dockerfile.dev, Dockerfile.production at repo root |
| Process manager | PM2 — 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/CD | GitHub Actions — be-deploy-uat-dev.yml (dev/UAT), deploy-prod.yml (production) |
| Queues | 12 distinct SQS queues in production (ap-south-1): audit-logs, loan-allocation, loan-screening, noc, onboarding-fanout, user-remindar, and more |
| RabbitMQ | PROTOTYPE ONLY 3-node RabbitMQ 4.1 cluster behind HAProxy — a possible future SQS replacement. Nothing in production publishes to it yet. |
| Cache | Redis (ioredis), toggle REDIS_ENABLED — dedicated BrandCacheModule and MasterDataCacheModule |
| PDF / imaging | pdf-lib, pdfjs-dist, pdfkit, puppeteer, sharp — agreement/statement generation |
| Background jobs | Trigger.dev alongside NestJS @Cron |
| Ops scripts | scripts/ — 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) |
Git shows 95 new *.module.ts files added since 2026-04-07 — most of the current business-feature surface postdates the old docs.
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.
/bre/smart-bre is now a deprecated alias.