8byte.ai
Loan Origination System — Database Documentation
PostgreSQL Prisma ORM ~120 Tables

LOS Backend Database Documentation

Complete schema reference for the Loan Origination System — multi-tenant, multi-brand lending platform.

Database
PostgreSQL
ORM
Prisma
Total Tables
~120+
Schema File
prisma/schema.prisma

Overview System Overview

This is a Loan Origination System (LOS) — a multi-tenant SaaS platform where multiple lending companies (Brands) operate independently on the same infrastructure.

  • Brands = lending companies (tenants). Each brand has its own config, loan rules, users, and partner staff.
  • Partner Users = internal staff — credit executives, collection agents, operations, admins.
  • Users = end customers applying for loans.
  • The platform manages the complete loan lifecycle: onboarding → KYC → application → BRE evaluation → disbursement → repayment → closure.

High-Level Data Flow

Brand (Tenant) ├── BrandConfig → runtime settings, feature flags ├── BrandProviders → which 3rd-party APIs to use per service ├── LoanRules → products, eligibility, fee structures ├── PartnerUsers → internal staff with roles + permissions └── Users (customers) ├── UserDetails → personal info, KYC data ├── Documents → PAN, Aadhaar files ├── Employment → company, salary, payslips ├── UserBankAccount → account verified via penny drop └── Loans ├── Evaluation → BRE rule results ├── LoanAgreement → e-sign via SignDesk/Signzy/Digitap ├── Disbursement → fee deductions, net amount ├── Repayment → obligation schedule └── PaymentRequest → transactions → receipts

Reference Entity Relationship Flow

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ MASTER / LOOKUP DATA ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ master_states → master_districts → master_pincodes master_banks (standalone lookup: bank name, IFSC pattern) master_category → master_value (generic key-value config store) └── referenced by users (status_id, occupation_type_id, rejected_by_id) brand_category → brand_value (brand-level overrides of master_category/master_value) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ BRAND (multi-tenant root) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ brands ├── [1:1 config] │ ├── brand_configs │ ├── brand_details │ ├── brand_themes │ ├── brand_policy_links │ ├── brand_reloan_configs │ └── brand_loan_agreement_configs │ ├── [operational] │ ├── brand_api_keys │ ├── brand_bank_account │ ├── brand_providers (payment / KYC providers per brand) │ ├── brand_evaluation_items → evaluation_item (master) │ ├── brand_status_reasons → referenced by loan_status_brand_reasons │ ├── brand_non_repayment_dates │ ├── brand_sub_domains │ ├── brand_paths │ ├── brand_targets │ ├── brand_coupons → loan_coupon_redemptions │ ├── brand_rating_matrix │ ├── brand_blogs │ ├── brand_setting_audit_logs (audit trail for brand config changes) │ └── brand_cards │ ├── [notification / reminder] │ ├── notifications → notification_targets → partner_users │ ├── email_reminder_configs │ ├── whatsapp_reminder_configs │ └── brand_acefone_configs (dialer / voice config) │ ├── [blocklists] │ ├── brand_blocklisted_pan │ ├── brand_blocklisted_mobile │ ├── brand_blocklisted_aadhar │ ├── brand_blocklisted_account_number │ └── brand_blocklisted_pincode │ ├── [loan product rules] │ └── loan_rules │ ├── loan_rule_tenures (1:1) │ │ └── loan_charge_config → loan_charge_taxes │ └── loan_penalty │ ├── partner_user_brand_roles → partner_users (see Partner section) │ └── users (see User section below) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ USER (customer / borrower) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ users ├── [1:1 profile] │ ├── user_details │ └── user_status (current status snapshot) │ ├── [auth / session] │ ├── user_login_tokens │ ├── user_otp_verifications │ └── devices (registered devices / push tokens) │ ├── [lifecycle & tracking] │ ├── user_rejections │ ├── user_reloan │ ├── user_geo_tags │ ├── user_audit_logs │ ├── user_reminders → user_reminder_audit_logs │ ├── user_salaries │ ├── onboarding_journey │ ├── utm_tracking │ ├── call_me_requests │ ├── user_notifications │ ├── reloan_automation_log │ └── user_allotted_partner_user_logs (which partner user is assigned) │ ├── [contact / address] │ ├── alternate_addresses │ └── alternate_phone_numbers │ ├── [identity & KYC documents] │ ├── documents (PAN + Aadhaar) │ │ └── pan_aadhaar_verification → pan_aadhaar_address │ ├── other_documents │ ├── pan_details_log (PAN API call log) │ ├── mobile_to_pan_verification (mobile ↔ PAN cross-check) │ ├── mobile_verification_logs (OTP / mobile verification history) │ ├── aadhaar_digi_locker_log (DigiLocker callback log) │ ├── digitap_some_table (Digitap KYC session data) │ └── kyccart_some_table (KYCCart session data) │ ├── [calls / communication] │ └── user_calls │ ├── user_call_events (individual call events) │ └── user_call_recordings (recording files) │ ├── [employment] │ ├── employment (1:1) │ │ └── payslips │ ├── previous_employments │ ├── phone_to_uan_log (mobile → UAN lookup log) │ └── uan_to_employment_log (UAN → employment details log) │ ├── [bank account & statements] │ └── user_bank_account │ ├── penny_drop_log (penny-drop verification log) │ └── bank_account_statement │ ├── finbox_some_table │ ├── scoreme_some_table │ └── cart_some_table │ ├── [credit bureau] │ ├── equifax_some_table │ ├── cirprov2_some_table │ ├── user_cibil_reports │ └── user_cibil_report_logs │ ├── [scoreme / BDA] │ └── scoreme_bda_report │ ├── [account aggregator] │ └── aa_consent_requests │ ├── aa_consent_notifications │ ├── aa_data_sessions → aa_financial_insights │ └── aa_periodic_data_responses │ ├── [public inquiry] │ └── public_loan_inquiries (pre-login / open loan inquiry form) │ └── loans (see Loan section below) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ LOAN (the core lending lifecycle) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ loans ├── [1:1 meta] │ ├── loan_details │ └── cam_calculators │ ├── [financials] │ ├── disbursements → deductions → tax_deductions │ ├── repayments → fee_breakdowns → tax_fee_breakdowns │ ├── cost_summaries │ ├── early_repayment_discounts │ ├── penalties │ ├── loan_ledger (full GL ledger entries) │ └── repayment_timelines (partner-assigned repayment schedule) │ ├── [evaluation] │ └── evaluations → evaluation_item │ ├── [status history] │ └── loan_status_history │ └── loan_status_brand_reasons │ ├── [agreements / esign] │ └── loan_agreements │ └── loan_agreement_references │ ├── signdesk_some_table │ ├── signzy_some_table │ └── digitap_esign_some_table │ ├── [unsigned data] │ └── unsigned_data_agreement (pre-esign data capture) │ ├── [documents / ops] │ ├── loan_no_due_certificates │ ├── loan_email_logs │ ├── loan_xlsx_files │ ├── loan_coupon_redemptions → brand_coupons │ ├── field_visit │ ├── loan_allotted_partner_user_logs (partner assignment per loan) │ └── loan_collection_allocated_partner_logs │ ├── [payments] │ └── payment_request (one per payment attempt) │ ├── payment_disbursal_transaction │ │ └── payment_provider_log (raw API log) │ ├── payment_collection_transaction │ │ ├── payment_transaction_receipt │ │ └── payment_provider_log │ ├── payment_partial_collection_transaction │ │ ├── payment_transaction_receipt │ │ └── payment_provider_log │ └── payment_autopay_transaction │ └── [lendbox / co-lending] ├── lendbox_workflow └── lendbox_api_logs (Lendbox API call log) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ PARTNER USER (internal team: ops, credit, collections, etc.) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ partner_users ├── reportsTo / subordinates (self-referential hierarchy) │ ├── [auth] │ ├── partner_login_tokens │ ├── partner_otp_verifications │ └── partner_user_password_reset_tokens │ ├── [roles & permissions] │ ├── partner_user_brand_roles → partner_roles (brand-scoped role) │ ├── partner_user_global_roles → partner_roles (global role) │ ├── partner_user_permissions → partner_permissions (granular permissions) │ └── partner_user_primary_permissions → partner_permissions (primary permission) │ ├── [activity] │ ├── partner_user_login_logs │ ├── partner_user_activity_sessions → partner_user_activity_logs │ └── partner_user_inactivity_alerts │ ├── [codes & audits] │ ├── partner_user_codes │ ├── partner_user_code_audit_logs │ ├── partner_user_audit_logs (action audit trail) │ └── partner_user_report_logs (downloaded / generated reports) │ ├── [availability & config] │ ├── partner_unavailability_dates │ ├── partner_user_dialer_configs │ └── partner_user_rating_matrix │ ├── [loan ops (cross-references)] │ ├── loan_status_history (partner who changed status) │ ├── loan_allotted_partner_user_logs │ ├── loan_collection_allocated_partner_logs │ ├── user_allotted_partner_user_logs │ ├── service_request_logs (partner who handled service req) │ └── repayment_timelines (partner-created schedules) │ └── partner_user_rules (1:1) (custom rule overrides per agent) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ SERVICE REQUESTS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ service_request_logs → loan (FK) → partner_user (assigned to) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ LEAD MANAGEMENT ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ lead_forms → lead_matches → users / documents ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ NOTIFICATION SYSTEM ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ notifications (created by partner_user, scoped to brand/partner_role) └── notification_targets → partner_users whatsapp_message_logs (outbound WhatsApp messages, linked to user/loan)

Total tables: 168. Every model in the Prisma schema is represented above. The tree is grouped by domain: Master/Lookup → Brand → User → Loan → Partner User → Service Requests → Leads → Notifications. Cross-domain foreign-key references (e.g. a loan referencing a partner_user) are shown inline with a arrow. (1:1) denotes a strict one-to-one relation. All other branches are one-to-many unless noted.

Module 1 Brand & Configuration

🏢
Multi-tenant setup. Every customer, loan, and partner user belongs to a brand.
Brands are the top-level tenants. All configuration, rules, integrations, and data are scoped per brand.
~25 tables

brands

The central tenant table. Everything in the system is scoped to a brand.

ColumnTypeDescription
idUUID PKBrand identifier
nameString UNIQUEBrand name
domainString UNIQUECustom domain
loanPrefixString UNIQUEPrefix for loan IDs (e.g. 8BL)
customerPrefixString?Prefix for customer IDs
defaultLoanRiskCategoryEnum?Default risk bucket for loans
onPartnerBooleanWhether brand uses partner portal
partner_version / web_versionString?App version tags
is_lendbox_integratedBooleanLendbox co-lending integration
max_multi_device_sessionIntMax concurrent sessions per user
isUATServicesBooleanUAT/test mode flag

brand_configs

Per-brand feature flags and workflow settings — the main configuration table controlling all business logic toggles.

ColumnTypeDescription
brandIdUUID UNIQUE FK→ brands
salaryThresholdAmountIntMinimum salary for eligibility
rejectionDurationIntDays before rejected user can re-apply (default: 15)
bankStatementHistoryMonthsIntHow many months of bank statements required
esignExpiryDayCountIntE-sign link expiry in days (default: 2)
isAABooleanEnable Account Aggregation flow
loanAgreementVersionIntLoan agreement template version
minLoanAmountRequiredIntMinimum loan amount (default: 15000)
forceEmploymentBooleanRequire employment data
autoAllocationTypeStringAuto-allocation trigger (LOGIN / etc.)
evaluationVersionStringBRE version (V1/V2)
collection_auto_allocationBooleanAuto-assign collection agents
loan_auto_allocationBooleanAuto-assign credit executives
user_auto_allocationBooleanAuto-assign users to partners
enable_central_dedupBooleanCentral deduplication check
max_age / min_ageIntCustomer age eligibility bounds
is_cam_calculation_requiredBooleanCAM (Credit Appraisal Memo) required
is_automated_reloanBooleanAuto re-loan trigger after closure
user_auto_rejectionBooleanAuto-reject stale users
user_auto_rejection_daysIntInactivity days before auto-reject
sunday_offBooleanExclude Sundays from repayment calculation
requiresUserPhoto / requiresUserVideoBooleanSelfie / video KYC required
skip_loan_evaluation_approval_daysIntDays after which evaluation approval is auto-skipped
dashboard_version / loan_ops_versionStringUI version tags

brand_providers

Maps which third-party provider a brand uses for each service type. Supports primary/secondary provider fallback.

ColumnDescription
typePENNYDROP, LOAN_AGREEMENT, BRE, PAN_DETAILS_PLUS, DISBURSEMENT, SMS, EMAIL, WHATSAPP, ACCOUNT_AGGREGATION, etc.
providerDIGITAP, SIGNDESK, SIGNZY, FINBOX, SCOREME, RAZORPAY, CASHFREE, MSG91, FINDUIT, etc.
isPrimaryDefault provider for this type
isActive / isDisabledStatus flags

Constraint: UNIQUE(brandId, type, provider) — each brand-provider-type combo is unique.

brand_evaluation_items

BRE (Business Rule Engine) rules configured per brand. Defines what parameters are evaluated during loan underwriting.

ColumnDescription
parameterWhat to evaluate (e.g. CREDIT_SCORE, SALARY, AGE)
requiredValuePass condition value
sourcesArray of data sources (e.g. CIBIL, AA, BSA)
stageEvaluation stage: ONE, TWO, THREE, FOUR
priorityRule execution order

Blocklist Tables

Five tables blocking specific identifiers from applying for loans on a brand:

TableBlocked FieldNotes
brand_blocklisted_panPAN card number+ customer_name, reason, dpd
brand_blocklisted_mobileMobile number+ customerName, reason, dpd
brand_blocklisted_aadharAadhaar number+ customerName, reason, dpd
brand_blocklisted_account_numberBank account number+ customerName, reason, dpd
brand_blocklisted_pincodePincode (serviceability)+ reason, dpd

Other Brand Tables

TablePurpose
brand_detailsLegal info: GST, CIN, RBI registration, lender name, address
brand_policy_linksT&C, privacy policy, FAQ, contact URLs shown to users
brand_themesWhite-label UI colors, fonts, dark mode config
brand_bank_accountBrand's bank accounts for disbursal & collection
brand_api_keysAPI keys for programmatic access to the LOS
brand_loan_agreement_configsLegal contact details embedded in loan agreements
brand_non_repayment_datesHolidays — dates excluded from repayment schedule
brand_sub_domainsMultiple signup funnels per brand with marketing source tags
brand_targetsMonthly credit/debit disbursement targets
brand_couponsDiscount coupons for loan processing fees
brand_reloan_configsAuto-reloan amount hike rules (fixed / percentage)
brand_rating_matrixScoring matrix (ratings 1–10 with weightages) per role/metric
brand_acefone_configsTelephony dialer integration settings
brand_status_reasonsConfigurable rejection/status reason codes
brand_pathsNavigation menu items for partner portal
brand_blogsCMS blog posts per brand (DRAFT/PUBLISHED/ARCHIVED)
brand_category / brand_valueFlexible key-value config catalog per brand
email_reminder_configsEmail reminder templates with day offsets and loan status filters
whatsapp_reminder_configsWhatsApp reminder template configs per brand

Module 2 Partner User Management

👥
Internal staff — credit executives, collection agents, operations, admins.
Partner users manage the loan workflow. They have brand-scoped roles, granular permissions, and a manager hierarchy.
~15 tables

partner_users

ColumnTypeDescription
idUUID PKPartner user ID
emailString UNIQUELogin email
passwordStringHashed password (bcrypt)
nameString?Display name
employee_idString?HR employee ID
phone_numberString?Mobile number
reportsToIdUUID? FK → selfManager (self-referential hierarchy)
isActive / is_disabledBooleanAccount state flags
isReloanSupportBooleanCan handle reloan cases
is_fresh_loan_supportBooleanCan handle fresh loan applications

Self-referential relation: reportsTo / subordinates builds a manager hierarchy tree for the entire org chart.

Role & Permission System

TableDescription
partner_rolesNamed roles: CREDIT_EXECUTIVE, COLLECTION_AGENT, OPS, ADMIN, etc. Grouped by role_group_id
partner_user_brand_rolesRole assigned to a user within a specific brand. PK: (brandId, partnerUserId, roleId) — different roles across brands
partner_user_global_rolesRole assigned across all brands (super-admin). PK: (partnerUserId, roleId)
partner_permissionsFine-grained permissions: VIEW_LOANS, EDIT_USER, DISBURSE, etc.
partner_user_permissionsPermission grants per user. Type: READ / WRITE / ALL
partner_user_primary_permissionsOne default primary permission level per user

Activity & Session Tracking

TableDescription
partner_user_login_logsDaily login tracking. UNIQUE(partnerUserId, date) — one record per user per day with first login + last logout
partner_user_activity_sessionsFull session records: startTime, endTime, totalEvents, inactiveTimeMs, pageViews[], userAgent, screenResolution
partner_user_activity_logsIndividual events per session: eventType, pageUrl, mouseX, mouseY, scrollPos, timestamp
partner_user_inactivity_alertsRecords when a user was warned about inactivity (inactiveTimeSeconds, lastActivityTime, currentPage)

Other Partner Tables

TableDescription
partner_login_tokensJWT access + refresh tokens with device tracking and logout flag
partner_user_password_reset_tokensPassword reset flow: token, expiresAt, usedAt, redirectLink
partner_user_rulesPer-user overrides: isReloanSupport, isCxAllCustomer (see all customers, not just assigned)
partner_user_codesEncrypted QR/invite codes with audit trail (generatedBy, deactivatedBy)
partner_user_code_audit_logsCode generation/deactivation audit
partner_unavailability_datesLeave dates — impacts auto-allocation of users/loans
partner_user_dialer_configsTelephony: agent number, caller ID, skill routing
partner_user_rating_matrixMonthly performance ratings (1–10) per metric type with weightages
partner_user_report_logsAudit of report downloads/exports

Module 3 End User Management

🙋
End customers — borrowers applying for loans.
Each user is tied to one brand. Complete lifecycle tracking from signup to loan closure.
~20 tables

users

Primary customer entity.

ColumnTypeDescription
idUUID PK
email / phoneNumberString?UNIQUE per brand (same contact can register on multiple brands)
brandIdUUID FK→ brands
brandSubDomainIdUUID? FKWhich subdomain/funnel they signed up from
formattedUserIdString UNIQUEHuman-readable ID (e.g. CUST00123)
onboardingStepIntCurrent onboarding step (1-based)
isActiveBooleanActive account
isEmailVerified / isPhoneVerified / isWhatsappVerifiedBooleanVerification flags
migrationStatusEnumONBOARDED_NEW / MIGRATED / PARTIALLY_MIGRATED
pan_number / aadhaar_numberString?Masked PAN (10 chars) and Aadhaar (last 4)
is_pan_verified / is_aadhaar_verifiedBoolean?Verification status
is_aadhaar_pan_linkedBoolean?Aadhaar-PAN linkage status
allocated_partner_user_idUUID?Assigned credit executive / agent
allocated_atDateTime?Assignment timestamp
status_idBigInt FK → master_valueUser status from master data
occupation_type_idBigInt FK → master_valueJob category
is_auto_rejectedBoolean?System auto-rejected flag
lendbox_user_idString?Co-lending platform user reference

user_details

Extended personal profile — one-to-one with users.

ColumnDescription
firstName / middleName / lastNameName parts
gender / dateOfBirthDemographics
address / city / state / pincodeCurrent address
profilePicUrl / profileVideoUrlKYC selfie / video
fathersName / mothersName / spouseNameFamily details
maritalStatus / religion / residenceTypePersonal info
creditScoreStored credit score
aAdharName / aAdharDOBAadhaar-matched name & DOB
pan_name / pan_dob / pan_fathernamePAN-matched details
geoLatitude / geoLongitude / geolocation_pincodeGPS coordinates & derived pincode
isFraudulentByCMSFraud flag from CART/CMS provider
linkedAadhaarNumberByDigiLocker / linkedAadhaarNumberByPanPlusAadhaar confirmed via providers
aadhaar_digilocker_gz_key / pan_details_gz_keyS3 keys for compressed KYC data
profile_photo_key / profile_video_keyS3 keys for media files

user_status

KYC and loan eligibility status — one-to-one with users.

ColumnDescription
kycCompletedFull KYC done flag
loanEligibleEligible for a loan
accountStatusACTIVE / HOLD / PENDING / REJECTED
currentStatusSALARIED / SELF_EMPLOYED / OTHER
termsAcceptedT&C accepted by customer

Other User Tables

TableDescription
user_login_tokensJWT access + refresh tokens with device tracking
user_otp_verificationsOTP attempts (6-digit, typed, used flag, expiry)
user_rejectionsHistory of rejections with type, source (ADMIN/SYSTEM), and end date
user_reloanRe-loan requests linking customer to their previous loan
user_geo_tagsGPS location records (reverse-geocoded to address)
user_audit_logsFull event audit trail with serial number per user
user_status_brand_reasonsSpecific rejection/status reasons attached to user status
alternate_addressesAdditional addresses (office, parent) with proof document
alternate_phone_numbersSecondary contacts with relationship and OTP verification
user_remindersScheduled SMS/WhatsApp/push reminders with retry logic
user_reminder_audit_logsReminder lifecycle events
user_salariesMultiple salary entries per month (when multi-salary is enabled)
utm_trackingMarketing attribution: UTM params, landing page, fbclid, clickid
onboarding_journeyStep-by-step signup funnel progress. UNIQUE(userId, stepNumber)
user_allotted_partner_user_logsHistory of which partner user was assigned to the customer
user_cibil_reportsStored credit bureau reports (score, HTML/JSON/PDF keys)
user_cibil_report_logsAPI call logs for all credit bureau queries
call_me_requestsCustomer callback requests with message and resolution flag
user_notificationsIn-app notifications for customers (type, JSON payload, readAt)
devicesDevice fingerprints (fpId, OS, appVersion, fcmToken, platformType)

Module 4 KYC & Document Verification

🪪
Identity documents, verification results, and call records.
Tracks PAN, Aadhaar, other documents, and all third-party verification API results.
~8 tables

documents

Primary KYC documents — PAN and Aadhaar. One of each per user.

ColumnDescription
typeAADHAAR or PAN
frontDocumentUrl / backDocumentUrlDocument image URLs
documentNumberPAN/Aadhaar number (trigram indexed)
statusPENDING / APPROVED / REJECTED
userDataStatusNOT_VERIFIED / VERIFIED_BY_USER / VERIFIED_BY_ADMIN
providerDataJSON response from verification provider
isApprovedByAdminManual admin approval flag

Constraint: UNIQUE(userId, type) — one PAN and one Aadhaar per user.

pan_aadhaar_verification

Result of PAN + Aadhaar cross-verification (checks if Aadhaar is linked to PAN). One-to-one with document.

pan_aadhaar_address

Address parsed from the PAN+Aadhaar verification response. One-to-one with verification.

other_documents

Secondary documents — voter ID, driving license, passport, salary slips, Form 16, ITR, rent agreement, etc. Can be linked to a specific loan.

Call Records

TableDescription
user_callsCall session linking partnerUser + user + brand + optional loan
user_call_eventsTelephony events: callStatus, duration, answerDuration, fromNumber, toNumber, endCallCause
user_call_recordingsRecording file reference, startTime, endTime, filePrivateUrl

repayment_timeline

Promise-to-Pay (PTP) records — documents/evidence uploaded by collection agents during calls.

field_visit

Flag record indicating whether a field visit is required for a specific loan.

service_request_logs

Full API request/response audit log: action, method, URL, IP, userAgent, requestBody, responseStatus, responseTime.

Module 5 Employment & Bank Details

🏦
Employment information, payslips, and bank accounts.
Income verification data used for loan eligibility and disbursal.
5 tables

employment

Current employment — one per user.

ColumnDescription
companyName / designationJob details
joiningDate / salaryWhen they joined and their monthly salary
companyAddress / pinCodeOffice location
uanNumberEPFO Universal Account Number
modeOfSalaryBANK_TRANSFER / CASH / CHEQUE / OTHER
employmenttypeFULL_TIME / PART_TIME / CONTRACT / INTERN / FREELANCE / GIG / etc.
expectedDateOfSalaryDay of month salary is credited (default: 5)
officialEmailOffice email address
userDataStatusVerification status

payslips

Monthly salary slips. UNIQUE(userId, employmentId, month, year)

ColumnDescription
month / yearPayslip period
filePrivateKeyS3 key for the PDF
filePasswordPassword if PDF is encrypted

user_bank_account

ColumnDescription
accountNumber / ifscCode / bankNameAccount details
accountTypeCurrent / Savings
isPrimaryPrimary account for disbursal
verificationMethodMANUAL / PENNY_DROP / API
verificationStatusPENDING / VERIFIED / FAILED / RETRYING
pennyDropResponse / pennyDropStatusLast penny drop API result
pennyVerifiedNameAccount holder name returned from penny drop

bank_account_statement

Bank statement files per account. Has fraud detection fields (isFraud, fraudScore) and is the parent for BSA analysis tables (FinBox, ScoreMe, CART).

previous_employments

Past employment records from EPFO. Stores UAN, memberId, establishment name, joining/exit dates.

Module 6 Loan Lifecycle

📋
The core of the LOS — from application to closure.
Loan products, rules, fees, evaluations, agreements, ledger, and all lifecycle tracking.
~20 tables

Loan Status Flow

ONBOARDING PENDING CX_APPROVED SM_APPROVED APPROVED AWAITING_DISBURSAL DISBURSED ACTIVE PARTIALLY_PAID PAID / COMPLETED
Terminal states: REJECTED CANCELLED DEFAULTED OVERDUE WRITE_OFF SETTLED

loan_rules

Loan product definitions per brand. Each rule type is a distinct product (e.g. LOAN-1, LOAN-2).

ColumnDescription
ruleTypeLoan product type string (e.g. LOAN-1)
minAmount / maxAmountLoan amount range
maxCompleteLoanCountMax loans allowed per customer
isActive / isDisabled / isVisibleStatus flags

loan_rule_tenures

Tenure settings for a loan rule (one-to-one).

ColumnDescription
loan_typeEMI or PAYDAY_LOAN
minTermDays / maxTermDaysDuration range
gracePeriodPost-due grace days
allowPrepaymentEarly repayment allowed
minPostActiveTermDaysMinimum days in active state before post-active
is_fee_always_principalFee calculated on principal only
is_skip_disbursement_day_feeNo fee charged on disbursement day

loan_charge_config + loan_charge_taxes

Fee structure per loan rule/tenure. Each fee can have tax components.

ColumnDescription
typeprocessing / convenience / documentation / interest
valueTypefixed or percentage
chargeValueFee rate or amount
chargeModeINCLUSIVE (inside amount) or EXCLUSIVE
isRecurringDailyDaily recurring fee (overdue interest)

loans

The central loan record.

ColumnDescription
formattedLoanIdHuman-readable loan ID (e.g. 8BL000123)
amountRequested amount
statusCurrent loan status (see flow above)
ruleTypeLoan product applied (FK logic to loan_rules)
applicationDate / approvalDate / disbursementDate / closureDateKey lifecycle dates
loan_due_date / loan_tenure_daysRepayment due date and term
closingTypeNORMAL / SETTLEMENT / WRITE_OFF
loan_applied_amountWhat customer requested
loan_cx_approved_amountAmount approved by Credit Executive
loan_sm_sh_approved_amountAmount approved by Sanction Manager
loan_cx_assigned_partner_user_idAssigned credit executive
loan_collection_assigned_partner_user_idAssigned collection agent
is_repeat_loanIs this a re-loan
is_cam_calculation_requiredCAM required for this specific loan
lendbox_loan_idCo-lending platform reference
forceBsaReportByPass / forceCreditReportByPassBypass BSA/CIBIL checks

Financial Calculation Tables

TableDescription
loan_detailsComputed schedule: durationDays, dueDate, principal, grossPeriod, postActiveDate, prepayment bounds
disbursementsDisbursal math: grossAmount, totalDeductions, netAmount (what customer receives)
deductionsIndividual fee line items deducted upfront (processing fee, convenience, etc.)
tax_deductionsGST/TDS amounts on each deduction
repaymentsRepayment obligation: totalObligation, totalFees
fee_breakdownsIndividual fee components in repayment schedule
tax_fee_breakdownsTax on each repayment fee
cost_summariesHigh-level: totalTaxes, effectiveAPR
early_repayment_discountsDiscount amount offered for prepayment
penaltiesApplied overdue penalties on the loan
loan_ledgerDouble-entry ledger: principal/interest/penalty components per entry with running balances

cam_calculators

Credit Appraisal Memo filled by credit executives. Records 3 months of salary data, FOIR calculation, ROI, obligations, and recommended loan amount.

evaluations + evaluation_item

BRE evaluation record per loan. Each evaluation_item is one rule result: parameter, requiredValue, actualValue, source, ELIGIBLE/NOT_ELIGIBLE, manually overridden flag.

Loan Agreement Tables

TableDescription
loan_agreementsOne per loan. Status: NOT_SENT → SENT → SIGNED / REJECTED / EXPIRED
loan_agreement_referencesEach signing attempt. New reference on re-send. Provider: SIGNDESK / SIGNZY / DIGITAP
signdesk_some_tableSignDesk-specific response/callback data per reference
signzy_some_tableSignzy-specific data per reference
digitap_esign_some_tableDigitap e-sign data per reference

Other Loan Tables

TableDescription
loan_status_historyImmutable audit of all status changes with partner who changed it and reason
loan_status_brand_reasonsSpecific brand reasons attached to a status history entry
loan_no_due_certificatesNOC/closure certificates: NO_DUE_LETTER / WRITE_OFF_LETTER / SETTLEMENT_LETTER
loan_email_logsEmail delivery records (type, recipient, success, error)
loan_xlsx_filesExcel files for PAYOUT and BENEFICIARY reports
loan_coupon_redemptionsCoupon usage per loan with pre/post-discount values
loan_allotted_partner_user_logsHistory of loan → credit executive assignments
loan_collection_allocated_partner_logsHistory of loan → collection agent assignments with deallocation tracking
reloan_automation_logLog of automated reloan eligibility checks

Module 7 Payments & Transactions

💳
All money movement — disbursal, collection, partial payments, autopay.
Every payment flows through a PaymentRequest which spawns typed transactions.
7 tables

Payment Flow

Loan └── PaymentRequest (one per type per loan — DISBURSEMENT / COLLECTION / PARTIAL_COLLECTION / AUTOPAY_CONSENT) ├── PaymentDisbursalTransaction → bank transfer to customer ├── PaymentCollectionTransaction → full repayment from customer │ └── PaymentTransactionReceipt → receipt PDF ├── PaymentPartialCollectionTransaction → part-payment │ └── PaymentTransactionReceipt └── payment_autopay_transaction → UPI mandate setup All API calls → PaymentProviderLog

payment_request

ColumnDescription
typeDISBURSEMENT / COLLECTION / PARTIAL_COLLECTION / AUTOPAY_CONSENT
statusPENDING / SUCCESS / FAILED / RETRYING / CANCELLED / TIMEOUT
currencyDefault INR

Constraint: UNIQUE(loanId, type) — one request per transaction type per loan.

payment_disbursal_transaction

ColumnDescription
amountDecimal(12,2) — net amount transferred
methodMANUAL / RAZORPAY / CASHFREE / ICICI / IDFC / etc.
accountHolderName / bankAccountNumber / ifscCodeDestination account
transferModeNEFT / IMPS / UPI
externalRefProvider's transaction reference ID
retryCountRetry attempts
responseJSONRaw provider response
createdByPartnerId / opsPartnerIdWho initiated / who ops-approved

payment_collection_transaction

ColumnDescription
totalFees / totalTaxes / totalPenaltiesBreakdown of amounts collected
penaltyDiscountDiscount waived on penalty
opsApprovalStatusPENDING / APPROVED / REJECTED (ops must approve)
closingTypeNORMAL / SETTLEMENT / WRITE_OFF
isPaymentCompleteFull settlement flag
isReloanApplicableTrigger reloan offer after this collection
principalAmount / excessAmount / roundOffDiscountDetailed amount breakdown
paymentLinkPayment link URL sent to customer
platformTypeWEB or PARTNER

payment_autopay_transaction

UPI autopay mandate setup. Stores maxAuthorizedAmount for the mandate, metadata, and provider callback in responseData.

payment_transaction_receipt

Receipt record generated after a successful collection or partial-collection. One-to-one with the collection transaction. Stores receipt PDF S3 key, receipt number, and generated timestamp.

payment_provider_log

Raw API call logs: provider, apiEndpoint, correlationId, requestHeaders/Body, responseBody/Status, errorMessage.

Module 8 Third-Party API Integrations

🔌
External provider integrations — KYC, credit, BSA, e-sign, disbursal.
Each provider has its own log/response table for raw data storage and audit.
~15 tables

Bank Statement Analysis (BSA)

TableProviderKey Fields
finbox_some_tableFinBoxsessionId, statementId, initiateProcessing
scoreme_some_tableScoreMereferenceId, bsaReportJson, bsaReportXlsxPrivateKey
cart_some_tableCARTreferenceId, bsaReportJson, bsaReportDownloadJson

Credit Bureau Reports

TableProviderKey Fields
equifax_some_tableEquifaxbraReportJson, cibil_pdf_key, cibil_json_gz_key, generated_cibil_report_html_key, password
cirprov2_some_tableCIR Pro V2rawReportJson, cibil_html_key, cibil_json_gz_key

KYC Providers

TableProviderKey Fields
digitap_some_tableDigitappanDetailsPlus, mobilePrefill, pennyDropResponse, intiateKycAuto, kycUnifiedv1Details
kyccart_some_tableKYC CARTmobileAge, employmentHistory
aadhaar_digi_locker_logDigiLockerrequestType, digiLockerId, callbackData

Verification Logs

TableWhat It Logs
penny_drop_logBank account penny drop: accountNumber, ifsc, status (SUCCESS/FAILED/NAME_MISMATCH), nameMatch
pan_details_logPAN verification: pan, status, panHolderName, aadhaarLinked, cachedResponseData
phone_to_uan_logPhone → EPFO UAN lookup
uan_to_employment_logUAN → Employment history lookup
mobile_to_pan_verificationsPhone → PAN reverse lookup (Truecaller-style)
mobile_verification_logsGeneral mobile verification API calls

Lendbox (Co-lending)

TableDescription
lendbox_api_logsAPI call logs to Lendbox platform
lendbox_workflowStep-by-step workflow state: step_name, step_status, retry_count

scoreme_bda_report

ScoreMe Bureau Data Analysis (BDA) report per user. Stores the BDA report JSON response and report metadata returned by the ScoreMe bureau analysis API. One record per user.

unsigned_data_agreement

Stores the pre-signed loan agreement content (HTML/data) before the customer signs it.

Module 9 Notifications & Communication

🔔
In-app, email, and WhatsApp communication.
4 tables
TableDescription
notificationsPartner portal alerts: title, message, priority (HIGH/MEDIUM/LOW), scheduledAt, partnerRoleId target, brandId scope
notification_targetsMaps specific partner users to a notification. Tracks isRead, readAt, acknowledgedAt per user
whatsapp_message_logsWhatsApp delivery records: phoneNumber, templateName, status, deliveredAt, readAt, aiSensyResponse
user_notificationsIn-app notifications for customers: type, JSON payload, readAt

Module 10 Audit & Logs

📝
Complete audit trail for all system actions.
6 tables
TableWhat It Audits
user_audit_logsCustomer journey events with serial number, platformType, context JSON
partner_user_audit_logsAdmin actions on partner user accounts
brand_setting_audit_logsChanges to brand configuration
partner_user_code_audit_logsCode generation and deactivation audit
partner_user_report_logsReport download/export audit with format, dateRange, fileSize
public_loan_inquiriesPublic loan status checks via mobile/PAN with OTP verification lifecycle

Module 11 Master / Reference Data

📚
System-wide reference tables — geography, banks, configurable dropdowns.
7 tables
TableDescription
master_statesIndian states: name, 2-letter code, isUT (Union Territory) flag
master_districtsDistricts/cities linked to states. UNIQUE(name, stateId)
master_pincodes6-digit pincodes with cityId, stateId, area, status (ACTIVE/BLOCKED/SUSPECTED)
master_banksBank list with name and code
master_categoryCategories for dropdown values (e.g. USER_STATUS, REJECTION_TYPE)
master_valueValues within each category. Used for users.status_id, occupation_type_id, rejected_by_id
brand_category / brand_valueBrand-scoped configurable key-value catalog (same structure as master, but per-brand)
migrationsDatabase migration tracking: id, description, executed_at, checksum

Module 12 Lead Management

🎯
Facebook/Google ad leads with fuzzy matching against existing users.
2 tables

lead_forms

Leads captured from social media ad forms.

ColumnDescription
ad_id / campaign_id / form_idAd attribution IDs
full_name / email / phone / panCaptured lead details
is_organicOrganic vs paid traffic
statusPENDING / PROCESSED / FAILED / DUPLICATE

lead_matches

Results of matching a lead against existing users or documents in the system.

ColumnDescription
entityTypeUSER or DOCUMENT (what was matched)
matchTypeEXACT / PARTIAL / FUZZY
matchFieldEMAIL / PHONE / PAN / FULL_NAME
confidenceMatch confidence score (0.0 – 1.0)
statusACTIVE / INACTIVE / VERIFIED / REJECTED

Module 13 Account Aggregation (AA)

🏛️
RBI's Account Aggregator framework for financial data sharing with customer consent.
Customer gives consent → bank shares transaction data → system analyzes it for loan underwriting.
5 tables

AA Flow

aa_consent_requests ← customer gives consent via AA handle ├── aa_consent_notifications ← status webhooks from AA provider ├── aa_periodic_data_responses ← periodic data refresh callbacks └── aa_data_sessions ← one session per bank account (FIP) └── aa_financial_insights ← extracted financial analytics (1:1)

aa_consent_requests

ColumnDescription
clientTransactionIdUNIQUE internal tracking ID
aaCustomerHandleIdCustomer's AA handle (e.g. user@onemoney)
consentStatusPENDING / ACTIVE / REJECTED / PAUSED / REVOKED / EXPIRED
providerFINDUIT or CART
approvedAt / rejectedAt / revokedAt / expiresAtConsent lifecycle timestamps

aa_data_sessions

ColumnDescription
fipId / fipNameBank (Financial Information Provider) that shared data
maskedAccountNumberMasked account number
statusPENDING / RECEIVED / PROCESSED / FAILED / EXPIRED
jsonData / xmlData / csvDataRaw financial data in various formats
transactionSummary / balanceInfo / accountDetailsExtracted structured data
aa_json_gz_key / aa_pdf_key / aa_report_keyS3 file keys
bsa_metadata / far_metadataBSA and FAR analysis metadata
generated_bsa_report_html_keyS3 key for generated BSA report

Reference All Enums

loan_status_enum

PENDINGONBOARDINGCREDIT_EXECUTIVE_APPROVEDSANCTION_MANAGER_APPROVEDAPPROVEDAWAITING_DISBURSEMENTDISBURSEDACTIVEPARTIALLY_PAIDPOST_ACTIVEPAIDCOMPLETEDOVERDUEDEFAULTEDREJECTEDCANCELLEDSETTLEDWRITE_OFF

TransactionStatusEnum

PENDINGSUCCESSFAILEDRETRYINGCANCELLEDTIMEOUT

TransactionTypeEnum

DISBURSEMENTCOLLECTIONPARTIAL_COLLECTIONAUTOPAY_CONSENT

PaymentMethodEnum

MANUALRAZORPAYCASHFREEPAYTRINGICICIIDFCRAZORPAY_AUTOPAYLENDBOX

agreement_status_enum

NOT_SENTSENTSIGNEDREJECTEDEXPIRED

ContractSigningProvider

SIGNDESKSIGNZYDIGITAP

FeeType

processingconveniencedocumentationinterest

FeeValueType / ChargeMode

fixedpercentageINCLUSIVEEXCLUSIVE

TaxType

GSTTDSVATCESSCUSTOM

PenaltyType / closingTypeEnum

SIMPLECOMPOUNDNORMALSETTLEMENTWRITE_OFF

PermissionType

READWRITEALL

LoanTypeEnum

EMIPAYDAY_LOAN

DocumentTypeEnum

AADHAARPAN

document_status_enum

PENDINGAPPROVEDREJECTED

user_data_status

NOT_VERIFIEDVERIFIED_BY_USERVERIFIED_BY_ADMIN

AccountStatus

ACTIVEHOLDPENDINGREJECTED

gender_enum / current_status_enum

MALEFEMALEOTHERSALARIEDSELF_EMPLOYED

marital_status_enum

SINGLEMARRIEDDIVORCEDWIDOWED

ModeOfSalary

BANK_TRANSFERCASHCHEQUEOTHER

user_bank_verification

MANUALPENNY_DROPAPIPENDINGVERIFIEDFAILEDRETRYING

employment_type_enum

FULL_TIMEPART_TIMECONTRACTTEMPORARYINTERNFREELANCECASUALGIGAPPRENTICE

ResidenceTypeEnum

RENTEDOWNED

RelationshipEnum

SPOUSEBROTHERSISTERFATHERMOTHERFRIENDCOLLEAGUEOTHER

RejectionType / RejectionSource

DOCUMENT_INSUFFICIENTCREDIT_SCORE_LOWKYC_FAILEDADMINSYSTEMAUTOMATEDSUPPORT

platform_type

WEBPARTNER

MigrationStatus

ONBOARDED_NEWMIGRATEDPARTIALLY_MIGRATED

AAConsentStatus / AADataStatus

PENDINGACTIVEREJECTEDPAUSEDREVOKEDEXPIREDRECEIVEDPROCESSEDFAILED

AAProvider

FINDUITCART

PennyDropStatus

SUCCESSFAILEDPENDINGNAME_MISMATCH

PanVerificationStatus

SUCCESSFAILEDINVALIDPENDING

ReloanStatus

PENDINGAPPROVEDREJECTEDCANCELLED

EligibilityStatusEnum / evaluation_stage_enum

ELIGIBLENOT_ELIGIBLEONETWOTHREEFOUR

LeadFormStatus / LeadMatchType / LeadMatchField

PENDINGPROCESSEDFAILEDDUPLICATEEXACTPARTIALFUZZYEMAILPHONEPANFULL_NAME

EmailType

SEVEN_DAY_REMINDERTHREE_DAY_REMINDERONE_DAY_REMINDERSAME_DAY_REMINDEROVERDUE_REMINDERPAYMENT_DUE_REMINDERFINAL_NOTICECUSTOM_REMINDER

OpsApprovalStatusEnum

PENDINGAPPROVEDREJECTED

BrandProviderType

PENNYDROPLOAN_AGREEMENTBREPAN_DETAILS_PLUSPHONE_TO_UANUAN_TO_EMPLOYMENTUPI_AUTOPAYFULL_PAYMENTPART_PAYMENTAADHAAR_DIGILOCKERDISBURSEMENTSMSEMAILWHATSAPPACCOUNT_AGGREGATION

BrandProviderName

DIGITAPNEOKREDSIGNDESKSIGNZYSIGNZY_HYBRIDFINBOXSCOREMECARTEQUIFAXCIRPROKYCKARTCMS_FINTECHCLOUDRAZORPAYRAZORPAY_AUTOPAYCASHFREEPAYTRINGICICIIDFCMANUALLENDBOXMSG91SENDGRIDBREVOMAILGUNZEPTONEXMONIMBUSITSMSGATEWAYHUBTWILIOFINDUIT

certificate_type_enum

NO_DUE_LETTERWRITE_OFF_LETTERSETTLEMENT_LETTER

NonRepaymentDateType

BRAND_NON_REPAYMENTPARTNER_UNAVAILABILITY

brand_status_enum

APPROVEDREJECTEDHOLDACTIVEPENDINGDORMANT

BlogStatus / pincode_status

DRAFTPUBLISHEDARCHIVEDACTIVEBLOCKEDSUSPECTED

PublicInquiryStatus

INITIATEDOTP_SENTOTP_VERIFIEDCOMPLETEDFAILEDEXPIRED

notification_priority_enum

HIGHMEDIUMLOW
Generated from prisma/schema.prisma · 2026-03-20 · LOS Backend Database Documentation