# Exhaustive Module Data Flow & Schema Analysis

This document provides a 100% comprehensive breakdown of the Dealer Onboarding & Lifecycle Management system. It includes every enum, every database key, and every workflow transition to support a thorough gap analysis.

---

## 1. Global Constants & Enums (`constants.ts`)

These constants are the primary drivers of application logic and stage-gate controls.

### 👥 User Roles (`ROLES`)
| Key | Value | Role Description |
| :--- | :--- | :--- |
| `DD` | `DD` | Dealer Development Executive (Field) |
| `DD_ZM` | `DD-ZM` | DD Zone Manager (Zone) |
| `RBM` | `RBM` | Regional Business Manager |
| `ZBH` | `ZBH` | Zone Business Head |
| `DD_LEAD` | `DD Lead` | Lead for Dealer Development |
| `DD_HEAD` | `DD Head` | Head of Dealer Development |
| `NBH` | `NBH` | National Business Head |
| `LEGAL_ADMIN` | `Legal Admin` | Legal Dept (Verification/Letters) |
| `SUPER_ADMIN` | `Super Admin` | System Administrator (Bypass) |
| `FINANCE` | `Finance` | Finance Dept (Payments/Clearance) |
| `DEALER` | `Dealer` | The Business Partner / Applicant |
| `ARCHITECTURE` | `ARCHITECTURE` | Site Layout & Design Team |
| `FDD` | `FDD` | Field Due Diligence Agency |
| `CCO` | `CCO` | Chief Commercial Officer |
| `CEO` | `CEO` | Chief Executive Officer |

### 🛠️ Application Lifecycle (`APPLICATION_STATUS`)
| Status | Functional Meaning |
| :--- | :--- |
| `Pending` | Initial lead entry |
| `Submitted` | Form submitted by Prospect |
| `Questionnaire Pending` | Sent to prospect for survey |
| `Shortlisted` | DD Lead approval for evaluation |
| `FDD Verification` | Agency conducting site/back background check |
| `LOI Issued` | Intent letter issued (Commercial check complete) |
| `EOR In Progress` | Site construction/readiness audit |
| `LOA Issued` | Final Appointment Letter issued |
| `Onboarded` | System provisioning complete (Active Dealer) |

> **Full status list (sequential order, UI mapping, parallel statutory/architecture):** see [ONBOARDING_APPLICATION_STATUSES.md](./ONBOARDING_APPLICATION_STATUSES.md).

### 📦 Request Types (`REQUEST_TYPES`)
- `application`: New Onboarding
- `resignation`: Voluntary Exit
- `constitutional`: Legal entity change
- `relocation`: Site movement

---

## 2. Onboarding Module: Schema & Transitions

### 🔑 Primary Model: `Application` (`applications` table)
| Field | Type | Description |
| :--- | :--- | :--- |
| `id` | UUID | Internal Database PK |
| `applicationId` | String | Public ID (e.g., APP-2024-001) |
| `businessType` | Enum | `Dealership` or `Studio` |
| `applicantName`| String | Legal name of primary applicant |
| `experienceYears`| Integer | Industry experience |
| `investmentCapacity`| String | Range of funds available |
| `currentStage` | Enum | Current workflow stage (e.g., `ZBH`) |
| `overallStatus` | Enum | High-level status (e.g., `LOI Issued`) |
| `score` | Decimal | Aggregate Questionnaire/Interview score |
| `isShortlisted` | Boolean | Gate for proceeding to interviews |
| `documents` | JSONB | Active document snapshot {type, url, status} |
| `timeline` | JSONB | Sequential history of actions |

### 🔄 Sub-Entities captured during Onboarding
| Model | Key Fields Captured |
| :--- | :--- |
| **Interview** | `level` (1, 2, 3), `scheduleDate`, `type` (Virtual/Physical) |
| **FDD Report** | `findings` (Text), `recommendation` (Recommended/Not), `verifiedAt` |
| **Security Deposit**| `amount`, `paymentDate`, `transactionRef`, `status` |
| **EOR Checklist** | `auditorId`, `auditDate`, `items` (Compliant/Non-Compliant) |

---

## 3. Post-Onboarding Modules: Detailed Schema

### 🏗️ Relocation Module (`relocation_requests` table)
| Field | Type | Description |
| :--- | :--- | :--- |
| `requestId` | String | Unique Relocation ID |
| `outletId` | UUID | FK to the specific outlet being moved |
| `relocationType`| Enum | `Within City`, `Intercity`, `Interstate` |
| `newAddress` | Text | Destination street address |
| `newCity/State` | String | Destination geo-attributes |
| `reason` | Text | Business justification for relocation |
| `currentStage` | Enum | `ASM Review` -> `NBH` -> `Legal` |

### ⚖️ Constitutional Change (`constitutional_changes` table)
| Field | Type | Description |
| :--- | :--- | :--- |
| `changeType` | Enum | `Ownership Transfer`, `Partnership Change`, etc. |
| `description` | Text | Summary of legal restructuring |
| `oldValue` | String | Current constitution (Snapshot) |
| `newValue` | String | Proposed constitution |

### 🚪 Offboarding (Termination & Resignation)
Both flows merge into the **Full & Final (F&F)** settlement.

| Module | Primary Keys | Clearance Tracks |
| :--- | :--- | :--- |
| **Resignation** | `resignationType`, `lastOperationalDate`, `reason` | Spares, Service, Accounts, Logistics |
| **Termination** | `category` (Non-performance/Compliance), `proposedLwd` | Show Cause Notice, Personal Hearing Record |
| **FnF Settlement**| `totalReceivables`, `totalPayables`, `netAmount` | Line items for specific credit/debit memos |

---

## 4. Document Matrix (Gap Analysis Reference)

Every request type captures a specific subset of `DOCUMENT_TYPES`. Missing a document in a stage is a common "Gap".

| Document Type | Captured In | Mandatory For |
| :--- | :--- | :--- |
| `GST Certificate` | Application / Const. Change | All entities |
| `Partnership Deed` | Application / Const. Change | Partnership firms |
| `New Lease Agreement`| Relocation | Site movement |
| `NOC Landlord` | Relocation | Existing site exit |
| `SCN Response` | Termination | Show Cause phase |
| `Hearing Record` | Termination | Personal Hearing phase |
| `Exit Feedback` | Resignation | Dealer exit |

---

## 5. Audit & Traceability Logic

Every action across all modules is tracked via these shared models:

### `AuditLog`
- `userId`: Who did it.
- `action`: `CREATED`, `UPDATED`, `APPROVED`, etc.
- `oldData` / `newData`: JSON snapshots of the record BEFORE and AFTER the change.

### `Worknote`
- `requestId`: Link to Application/Relocation/etc.
- `noteText`: Threaded comments between field and HO teams.
- `noteType`: `general`, `system`, or `private`.

### `Document Types` (Exhaustive List)
| Enum Key | Display Name |
| :--- | :--- |
| `GST_CERTIFICATE` | GST Certificate |
| `PAN_CARD` | PAN Card |
| `AADHAAR` | Aadhaar |
| `PARTNERSHIP_DEED` | Partnership Deed |
| `LLP_AGREEMENT` | LLP Agreement |
| `INCORPORATION_CERTIFICATE` | Certificate of Incorporation |
| `MOA` | MOA |
| `AOA` | AOA |
| `BOARD_RESOLUTION` | Board Resolution |
| `PROPERTY_DOCUMENTS` | Property Documents |
| `BANK_STATEMENT` | Bank Statement |
| `NODAL_AGREEMENT` | Nodal Agreement |
| `CANCELLED_CHECK` | Cancelled Check |
| `FIRM_REGISTRATION` | Firm Registration |
| `RENTAL_AGREEMENT` | Rental Agreement |
| `VIRTUAL_CODE` | Virtual Code Confirmation |
| `DOMAIN_ID` | Domain ID Setup |
| `MSD_CONFIG` | MSD Configuration |
| `LOI_ACK` | LOI Acknowledgement |
| `FDD_REPORT` | FDD Final Audit Report |
| `KT_MATRIX` | Kepner Tregoe Matrix |
| `INTERVIEW_EVALUATION` | Interview Evaluation Sheet |
| `SITE_READINESS` | Site Readiness Report |
| `CIBIL_REPORT` | CIBIL Report |
| `LOA_ACCEPTANCE` | LOA Acceptance Copy |
| `ARCHITECTURE_BLUEPRINT` | Architecture Blueprint |
| `SITE_PLAN` | Site Plan |
| `STATUTORY_AUDIT` | Statutory Approval Certificate |
| `BANK_GUARANTEE` | Bank Guarantee Document |
| `RELOCATION_*` | 10+ Relocation specific docs (Photos, NOC, Fire Safety, etc.) |

### `Audit Actions` (System Traceability)
`CREATED`, `UPDATED`, `APPROVED`, `REJECTED`, `DELETED`, `LOGIN`, `LOGOUT`, `STAGE_CHANGED`, `SHORTLISTED`, `DISQUALIFIED`, `QUESTIONNAIRE_SUBMITTED`, `DOCUMENT_UPLOADED`, `DOCUMENT_VERIFIED`, `INTERVIEW_SCHEDULED`, `LOI_REQUESTED`, `LOA_GENERATED`, `EOR_AUDIT_SUBMITTED`, `PAYMENT_UPDATED`, `RESIGNATION_SUBMITTED`.

## 9. Advanced Approval Policies (`StageApprovalPolicy`)

To enforce strict governance, certain stages (Interviews, LOI, LOA) require multiple independent approvals.

| Mode | Rule | Evaluation Logic |
| :--- | :--- | :--- |
| `MIN_N` | Minimum Count | Requires at least `N` unique users to approve, regardless of role. |
| `ROLE_MANDATORY`| Specific Roles | Requires unique approvals from EACH role listed in `requiredRoles`. |
| `ALL` | Full Concensus | Every assigned `RequestParticipant` for that stage must approve. |

**Evaluation Engine**: `WorkflowService.evaluateStagePolicy()`
- **Super Admin Bypass**: A Super Admin approval automatically satisfies any policy.
- **Unique Actor Check**: Prevents a single user with multiple roles from satisfying multiple requirements alone.

---

## 10. Auto-Assignment & Territory Mapping

The system automatically assigns evaluators based on the **District -> Region -> Zone** hierarchy linked to each application.

### 🗺️ Evaluator Mapping Matrix
| Stage / Level | Role Sources | Logic / Hierarchy |
| :--- | :--- | :--- |
| **Level 1 Interview** | `DD-ZM`, `RBM` | Primary District Manager (`zmId`) + Regional Manager (`rbmId`). |
| **Level 2 Interview** | `ZBH`, `DD Lead`| Zone Business Head (`zbhId`) + DD Lead assigned to that Zone. |
| **Level 3 Interview** | `NBH`, `DD Head`| National Level Roles (Active status check). |
| **LOI Approval** | `Finance`, `Head`, `NBH`| National Level (Requires 3 unique approvals). |
| **LOA Approval** | `DD Head`, `NBH`| National Level (Requires 2 unique approvals). |

**Metadata capture**: Assignments are stored in `RequestParticipant` with `joinedMethod: 'auto'` and `metadata.autoMapped: true`.

---

## 11. System Fail-Safe (Retriggering)

If any territory mapping is missing (e.g., a District has no assigned ASM) or if a manager changes mid-flow, the system provides a **Retrigger** capability.

### 🔄 The Retrigger Process
1. **API Endpoint**: `POST /onboarding/:id/retrigger-evaluators`
2. **Step A (Cleanup)**: Deletes all participants where `metadata.autoMapped = true`. This preserves manual notes and manually added participants.
3. **Step B (Hierarchy Sync)**: Invokes `syncLocationManagers()` to refresh the `District` table with current managers from `UserRole`.
4. **Step C (Re-assignment)**: Re-runs the `assignStageEvaluators` logic to map the correct current users to all 3 interview levels and approval stages.

---
*Generated: April 2026 | Comprehensive System Data Flow Analysis v2.1 (Advanced Features)*

