notification service enhanced even more detailed way added more templates documentented i splitted based on modulewise

This commit is contained in:
laxman h 2026-04-30 18:49:11 +05:30
parent 3c95146f4a
commit 2b73036bb9
37 changed files with 1272 additions and 5750 deletions

View File

@ -1726,39 +1726,40 @@ Centralized workspace for Finance. Two tabs: **Onboarding** (security deposit ve
## Notification / Email Trigger Summary — All Modules ## Notification / Email Trigger Summary — All Modules
| Trigger Event | Channel | Recipients | | Trigger Event | Channel | Recipients | Template Code (Master Seeder) |
|---|---|---| |---|---|---|---|
| Application Submitted (Opportunity) | Email + WhatsApp | Applicant (credentials + questionnaire link) | | Application Submitted (Opportunity) | Email + WhatsApp | Applicant (credentials + questionnaire link) | `OPPORTUNITY` |
| Application Submitted (Non-Opportunity) | Email | Applicant (non-opportunity notice) | | Application Submitted (Non-Opportunity) | Email | Applicant (non-opportunity notice) | `NON_OPPORTUNITY` |
| Application Shortlisted | Email + In-app | DD-ZM, RBM | | Application Shortlisted | Email + In-app | DD-ZM, RBM | `APPLICANT_SHORTLISTED` |
| Application Rejected | Email + WhatsApp | Applicant | | Application Rejected | Email + WhatsApp | Applicant | `APPLICANT_REJECTED` |
| Interview Scheduled | Google Calendar + Email + WhatsApp | All evaluators + Applicant | | Interview Scheduled | Google Calendar + Email + WhatsApp | All evaluators + Applicant | `INTERVIEW_SCHEDULED` |
| Questionnaire Completion Reminder | WhatsApp | Applicant | | Questionnaire Completion Reminder | WhatsApp | Applicant | `QUESTIONNAIRE_REMINDER` |
| FDD Report Submitted | In-app + Email | Finance, DD-Admin | | FDD Report Submitted | In-app + Email | Finance, DD-Admin | `GENERIC_NOTIFICATION` |
| Finance Verified (Deposit) | In-app + Email | DD-Admin, DD-Lead | | Finance Verified (Payment/Deposit) | In-app + Email | DD-Admin, DD-Lead | `ONBOARDING_PAYMENT_VERIFIED` |
| LOI Document Request | Email (NOT WhatsApp) | Applicant | | LOI Document Request | Email | Applicant | `LOI_ISSUED` |
| LOI Issued | Official Email (NOT WhatsApp) | Applicant | | LOI Issued | Official Email | Applicant | `LOI_ISSUED` |
| LOI Issuance Confirmed | Email + In-app | Finance, DD-Head, NBH | | LOI Issuance Confirmed | Email + In-app | Finance, DD-Head, NBH | `LOI_ISSUANCE_CONFIRMED` |
| Dealer Code Generated | In-app | DD-Admin, Finance, Legal | | Dealer Code Generated | In-app + Email | DD-Admin, Finance, Legal | `DEALER_CODE_READY` |
| Statutory Verification Complete | In-app | DD-Admin | | EOR 100% Complete | In-app | DD-Head, NBH | `EOR_COMPLETED` |
| EOR 100% Complete | In-app | DD-Head, NBH | | Dealership Live (Inauguration) | In-app + Email | All stakeholders | `INAUGURATION_COMPLETED` |
| Dealership Live (Onboarded) | In-app | All stakeholders | | Resignation Request Received | Email | Dealer (Acknowledgement) | `RESIGNATION_RECEIVED` |
| Resignation Request Submitted | In-app | DD-Admin, DD-ASM, DD-Head, ZBH, NBH | | Resignation Request Submitted | In-app + Email | DD-Admin, DD-ASM, DD-Head, ZBH, NBH | `RESIGNATION_SUBMITTED` |
| Resignation Send Back / Revoke | Work Notes + In-app + Email | Dealer + Internal teams | | Resignation Send Back / Revoke | Work Notes + Email | Dealer + Internal teams | `RESIGNATION_UPDATE` |
| NBH Resignation Approved | In-app | DD-Lead, RBM, ZBH, Finance, Legal | | Resignation Approved (NBH) | In-app + Email | DD-Lead, RBM, ZBH, Finance, Legal | `RESIGNATION_APPROVED` |
| Resignation Acceptance Letter Uploaded | In-app | DD-Admin, DD-ASM | | Termination Request Created | In-app + Email | RBM + DD-ZM | `TERMINATION_INITIATED` |
| Resignation Withdrawn | In-app | DD-ASM, DD-Admin, stakeholders | | SCN Issued | Email (via DD-Admin) | Dealer | `TERMINATION_SCN_ISSUED` |
| Termination Request Created | In-app | RBM + DD-ZM | | Legal Letter Generated | In-app + Email | Legal, DD-Lead, DD-Admin, Finance | `TERMINATION_LETTER_ISSUED` |
| SCN Issued | Email (via DD-Admin) | Dealer | | Termination Final Closure | Email | Dealer (Access Revoked) | `TERMINATION_FINAL_CLOSURE_DEALER` |
| CEO + CCO Authorization | In-app | Legal, DD-Lead, DD-Admin, Finance | | F&F Initiated | In-app + Email | Finance, all 16 departments | `FNF_INITIATED` |
| Termination Letter Uploaded | In-app | DD-Lead, DD-Admin, Finance (all linked personas) | | F&F Summary Prepared | In-app + Email | Finance Review Team | `FNF_SUMMARY_PREPARED` |
| F&F Initiated | In-app + Email | Finance, all 16 departments | | F&F Settlement Approved | In-app + Email | DD-Admin, Legal, DD-Lead | `FNF_SETTLEMENT_APPROVED` |
| Department Clearance SLA Reminder | In-app + Email | Respective department | | Constitutional Change Submitted | In-app + Email | ASM, RBM | `CONSTITUTIONAL_CHANGE_SUBMITTED` |
| Finance Approved Settlement | In-app + Email | DD-Admin, Legal | | Constitutional Change Approved | Email | Dealer | `CONSTITUTIONAL_CHANGE_APPROVED` |
| F&F Closed | In-app | DD-Lead, NBH, Legal, DD-Admin | | Relocation Request Received | Email | Dealer (Acknowledgement) | `RELOCATION_RECEIVED` |
| SLA Breach | In-app + Email | Activity owner + escalation chain | | Relocation Request Submitted | In-app + Email | ASM, RBM | `RELOCATION_SUBMITTED` |
| Work Note @mention | In-app + Email | Tagged user | | Relocation Approved | Email | Dealer | `RELOCATION_APPROVED` |
| Opportunity Window Activated | In-app | DD-ZM, RBM for assigned area | | SLA Breach / Reminder | In-app + Email + WhatsApp | Activity owner + escalation chain | `SLA_REMINDER` |
| Work Note @mention | In-app + Email | Tagged user | `WORKNOTE_NOTIFICATION` |
--- ---

View File

@ -1,89 +1,6 @@
# RE Onboarding & Offboarding System # RE Onboarding
# Requirements
``` ```
System Requirements Specifications
```
## 16 - Oct- 2025
## Version 1. 4
## Contents
- Change Log
- 1.1 Change Log Version 2.0
- 1.2 Change Log Dealer Self-Service Enablement
- 1 System Overview & Problem Statement
- 2 Intended Audience
- 2.1 Business & Functional Users
- 2.2 External & Integrated Stakeholders
- 3 Definitions and Acronyms
- 4 HiFi Wireframes & Flow of Application
- 4.1 Dealer onboarding - Process Flow Overview
- 4.2 Dealer Resignation Process Flow Overview
- 4.3 Dealer Termination Process Flow Overview
- 4.4 Dealer Full & Final (F&F) Settlement Process Flow
- 4.5 Finance Team Process Flow
- 5 System Features & Requirements
- 6 Dealer onboarding
- 6.1 Dealership Application Form
- 6.2 SSO Login
- 6.3 Dashboard
- 6.4 Opportunity & Non Opportunity
- 6.5 Questionnaire Response
- 6.6 Shortlisting Process
- 6.7 Shortlisted Applicants
- 6.8 Application Detail View
- 6.9 Interview Scheduling & Coordination
- 6.10 Interview Evaluation & Feedback Management
- 6.11 Interview Feedback & Evaluation Summary
- 6.12 Application Approval & Rejection Workflow
- 6.13 Work Notes & Internal Communication Trail
- 6.14 System Notifications & Alerts
- 6.15 FDD (Financial Due Diligence) & Finance Module
- 6.16 LOI Approval & Issuance
- 6.17 Dealer Code Generation, Architectural Work & Statutory Documentation............
- 6.18 LOA Issuance, Essential Operating Requirements & Inauguration
- 6.19 Essential Operating Requirements (EOR) Checklist
- 6.20 Progress Tracker.......................................................................................................
- 6.21 Central Document Repository
- 6.22 Audit Trail & Activity Log..........................................................................................
- 7 Dealer Resignation
- 7.1 Dealer Resignation Request (Initiation)
- 7.2 Resignation Management Dashboard
- 7.3 Resignation Details & Review
- 7.4 Resignation Request Review & Action Management
- 7.5 Resignation Progress Tracker
- 7.6 Documents & Audit Trail
- 8 Termination
- 8.1 Create Termination Request
- 8.2 Termination Ticket overview
- 8.3 Termination Approval & Review Process
- 8.4 Termination Progress Timeline
- 9 Admin Section
- 9.1 Master Configuration Organization
- 9.2 Zone, Region & Area Configuration
- 9.3 Roles & permissions
- 9.4 SLA Configuration & Escalation Management
- 9.5 Email & Letter Templates Management
- 9.6 Opportunity Management (Geography & Window Setup)
- 10 F&F Case
- 10.1 F&F Settlement Progress Timeline
- 10.2 Department Responses
- 11 Finance Dashboard
- 11.1 Finance Dashboard Page
- 11.2 F&F Settlement Module
- 12 Dealer Persona
- 12.1 Dealer Resignation
- 12.2 Dealer Constitutional Change Management
- 13 Non-Functional Requirements
- 14 Technology Matrix
- 15 Infra requirements & System Hygiene
- 16 Not in scope
## Change Log ## Change Log
@ -122,26 +39,7 @@ System Requirements Specifications
- Corrected the workflow sequence to ensure that **LOA is issued prior to initiating the** - Corrected the workflow sequence to ensure that **LOA is issued prior to initiating the**
**EOR checklist** , with EOR serving as the final readiness validation before go-live. **EOR checklist** , with EOR serving as the final readiness validation before go-live.
**1.1.5 Dealer Resignation Access & Workflow Enhancements**
- Enabled **dealer portal access** for initiating resignation requests and uploading required
information.
- Clarified that the **Legal team issues the Resignation Acceptance Letter** in all cases.
- Expanded review authority to allow **ZBH, DD Lead, DD Head, and NBH** to **Send Back or**
**Revoke resignation requests** , with communication routed through **Work Notes**.
- Confirmed that **Full & Final (F&F) settlement is triggered strictly on the Last Working**
**Day (LWD)** and not based on approval date.
**1.1.6 Termination Workflow Governance Updates**
- Clarified that **CEO is the final approving authority** for dealer termination cases.
- Included **CCO and CEO** as approval authorities with **Approve / Hold / Reject** options.
- Confirmed that the **Legal team issues termination letters only after CEO approval**.
- Removed **dealer portal access** from termination workflows.
- Extended **Send Back / Revoke** authority to **ZBH and DD Lead** for termination reviews.
- Aligned **F&F trigger for termination** to occur strictly on the **Last Working Day (LWD)**.
**1.1.7 Role & Persona Alignment** **1.1.7 Role & Persona Alignment**
@ -172,70 +70,7 @@ System Requirements Specifications
clearly scoped responsibilities. clearly scoped responsibilities.
### 1.2 Change Log Dealer Self-Service Enablement
**Version:** v2.
**Section Impacted:** Section 12 Dealer Portal (12.1 onwards)
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Dealer Feature Enablement (Section 12 onwards)
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 5 - Jan- 2026
**1.2.1 Introduction of Dealer Portal**
- Introduced a **Dealer Portal capability** enabling onboarded dealers to initiate and track
post-onboarding lifecycle requests through the portal.
- Dealer actions are governed by **role-based access controls** , approval hierarchies, and
audit mechanisms.
**1.2.2 Dealer Resignation Enablement**
- Enabled **dealer-initiated resignation requests** at outlet level via the portal.
- Added structured resignation submission with:
o Last Operational Date (Sales & Services)
o Reason for resignation
o Mandatory document readiness guidance
- Enabled **dealer withdrawal option** for resignation requests **only until the case is**
**pending with NBH**.
- Clarified that **Legal team issues the Resignation Acceptance Letter** post approvals.
- Ensured **F&F settlement is triggered based on Last Working Day (LWD)** and not
approval date.
- Restricted dealer portal access **post resignation closure**.
**1.2.3 Dealer Relocation Request Enablement**
- Enabled dealers to **initiate and track relocation requests** through a guided workflow.
- Added support for:
o Manual or map-based location entry
o Distance calculation from existing location
o Property type selection and expected relocation date
- Introduced **document-driven relocation validation** , including statutory, legal, property,
and infrastructure documents.
- Implemented **multi-level approval workflow** with Work Notesbased communication
and audit trail.
- Ensured dealer has **view and upload access only** , with approvals retained by RE
stakeholders.
**1.2.4 Dealer Constitutional Change Enablement**
- Enabled dealers to **initiate constitutional change requests** post onboarding.
- Supported all approved constitution change scenarios:
o Proprietorship, Partnership, LLP, and Private Limited permutations
- Implemented **dynamic document requirement determination** based on target
constitution.
- Explicitly confirmed **no OCR-based document validation** ; all validations are manual and
role-driven.
- Ensured statutory compliance via Legal review before master data updates.
**1.2.5 Post-Exit Access Control**
- Enforced system rule to **revoke dealer portal access** once resignation or termination is
completed.
## 1 System Overview & Problem Statement ## 1 System Overview & Problem Statement
@ -323,45 +158,8 @@ RE standards.
The Dealer role is enabled to perform the following activities: The Dealer role is enabled to perform the following activities:
```
- **Resignation Initiation**
```
The dealer can initiate the resignation process directly through the portal , submit the
reason for exit, and track the status of the request across the defined review, clearance,
and closure stages.
```
- **Relocation Request Submission**
```
The dealer can submit a relocation request in scenarios where there is an intent to shift
the dealership from the current location to a new proposed location. The request is
routed for internal feasibility assessment, validation, and management approval before
execution.
```
- **Change in Constitution Request**
```
The dealer can initiate a Change in Constitution request to seek approval from RE
management for ownership or structural changes within the dealership. Upon approval,
the dealer may proceed with the legally compliant transition.
```
```
Supported Change in Constitution scenarios include:
```
```
o Proprietorship (Single Owner) → Partnership
o Proprietorship → LLP (Limited Liability Partnership)
o Proprietorship → Private Limited
o Partnership → LLP
o Partnership → Private Limited
o Private Limited → LLP
o Private Limited → Partnership
```
All dealer-initiated requests are subject to **defined validations, mandatory document
submissions, role-based reviews, and approvals**. The dealers access is **restricted to initiation,
document upload, and status visibility** , with **final decision-making authority retained by
authorized internal stakeholders of RE**
### 2.2 External & Integrated Stakeholders ### 2.2 External & Integrated Stakeholders
@ -553,395 +351,8 @@ o Site validation and inspection
- The entire lifecycle remains accessible under **Audit Trail** for future reference, compliance, - The entire lifecycle remains accessible under **Audit Trail** for future reference, compliance,
or offboarding workflows. or offboarding workflows.
### 4.2 Dealer Resignation Process Flow Overview
**4.2.1.1 Overview**
```
The Dealer Resignation Process manages the structured offboarding of a dealership initiated
by the dealer. The process begins when a dealer formally submits their resignation via
email to the Area Sales Manager (ASM) , after which the workflow transitions into the
system-managed approval sequence.
```
```
Dealer resignation requests are initiated by the dealer through the portal and subsequently
reviewed and processed by Admin, Finance, Legal, and relevant business stakeholders.
```
```
This flow ensures that each resignation is verified, discussed, and approved across all
required levels — maintaining proper documentation, compliance, and traceability until the
final Legal Acceptance Letter is issued.
```
**4.2.2 Step-by-Step Process Flow**
```
4.2.2.1 Dealer Initiation
```
- The dealer submits a **formal resignation email** on the dealerships official letterhead to
the **ASM**.
- The resignation reason must be clearly stated (e.g., personal, financial, business
restructuring).
- The **dealer is provided portal access** to initiate the resignation request directly through
the system. The dealer submits resignation details, reason for exit, and proposed
timeline via the portal, after which the request enters the internal review and clearance
workflow.
```
4.2.2.2 ASM Review
```
- The **ASM** reviews the dealers resignation request and supporting letter.
- Uploads the **resignation email** and **dealers letterhead document** onto the portal.
- Adds remarks summarizing the discussion and reason for resignation.
- Forwards the request to **RBM + DD-ZM** for evaluation.
```
4.2.2.3 RBM + DD-ZM Joint Evaluation
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** review the uploaded documents.
- Conduct a joint discussion with the dealer to confirm the intent and understand any
issues.
- Uploads the **Minutes of Meeting (MOM)** or discussion summary.
- Adds comments and recommendations before forwarding to **Zonal Business Head**
**(ZBH)**.
- Actions available at this stage:
o **Approve** → Send forward for next-level review
o **Send Back for Clarification** → Returns to ASM
o **Withdraw** → Cancels the request (with remarks logged)
```
4.2.2.4 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the resignation summary and all remarks.
- Adds their comments and recommendations.
- Forwards the request to **DD-Lead** through the system.
- Worknote is updated automatically to reflect action and timestamp.
- The resignation request is reviewed by authorized business stakeholders,
including **RBM, ZBH, and DD-Head**. During the review stage, the **ZBH is authorized to**
```
Send Back or Revoke the resignation request for clarification or correction. Send Back
actions are communicated to the dealer and internal teams through Work Notes , with
mandatory remarks captured for traceability.
```
```
4.2.2.5 DD-Lead Review
```
- The **DD-Lead** consolidates all discussions, documents, and feedback.
- Prepares a **Resignation Presentation** with recommendations and supporting data.
- Uploads the presentation to the portal.
- Forwards the case to **NBH** for final decision.
- The resignation request is reviewed by the **DD-Lead and DD-Head**. At this stage, both
roles are authorized to **Send Back or Revoke** the resignation request for clarification,
correction, or reconsideration. **Send Back actions are communicated through Work**
**Notes** , with **mandatory remarks** recorded for audit and traceability.
```
4.2.2.6 NBH Final Approval
```
- The **National Business Head (NBH)** reviews the entire resignation dossier.
- Adds final remarks with one of the following outcomes:
o **Approve** → Case moves automatically to Legal for letter issuance.
o **Send Back for Clarification** → Returns to DD-Lead or ZBH for revalidation.
o **Hold** → Temporarily pauses the process pending further discussion.
- Upon approval, the system triggers a **Worknote Notification** to DD-Lead, RBM, ZBH, and
Finance teams.
- The resignation request is reviewed by the **NBH** , who may **Approve, Send Back, or**
**Revoke** the request based on business considerations. Any **Send Back or Revoke action**
**must be accompanied by remarks recorded in Work Notes** , ensuring transparent
communication and governance.
```
4.2.2.7 Legal Acceptance Letter
```
- Once approved by **NBH** , the request is **auto-assigned to the Legal team**.
- Legal verifies the uploaded resignation and issues a **Resignation Acceptance Letter**.
- The letter is uploaded to the portal, visible to all relevant personas including **DD-**
**Admin** and **DD-AM**.
- Legal can also raise clarifications through worknotes if required.
- Upon completion of all approvals, the **Legal team issues the official Resignation**
**Acceptance Letter** and shares it with the dealer through authorized communication
channels.
```
4.2.2.8 DD-Admin Closure
```
- The **DD-Admin** downloads and shares the final **Resignation Acceptance Letter** with the
dealer.
- Marks the resignation as completed and triggers the **F&F (Full and Final) process** by
forwarding the case to the Finance team.
- The **Full & Final (F&F) settlement process is initiated only on the Last Working Day**
**(LWD) of the dealership**. The system shall **enable and trigger the F&F workflow strictly**
**based on the LWD date** , and **not based on the resignation approval date**.
### 4.3 Dealer Termination Process Flow Overview
```
4.3.1.1 Overview
```
```
The Dealer Termination Process governs the structured offboarding of a dealership initiated
internally by Royal Enfield due to operational, contractual, or ethical concerns.
It ensures that any termination—whether due to working-capital issues, poor performance,
or unethical practices —is investigated, documented, reviewed at multiple managerial levels,
and legally validated before final execution. The process maintains full transparency and
traceability through digital records, comments, and worknotes until the Termination
Letter is issued and the Full & Final (F&F) settlement begins.
```
**4.3.2 Step-by-Step Process Flow**
```
4.3.2.1 ASM Case Initiation
```
- The **Area Sales Manager (ASM)** regularly visits dealers and records **Minutes of Meeting**
**(MOM)** for performance or compliance concerns.
- After two consecutive unsatisfactory commitments or escalations, the ASM initiates
a **Termination Request** in the portal.
- Fills all operational details (Dealer Code, LOI, LOA, Sales Data, etc.), selects
a **Termination Category** (Working Capital, Performance, Unethical Practice), and
uploads supporting documents (MOMs, commitments, dealer letters).
- Submits the case to **RBM + DD-ZM** for review.
```
4.3.2.2 RBM + DD-ZM Review
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** jointly evaluate the case.
- Conduct a meeting with the dealer and record fresh MOMs; upload dealer
commitments on letterhead.
- Provide remarks and supporting evidence.
- Actions available:
o **Approve** → Forward to ZBH
o **Send Back for Clarification** → Returns to ASM with comments
o **Withdraw** → Terminates workflow with justification
```
4.3.2.3 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the full chronology (ASM visits, RBM/DD-ZM
remarks, uploaded MOMs).
- Validates escalation authenticity and dealer communication record.
- Adds remarks and forwards to **DD-Lead** for deeper review.
- The termination request is reviewed by the **ZBH** , who is authorized to **Approve, Send**
**Back, or Revoke** the termination request. **Send Back actions are communicated**
**through Work Notes** , with **mandatory remarks** recorded for traceability.
```
4.3.2.4 DD-Lead Review & Legal Assignment
```
- The **DD-Lead** cross-verifies case chronology with all stakeholders (ASM, RBM, ZBH).
- Prepares a **Termination Presentation** summarizing facts, dealer history, and
recommendations.
- Assigns the case to **Legal Team** for inputs through the system (visible in worknotes).
- The termination request is reviewed by the **DD-Lead** , who is authorized to **Send Back or**
**Revoke** the termination request for clarification or reconsideration. All such actions
require **mandatory remarks captured in Work Notes**.
```
4.3.2.5 Legal Verification
```
- The **Legal Team** reviews documentation, ensures contractual breaches are well-
supported, and checks all precedents.
- May raise queries via **Worknotes** or **Send Back** the case to DD-Lead for clarification.
- Once satisfied, forwards the verified case back to **DD-Lead** for next action.
```
4.3.2.6 DD-Lead → DD-Head Review
```
- The **DD-Lead** attaches Legals feedback and forwards the case to **DD-Head** for strategic
review.
- **DD-Head** validates the case, evaluates impact, and presents it to **National Business**
**Head (NBH)** for final business decision.
```
4.3.2.7 NBH Evaluation
```
- The **NBH** reviews all documentation and Legal remarks.
- May choose one of three actions:
o **Go Ahead** → Approve for issuance of **Show Cause Notice (SCN)**
o **Hold Decision** → Pause temporarily for further monitoring or negotiation
o **Raise Query** → Sends back to DD-Lead for additional input
```
4.3.2.8 Show Cause Notice (SCN) Issuance
```
- Upon NBH approval, the system triggers Legal to prepare and issue the **SCN**.
- The **DD-Lead** formally shares the SCN with the dealer through **DD-Admin**.
- Dealer replies to the SCN by email or letter, which **DD-Admin uploads** to the portal.
- For termination cases, the **F&F settlement process is triggered only on the Last**
**Working Day (LWD)**. The system shall **control the F&F trigger based on the LWD date** ,
irrespective of the termination approval date.
```
4.3.2.9 Evaluation of Dealer Response
```
- The **DD-Lead** , **ZBH** , **RBM** , and **DD-Head** jointly review the dealers SCN response.
- Uploads internal comments, Legal feedback, and recommendation for NBHs final
decision.
```
4.3.2.10 NBH Final Decision
```
- The **NBH** reviews the compiled case with Legal advice and decides among:
o **Approve Termination** → Moves to CEO/CCO for confirmation
o **Reconsider** → Allow additional time or corrective action
o **Reject** → Case closed without termination
```
4.3.2.11 11. CEO & CCO Authorization
```
- **CEO** and **Chief Commercial Officer (CCO)** review the NBH-approved termination.
- Provide authorization on the portal.
- Once signed off, the decision becomes final.
```
4.3.2.12 12. Legal Termination Letter
```
- The **Legal Team** generates the **Termination Letter** to the portal.
- The letter is auto-visible to **DD-Lead** , **DD-Admin** , and **Finance**.
- A system notification is triggered to all linked personas.
```
4.3.2.13 13. DD-Admin Communication & F&F Trigger
```
- The **DD-Admin** shares the official **Termination Letter** with the dealer and field team.
- Marks the case as “Terminated” in the portal.
- Forwards the case to **Finance** for **Full & Final Settlement** initiation.
- Updates the worknote with final remarks and due-date for settlement.
### 4.4 Dealer Full & Final (F&F) Settlement Process Flow
```
4.4.1.1 Overview
```
The **Full & Final (F&F) Settlement Process** governs the financial closure of a dealership
following **Resignation** or **Termination**.
It ensures that all financial obligations between Royal Enfield and the dealer —
including **security deposits, recoveries, payables, and department-wise dues** — are
transparently reconciled, verified, and documented before closure.
**4.4.2 Step-by-Step Process Flow**
```
4.4.2.1 F&F Initiation
```
- Triggered automatically once the **Resignation Acceptance Letter** or **Termination**
**Letter** is uploaded by **Legal**.
- The **DD-Admin** or **DD-Lead** initiates the F&F case in the **Finance Dashboard** , which
creates a unique **FNF Case ID** linked to the dealer code.
- The system auto-fetches dealer details, associated documents, resignation/termination
date, and due dates.
- Notification is sent to the **Finance Team** and all functional departments to begin the
clearance process.
```
4.4.2.2 Department-wise Response Collection
```
- The system automatically prompts all mapped **functional departments (16 in total)** to
submit their clearance inputs — including NOC, payables, recoveries, and remarks.
- Each department updates:
o Financial dues (if any)
o Clearance confirmation (NOC)
o Supporting document uploads (e.g., debit note, invoice copy)
- The system dynamically updates progress (e.g., _12/16 Departments Responded_ ) with
color-coded indicators:
o 🟢 **No Dues** Cleared
```
o 🔴 Dues Pending Outstanding financial liability
o ⚪ Pending Awaiting department input
```
- SLA-based reminders are auto-triggered for pending responses nearing the deadline.
```
4.4.2.3 Finance Summary Consolidation
```
- Once all departments respond, the **DD-Admin Team** consolidates inputs into the **Final**
**F&F Summary Sheet** , which consists of:
o **Payables to Dealer** (e.g., refundable deposits, reimbursements)
o **Receivables from Dealer** (e.g., outstanding invoices, recoveries)
o **Deductions** (policy penalties, non-compliance adjustments)
- At this stage, **department-claimed amounts are frozen** and become read-only for
departments.
- Finance does **not overwrite department claim values**. Instead, Finance validates each row
in a dedicated validation layer by recording:
- Finance decision (Accepted / Partially Accepted / Rejected / Under Clarification)
- Finance-validated amount
- Variance amount and mandatory variance reason (if changed)
- Supporting proof/document
- The system automatically calculates:
- Net Settlement = Total Payables Total Receivables Total Deductions
- Final totals are computed from **finance-validated values only**.
- Status updates to _Finance Summary Prepared_ once complete.
```
4.4.2.4 Internal Review & Clarification
```
- The **Finance Team** may use the **Work Note** section to raise clarifications to **DD-**
**Lead** , **Legal** , or concerned departments.
- If discrepancies exist (e.g., mismatched values or missing NOCs), the case remains _Under_
_Clarification_ until resolved.
- Once validated, Finance locks the summary for further edits.
```
4.4.2.5 Dealer Discussion & Acknowledgment
```
- The **Finance Team** , along with **Legal** and **DD-Lead** , discusses the settlement summary
with the dealer.
- Dealer acknowledgment is captured either via written confirmation or attached email
communication.
- The case then proceeds for **Final Finance Approval**.
```
4.4.2.6 Final Finance Approval & Payment Processing
```
- The **Finance Team** reviews the approved summary and enters payment or recovery
details:
o **Transaction Type:** RTGS / NEFT / Cheque
o **Transaction ID & Date**
o **Bank Name & Account Details** (auto-fetched from dealer profile)
o **Settlement Remarks**
- Finance takes one of three actions:
```
o Approve Settlement → Marks the case as “Finance Approved.”
o Request Clarification → Sends query to DD-Lead or Admin.
o Reject Summary → Returns for re-verification.
```
- Upon approval, notifications are sent to DD-Admin and Legal for record update.
```
4.4.2.7 F&F Completion & Closure
```
- Once approved, the case is automatically marked **Completed** , and the **Finance**
**Dashboard** updates status as _F&F Closed_.
- The **Settlement Proof** (e.g., payment confirmation or recovery adjustment) is uploaded
by Finance.
- The **DD-Admin** communicates official closure to the dealer and archives all artefacts.
- System triggers final alerts to DD-Lead, NBH, and Legal confirming completion.
- The case is archived in the **Audit Trail** for future reference.
### 4.5 Finance Team Process Flow
```
4.5.1.1 Overview
```
The **Finance Team Process Flow** governs all financial activities related to dealer lifecycle
management — from **security deposit validation at onboarding** to **final settlement at
resignation or termination**.
It ensures complete financial traceability, proper verification of payments, and compliance with
Royal Enfields financial governance standards.
The process flow integrates with **Admin, Legal, Dealer Development (DD)** , and **Departmental
Modules** , ensuring accurate financial updates and timely closure of all financial transactions.
**4.5.2 Step-by-Step Process Flow** **4.5.2 Step-by-Step Process Flow**
@ -959,55 +370,7 @@ Modules** , ensuring accurate financial updates and timely closure of all financ
Admin and DD-Lead. Admin and DD-Lead.
```
o The verified payment data is stored permanently in the dealers financial profile
for audit and reference.
```
```
4.5.2.2 Financial Summary Preparation
```
- **Action:**
Once departmental inputs are received, Finance consolidates all data into the **F&F**
**Summary Sheet**.
- **System Steps:**
o Segregates entries under:
**Payables to Dealer** (e.g., refundable deposits, reimbursements)
**Receivables from Dealer** (e.g., outstanding payments, penalties)
**Deductions** (e.g., policy recoveries, warranty holdbacks)
o The system auto-calculates:
o Net Settlement = Total Payables Total Receivables Deductions
o Finance validates each record, uploads supporting documents (receipts, invoices,
credit notes), and adds remarks.
- **Outcome:**
The computed **Net Settlement Amount** is reflected in the dashboard, categorized
as _Payable to Dealer_ or _Recoverable from Dealer_.
```
4.5.2.3 Internal Clarification & Approval
```
- **Action:**
Finance initiates clarification rounds with departments or DD-Lead for mismatched data.
- **System Steps:**
o Uses the **Work Notes** section for comments, tagging users like _@DD-_
_Lead_ , _@Legal_ , or _@Admin_.
o Tracks status as _Pending Clarification_ until resolved.
o After reconciliation, Finance locks the summary and updates case status
to _Ready for Approval_.
```
4.5.2.4 Final Review & Dealer Confirmation
```
- **Action:**
Finance conducts an internal review of the consolidated settlement and initiates a
financial discussion with the dealer.
- **System Steps:**
o Reviews summary details on-screen with Legal and DD-Lead.
o Records dealers acknowledgment via Work Note or attached email
confirmation.
o Once confirmed, proceeds to payment verification.
```
4.5.2.5 Payment Processing & Record Update 4.5.2.5 Payment Processing & Record Update
``` ```
- **Action:** - **Action:**
@ -1020,17 +383,6 @@ for audit and reference.
o System automatically updates the **Progress Timeline** and **Audit Trail**. o System automatically updates the **Progress Timeline** and **Audit Trail**.
``` ```
4.5.2.6 F&F Completion & Closure
```
- **Action:**
Finance reviews all entries, confirms ledger reconciliations, and marks case
as **Completed**.
- **System Steps:**
o Locks financial data and supporting artefacts.
o Status changes to _Closed F&F Completed_.
o Final confirmation sent to all stakeholders — DD-Lead, NBH, DD-Head, Legal, and
DD-Admin.
o Finance Dashboard updates counters under “Completed Cases.”
## 5 System Features & Requirements ## 5 System Features & Requirements
@ -1110,88 +462,6 @@ Full visibility for own
submission submission
``` ```
### 6.2 SSO Login
**6.2.1 Functionality Scope**
The **User Authentication & Secure Login** module ensures controlled access to the **Dealer
Onboarding and Offboarding System** through **Royal Enfields Single Sign-On (SSO)
bridge** integrated with **Active Directory (AD)**. This guarantees that only **authorized RE
employees** can access the platform while maintaining identity consistency across all RE
applications. The feature upholds organizational standards of **security, traceability, and role-
based access control (RBAC)**.
**6.2.2 Width**
- The login interface is the **entry point** to the system and is accessible via the internal RE
portal or direct system URL.
- It contains the following key fields and actions:
o **Email Address** (RE domain-based ID)
o **Password** (validated via Active Directory)
o **Remember Me** (optional session retention)
o **Forgot Password** (redirects to REs password reset service via SSO)
- Once authenticated, users are redirected to their **personalized dashboard** based on role
and access level defined in RBAC.
**6.2.3 Depth**
- The system leverages **REs enterprise SSO framework** for identity validation and token-
based session management.
- User credentials are not stored within the application; authentication tokens are
validated through **Active Directory** integration.
- Upon successful login, the system fetches user metadata (name, department, role, region,
and zone) to determine module visibility and permissions.
- **Role-Based Access Control (RBAC)** defines feature-level authorization for each user
category (e.g., DD-Admin, DD-ZM, RBM, Finance, Legal).
- Unauthorized users or non-RE email domains are denied access and redirected to an error
page stating: _“Access restricted to authorized Royal Enfield personnel only.”_
- User sessions are automatically logged out after 30 mins of inactivity period
**6.2.4 Flow**
```
Step Source → Destination Description / Action
1 User → Login Screen User enters RE email ID and password.
```
```
2
```
```
Login Screen → SSO
Bridge Credentials validated via Active Directory.^
3 SSO → System Authentication token passed back to the application.
4 System → RBAC Engine User role and permissions are identified.
```
```
5 System → User Dashboard User redirected to personalized dashboard based on access
level.
```
**6.2.5 Personas-Wise Accessibility & Visibility**
```
Persona Accessibility Visibility Scope
All RE Employees Login access via SSO
bridge
```
```
Limited to assigned modules post-login
```
```
External Users (Dealers,
FDD Partners)
```
```
No direct access via
RE SSO
```
```
Access provided through secure external
login URLs when applicable
```
**Dependency**
- SSO implementation guide and sample users are required.
### 6.3 Dashboard ### 6.3 Dashboard
@ -3445,74 +2715,5 @@ o LOI / LOA / EOR Stages: Marks approvals, uploads, and status changes.
stage. stage.
``` ```
6.22.3.5 Security & Data Integrity
```
- Audit logs are **read-only and non-editable** to preserve authenticity.
**6.22.4 Personas-Wise Accessibility & Visibility**
```
Persona Accessibility Visibility Scope
RE User except
FDD
```
```
Full access to view all logs and export reports. Complete visibility and
export control.
System
(Automation
Layer)
```
```
Automatically records all workflow events and
triggers background logging for system actions.
```
```
Background operation.
```
---
## 13 Non-Functional Requirements
```
Category Requirement
Performance Average response time < 3 seconds for standard operations.
Scalability Should scale horizontally on GCP.
Security JWT tokens, encrypted passwords, HTTPS enforced.
Usability Intuitive UI, consistent icons, and simple navigation.
Reliability 99% uptime target.
Backup & Recovery Daily database backup and weekly full snapshot.
Compliance Follows RE IT data privacy guidelines.
```
## 14 Technology Matrix
```
Component Specification
Database PGSQL (Managed or local instance)
Application Stack Node.js (Backend) + React.js (Frontend)
Authentication RE SSO Bridge
```
## 15 Infra requirements & System Hygiene
```
Component Specification
Environment QA / Testing
# of Virtual Machines (VMs) 1
CPU Configuration 4 - Core
Memory (RAM) 16 GB
Disk Size 500 GB
Operating System Ubuntu 24.04 LTS
```
```
Storage Type Cloud
```
Backup and Recovery
- Daily incremental and weekly full backups.
- Restore process must not exceed 2 hours.
## 16 Not in scope
Anything which comes beyond the scope defined above in terms of Width and depth

File diff suppressed because it is too large Load Diff

View File

@ -1,138 +1,4 @@
# RE Onboarding & Offboarding System # Offboarding System
# Requirements
```
System Requirements Specifications
```
## 16 - Oct- 2025
## Version 1. 4
## Contents
- Change Log
- 1.1 Change Log Version 2.0
- 1.2 Change Log Dealer Self-Service Enablement
- 1 System Overview & Problem Statement
- 2 Intended Audience
- 2.1 Business & Functional Users
- 2.2 External & Integrated Stakeholders
- 3 Definitions and Acronyms
- 4 HiFi Wireframes & Flow of Application
- 4.1 Dealer onboarding - Process Flow Overview
- 4.2 Dealer Resignation Process Flow Overview
- 4.3 Dealer Termination Process Flow Overview
- 4.4 Dealer Full & Final (F&F) Settlement Process Flow
- 4.5 Finance Team Process Flow
- 5 System Features & Requirements
- 6 Dealer onboarding
- 6.1 Dealership Application Form
- 6.2 SSO Login
- 6.3 Dashboard
- 6.4 Opportunity & Non Opportunity
- 6.5 Questionnaire Response
- 6.6 Shortlisting Process
- 6.7 Shortlisted Applicants
- 6.8 Application Detail View
- 6.9 Interview Scheduling & Coordination
- 6.10 Interview Evaluation & Feedback Management
- 6.11 Interview Feedback & Evaluation Summary
- 6.12 Application Approval & Rejection Workflow
- 6.13 Work Notes & Internal Communication Trail
- 6.14 System Notifications & Alerts
- 6.15 FDD (Financial Due Diligence) & Finance Module
- 6.16 LOI Approval & Issuance
- 6.17 Dealer Code Generation, Architectural Work & Statutory Documentation............
- 6.18 LOA Issuance, Essential Operating Requirements & Inauguration
- 6.19 Essential Operating Requirements (EOR) Checklist
- 6.20 Progress Tracker.......................................................................................................
- 6.21 Central Document Repository
- 6.22 Audit Trail & Activity Log..........................................................................................
- 7 Dealer Resignation
- 7.1 Dealer Resignation Request (Initiation)
- 7.2 Resignation Management Dashboard
- 7.3 Resignation Details & Review
- 7.4 Resignation Request Review & Action Management
- 7.5 Resignation Progress Tracker
- 7.6 Documents & Audit Trail
- 8 Termination
- 8.1 Create Termination Request
- 8.2 Termination Ticket overview
- 8.3 Termination Approval & Review Process
- 8.4 Termination Progress Timeline
- 9 Admin Section
- 9.1 Master Configuration Organization
- 9.2 Zone, Region & Area Configuration
- 9.3 Roles & permissions
- 9.4 SLA Configuration & Escalation Management
- 9.5 Email & Letter Templates Management
- 9.6 Opportunity Management (Geography & Window Setup)
- 10 F&F Case
- 10.1 F&F Settlement Progress Timeline
- 10.2 Department Responses
- 11 Finance Dashboard
- 11.1 Finance Dashboard Page
- 11.2 F&F Settlement Module
- 12 Dealer Persona
- 12.1 Dealer Resignation
- 12.2 Dealer Constitutional Change Management
- 13 Non-Functional Requirements
- 14 Technology Matrix
- 15 Infra requirements & System Hygiene
- 16 Not in scope
## Change Log
### 1.1 Change Log Version 2.0
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Clarifications, Role Alignment & Access Control Enhancements
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 31 - Dec- 2025
**1.1.1 Notification Channel Enhancement**
- Added **WhatsApp as a supported notification channel** for reminders and workflow
communications (e.g., questionnaire completion and status updates), while restricting
sensitive document sharing to email only.
**1.1.2 LOI Governance & Communication Clarifications**
- Clarified that the **Finance team is not the decision-making authority** for LOI issuance
and is responsible only for financial validation.
- Confirmed that **LOI documents are shared exclusively via official email** and not through
WhatsApp.
- Clarified that **LOA issuance is a parallel statutory activity** and is **not dependent on**
**infrastructure readiness**.
**1.1.3 Dealer Code Creation Control**
- Clarified that **Dealer Codes (SAP Master) are created only upon explicit trigger by the**
**DD Admin** , and not through automatic system generation.
**1.1.4 LOA & EOR Sequencing Correction**
- Corrected the workflow sequence to ensure that **LOA is issued prior to initiating the**
**EOR checklist** , with EOR serving as the final readiness validation before go-live.
**1.1.5 Dealer Resignation Access & Workflow Enhancements**
- Enabled **dealer portal access** for initiating resignation requests and uploading required
information.
- Clarified that the **Legal team issues the Resignation Acceptance Letter** in all cases.
- Expanded review authority to allow **ZBH, DD Lead, DD Head, and NBH** to **Send Back or**
**Revoke resignation requests** , with communication routed through **Work Notes**.
- Confirmed that **Full & Final (F&F) settlement is triggered strictly on the Last Working**
**Day (LWD)** and not based on approval date.
**1.1.6 Termination Workflow Governance Updates** **1.1.6 Termination Workflow Governance Updates**
@ -160,77 +26,8 @@ System Requirements Specifications
**scenarios only**. **scenarios only**.
- Confirmed that **dealer portal access is revoked after resignation or termination**. - Confirmed that **dealer portal access is revoked after resignation or termination**.
**1.1.9 Terminology & Documentation Corrections**
- Clarified **KT Matrix as Kepner Tregoe Matrix** for consistency and correctness.
**1.1.10 Super Admin Role Introduction**
- Introduced a **Super Admin (Master Role)** with end-to-end access and workflow control
across modules.
- Defined segregation of duties by splitting Super Admin into **two DD Admin roles** with
clearly scoped responsibilities.
### 1.2 Change Log Dealer Self-Service Enablement
**Version:** v2.
**Section Impacted:** Section 12 Dealer Portal (12.1 onwards)
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Dealer Feature Enablement (Section 12 onwards)
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 5 - Jan- 2026
**1.2.1 Introduction of Dealer Portal**
- Introduced a **Dealer Portal capability** enabling onboarded dealers to initiate and track
post-onboarding lifecycle requests through the portal.
- Dealer actions are governed by **role-based access controls** , approval hierarchies, and
audit mechanisms.
**1.2.2 Dealer Resignation Enablement**
- Enabled **dealer-initiated resignation requests** at outlet level via the portal.
- Added structured resignation submission with:
o Last Operational Date (Sales & Services)
o Reason for resignation
o Mandatory document readiness guidance
- Enabled **dealer withdrawal option** for resignation requests **only until the case is**
**pending with NBH**.
- Clarified that **Legal team issues the Resignation Acceptance Letter** post approvals.
- Ensured **F&F settlement is triggered based on Last Working Day (LWD)** and not
approval date.
- Restricted dealer portal access **post resignation closure**.
**1.2.3 Dealer Relocation Request Enablement**
- Enabled dealers to **initiate and track relocation requests** through a guided workflow.
- Added support for:
o Manual or map-based location entry
o Distance calculation from existing location
o Property type selection and expected relocation date
- Introduced **document-driven relocation validation** , including statutory, legal, property,
and infrastructure documents.
- Implemented **multi-level approval workflow** with Work Notesbased communication
and audit trail.
- Ensured dealer has **view and upload access only** , with approvals retained by RE
stakeholders.
**1.2.4 Dealer Constitutional Change Enablement**
- Enabled dealers to **initiate constitutional change requests** post onboarding.
- Supported all approved constitution change scenarios:
o Proprietorship, Partnership, LLP, and Private Limited permutations
- Implemented **dynamic document requirement determination** based on target
constitution.
- Explicitly confirmed **no OCR-based document validation** ; all validations are manual and
role-driven.
- Ensured statutory compliance via Legal review before master data updates.
**1.2.5 Post-Exit Access Control** **1.2.5 Post-Exit Access Control**
@ -238,142 +35,6 @@ System Requirements Specifications
completed. completed.
## 1 System Overview & Problem Statement
**1.1.1 System Overview**
The **Dealer Onboarding and Offboarding System** for **Royal Enfield (RE)** is designed to **digitize,
standardize, and streamline** the complete dealer lifecycle — from **application and
evaluation** to **approval, resignation, termination, and full-and-final (F&F) settlement**.
At present, the process operates through **manual coordination** , involving **emails, spreadsheets,
and physical documentation** , which makes it difficult to maintain visibility, accountability, and
consistency across teams.
The proposed solution introduces a **centralized digital platform** that brings all stakeholders onto
a single workflow. It ensures that every stage — **onboarding, operational approvals, financial
diligence, legal validation, and final closure** — follows a **structured and traceable process**.
The system integrates seamlessly with existing RE applications such as **SSO** , **SAP** , and **Finance
modules** , providing **role-based access** , **real-time tracking** , and **secure document management**.
It also offers **automated workflows** , **configurable approval hierarchies** , and **AI-assisted decision
support** to improve efficiency and reduce turnaround time.
By moving to a digital workflow, Royal Enfield will achieve higher levels of **process
efficiency** , **data accuracy** , and **transparency** , ensuring faster decision-making and stronger
control over the dealer network lifecycle.
## 2 Intended Audience
This document is intended for all stakeholders involved in the **design, implementation, approval,
and operational use** of the **Dealer Onboarding and Offboarding System** at **Royal Enfield (RE)**.
The following user personas and roles are part of the system:
### 2.1 Business & Functional Users
**2.1.1 Dealer Development (DD) Team**
- **Super Admin (Master Role):**
The **Super Admin has unrestricted access** across all modules and workflows, with
authority to **configure, override, and influence workflow behavior** at every level.
```
The Super Admin role is segregated into two DD Admin roles , each with clearly defined
scopes to ensure segregation of duties and governance control.
```
- **DD-Admin:** System administrator responsible for user setup, role mapping, hierarchy
configuration, and workflow management.
- **DD-AM (Area Manager):** Reviews and manages applications within assigned regions;
performs preliminary screening.
- **DD-ZM (Zonal Manager):** Conducts the first level of dealer evaluation along with RBM;
prepares presentation decks for final interviews.
- **DD-Lead:** Reviews zonal evaluations, validates recommendations, and forwards
shortlisted applicants for senior-level approval.
- **DD-Head: DD Head** is engaged in the **final review and approval** of shortlisted dealer
applications before the **NBH interview** , and later **oversees final verification and LOI**
**issuance** after all evaluations are complete.
**2.1.2 Regional Sales & Business Team**
- **RBM (Regional Business Manager):** Participates in early-stage evaluations, provides
ground-level business insights, and recommends suitable candidates.
- **ZBH (Zonal Business Head):** Conducts the second-level review along with DD-Lead;
provides strategic feedback on market and location viability.
- **NBH (National Business Head):** Holds final authority for approval or rejection of dealer
onboarding; reviews consolidated feedback from all levels.
**2.1.3 Supporting Departments**
- **Finance Team:** Reviews financial due diligence reports, validates F&F (Full and Final)
settlements, and manages monetary closure during offboarding.
- **Legal Team:** Reviews agreements, issues **Letters of Intent (LOI)** or **Termination Letters** ,
and ensures all documentation aligns with company policy.
- **Brand Experience / Architecture Team:** Manages **EOR (Essential Operating**
**Requirements)** and ensures adherence to brand and infrastructure standards.
**2.1.4 Dealers**
Once a dealer is **successfully onboarded and activated in the system** , the Dealer role is enabled
with controlled, role-based access to initiate and track select lifecycle requests. This
enhancement introduces **structured self-service capabilities for dealers** , while ensuring all
actions remain governed by defined validations, internal reviews, and approval workflows as per
RE standards.
The Dealer role is enabled to perform the following activities:
- **Resignation Initiation**
```
The dealer can initiate the resignation process directly through the portal , submit the
reason for exit, and track the status of the request across the defined review, clearance,
and closure stages.
```
- **Relocation Request Submission**
```
The dealer can submit a relocation request in scenarios where there is an intent to shift
the dealership from the current location to a new proposed location. The request is
routed for internal feasibility assessment, validation, and management approval before
execution.
```
- **Change in Constitution Request**
```
The dealer can initiate a Change in Constitution request to seek approval from RE
management for ownership or structural changes within the dealership. Upon approval,
the dealer may proceed with the legally compliant transition.
```
```
Supported Change in Constitution scenarios include:
```
```
o Proprietorship (Single Owner) → Partnership
o Proprietorship → LLP (Limited Liability Partnership)
o Proprietorship → Private Limited
o Partnership → LLP
o Partnership → Private Limited
o Private Limited → LLP
o Private Limited → Partnership
```
All dealer-initiated requests are subject to **defined validations, mandatory document
submissions, role-based reviews, and approvals**. The dealers access is **restricted to initiation,
document upload, and status visibility** , with **final decision-making authority retained by
authorized internal stakeholders of RE**
### 2.2 External & Integrated Stakeholders
**2.2.1 FDD (Financial Due Diligence Partner)**
External agency responsible for assessing the applicants financial health, verifying credentials,
and uploading due diligence reports into the system.
**2.2.2 Dealer / Applicant**
External user who applies for dealership, uploads required documents, participates in
interviews, and later accesses the portal for resignation or closure status.
## 3 Definitions and Acronyms ## 3 Definitions and Acronyms
@ -396,286 +57,7 @@ LOA Letter of Appointment
F&F Full and Final (Dealer Settlement) F&F Full and Final (Dealer Settlement)
KT Matrix Evaluation Matrix used for scoring applicants KT Matrix Evaluation Matrix used for scoring applicants
``` ```
## 4 HiFi Wireframes & Flow of Application
HiFi Wireframes : https://mono-human-93592950.figma.site
### 4.1 Dealer onboarding - Process Flow Overview
The **Dealer Onboarding Workflow** outlines the end-to-end sequence through which a dealership
application progresses — from initial registration to final inauguration and operational readiness.
**4.1.1 Step-by-Step Process Flow**
```
4.1.1.1 Application Initiation
```
- The **applicant (dealer prospect)** submits an online application through the Dealer
Onboarding Portal.
- The system checks the **locations availability** in the Royal Enfield dealership network:
o If the location has **no open opportunity** , a **Non-Opportunity Email** is triggered
automatically.
o If an opportunity exists, the applicant receives an **Opportunity Email** with login
credentials and a link to the **Dealer Questionnaire**.
```
4.1.1.2 Questionnaire Completion
```
- The applicant fills out the **comprehensive questionnaire** covering business, infrastructure,
and financial readiness.
- The system auto-scores responses, generating a **Questionnaire Score** and **initial**
**ranking** for that applicant.
- Completed applications move to the **Admin review bucket**.
- The system shall trigger automated reminders to users for completing the
questionnaire. These **reminders will be sent through WhatsApp** , to ensure timely
submission. Reminder needs to be configured from Admin.
```
4.1.1.3 Admin Validation & Shortlisting
```
- **DD-Admin** reviews all submitted applications and validates details and attached
documents.
- Based on eligibility, applications are either **shortlisted** for evaluation or **archived** for
future opportunities.
- Shortlisted applications are distributed to respective **zones or regions** for further
assessment.
```
4.1.1.4 Interview Evaluation (Multi-Level Process)
```
- Admin schedules interviews in **Level 1** , **Level 2** , and **Level 3** , as applicable.
- Each interview can be **Virtual or Physical** , with calendar invites sent via Google Calendar.
- Evaluators at each level (DD-ZM, RBM, DD-Lead, ZBH, NBH, DD-Head) record their
feedback through:
o **KT Matrix Scoring** (quantitative)
o **Interview Feedback Form** (qualitative)
- The system consolidates panel feedback and generates an **AI-driven summary and**
**ranking** for decision support.
```
4.1.1.5 Financial Due Diligence (FDD) & Finance Review
```
- Upon shortlisting, the application is assigned to the **FDD Team (external agency)** for
financial validation.
- FDD users, using SSO credentials, can:
o View assigned applications in a restricted interface.
o Upload FDD reports and add remarks in the **Work Notes** section.
o Flag cases of **non-responsiveness** or incomplete data, returning them to Admin.
- The **Finance team** reviews submitted FDD reports, validates findings, and decides
whether the application proceeds to **LOI approval**. The finance team is not the decision
maker for LOI Issuance.
```
4.1.1.6 LOI (Letter of Intent) Approval & Issuance
```
- Based on Finance clearance, **DD-Head and NBH** review and approve the **LOI request**.
- The system tracks document approvals, timestamps, and supporting artefacts.
- Once approved, the LOI document is generated, uploaded, and shared **with the**
**applicant via official email communication** and not on WhatsApp
- Notification emails are triggered to all relevant stakeholders.
```
4.1.1.7 Dealer Code Generation & Setup
```
- After LOI issuance, the **DD-Admin triggers** the Dealer Code creation process. Based on
this trigger, the **Dealer Code is created in the SAP Master** and **mapped to the applicant**
within the system.
- The code links all downstream modules, including Architectural, Statutory, and EOR
checklists.
```
4.1.1.8 Architectural Work & Statutory Documentation
```
- Architectural activities are initiated (site plans, layout approvals, branding elements).
- The applicant and assigned Architecture Team upload documents, drawings, and
blueprints.
- In parallel, the applicant uploads **Statutory Documents** such as:
o GST certificate, PAN, Partnership Deed, Firm Registration, Rental/Lease
Agreement, etc.
- Each upload is timestamped and visible with file name, uploader, and document type.
```
4.1.1.9 Payment Verification & Finance Validation
```
- Applicant uploads proof of advance payment or security deposit.
- The **Finance team** verifies payment details (transaction ID, amount, and bank record).
- Status is updated to **Verified** once the payment is reconciled.
- Verified payment triggers readiness for final operational setup.
```
4.1.1.10 Essential Operating Requirements (EOR) Checklist
```
- All functional teams (Sales, Service, IT, Finance, Training, Architecture) verify their
respective readiness parameters.
- Progress is tracked through a **completion bar** until 100% EOR compliance is achieved.
- The **EOR checklist is initiated only after LOA issuance**. All functional teams verify their
respective readiness parameters, and progress is tracked until **100% EOR compliance** is
achieved.
```
4.1.1.11 LOA (Letter of Authorization) & Final Go-Live
```
- After LOI issuance and Dealer Code generation, the **Letter of Authorization (LOA) is**
**generated and approved by NBH and DD-Head**. Upon successful LOA issuance, the
```
application proceeds to the Essential Operating Requirements (EOR) checklist for final
readiness verification.
```
- Final verification includes:
```
o EOR document review
o Brand readiness assessment
o Site validation and inspection
```
- The **LOA** officially authorizes the dealership to operate under Royal Enfield.
```
4.1.1.12 Inauguration & Closure
```
- Post-authorization, the **Inauguration** event is scheduled and logged.
- Completion of inauguration marks the dealership as **Active** in the system.
```
4.1.1.13 System-Driven Governance & Audit
```
- Each stage automatically logs:
o User action, timestamp, and remarks
o Uploaded artefacts and version control
o Notifications sent and approvals received
- The entire lifecycle remains accessible under **Audit Trail** for future reference, compliance,
or offboarding workflows.
### 4.2 Dealer Resignation Process Flow Overview
**4.2.1.1 Overview**
```
The Dealer Resignation Process manages the structured offboarding of a dealership initiated
by the dealer. The process begins when a dealer formally submits their resignation via
email to the Area Sales Manager (ASM) , after which the workflow transitions into the
system-managed approval sequence.
```
```
Dealer resignation requests are initiated by the dealer through the portal and subsequently
reviewed and processed by Admin, Finance, Legal, and relevant business stakeholders.
```
```
This flow ensures that each resignation is verified, discussed, and approved across all
required levels — maintaining proper documentation, compliance, and traceability until the
final Legal Acceptance Letter is issued.
```
**4.2.2 Step-by-Step Process Flow**
```
4.2.2.1 Dealer Initiation
```
- The dealer submits a **formal resignation email** on the dealerships official letterhead to
the **ASM**.
- The resignation reason must be clearly stated (e.g., personal, financial, business
restructuring).
- The **dealer is provided portal access** to initiate the resignation request directly through
the system. The dealer submits resignation details, reason for exit, and proposed
timeline via the portal, after which the request enters the internal review and clearance
workflow.
```
4.2.2.2 ASM Review
```
- The **ASM** reviews the dealers resignation request and supporting letter.
- Uploads the **resignation email** and **dealers letterhead document** onto the portal.
- Adds remarks summarizing the discussion and reason for resignation.
- Forwards the request to **RBM + DD-ZM** for evaluation.
```
4.2.2.3 RBM + DD-ZM Joint Evaluation
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** review the uploaded documents.
- Conduct a joint discussion with the dealer to confirm the intent and understand any
issues.
- Uploads the **Minutes of Meeting (MOM)** or discussion summary.
- Adds comments and recommendations before forwarding to **Zonal Business Head**
**(ZBH)**.
- Actions available at this stage:
o **Approve** → Send forward for next-level review
o **Send Back for Clarification** → Returns to ASM
o **Withdraw** → Cancels the request (with remarks logged)
```
4.2.2.4 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the resignation summary and all remarks.
- Adds their comments and recommendations.
- Forwards the request to **DD-Lead** through the system.
- Worknote is updated automatically to reflect action and timestamp.
- The resignation request is reviewed by authorized business stakeholders,
including **RBM, ZBH, and DD-Head**. During the review stage, the **ZBH is authorized to**
```
Send Back or Revoke the resignation request for clarification or correction. Send Back
actions are communicated to the dealer and internal teams through Work Notes , with
mandatory remarks captured for traceability.
```
```
4.2.2.5 DD-Lead Review
```
- The **DD-Lead** consolidates all discussions, documents, and feedback.
- Prepares a **Resignation Presentation** with recommendations and supporting data.
- Uploads the presentation to the portal.
- Forwards the case to **NBH** for final decision.
- The resignation request is reviewed by the **DD-Lead and DD-Head**. At this stage, both
roles are authorized to **Send Back or Revoke** the resignation request for clarification,
correction, or reconsideration. **Send Back actions are communicated through Work**
**Notes** , with **mandatory remarks** recorded for audit and traceability.
```
4.2.2.6 NBH Final Approval
```
- The **National Business Head (NBH)** reviews the entire resignation dossier.
- Adds final remarks with one of the following outcomes:
o **Approve** → Case moves automatically to Legal for letter issuance.
o **Send Back for Clarification** → Returns to DD-Lead or ZBH for revalidation.
o **Hold** → Temporarily pauses the process pending further discussion.
- Upon approval, the system triggers a **Worknote Notification** to DD-Lead, RBM, ZBH, and
Finance teams.
- The resignation request is reviewed by the **NBH** , who may **Approve, Send Back, or**
**Revoke** the request based on business considerations. Any **Send Back or Revoke action**
**must be accompanied by remarks recorded in Work Notes** , ensuring transparent
communication and governance.
```
4.2.2.7 Legal Acceptance Letter
```
- Once approved by **NBH** , the request is **auto-assigned to the Legal team**.
- Legal verifies the uploaded resignation and issues a **Resignation Acceptance Letter**.
- The letter is uploaded to the portal, visible to all relevant personas including **DD-**
**Admin** and **DD-AM**.
- Legal can also raise clarifications through worknotes if required.
- Upon completion of all approvals, the **Legal team issues the official Resignation**
**Acceptance Letter** and shares it with the dealer through authorized communication
channels.
```
4.2.2.8 DD-Admin Closure
```
- The **DD-Admin** downloads and shares the final **Resignation Acceptance Letter** with the
dealer.
- Marks the resignation as completed and triggers the **F&F (Full and Final) process** by
forwarding the case to the Finance team.
- The **Full & Final (F&F) settlement process is initiated only on the Last Working Day**
**(LWD) of the dealership**. The system shall **enable and trigger the F&F workflow strictly**
**based on the LWD date** , and **not based on the resignation approval date**.
### 4.3 Dealer Termination Process Flow Overview ### 4.3 Dealer Termination Process Flow Overview
@ -841,211 +223,6 @@ transparently reconciled, verified, and documented before closure.
- Notification is sent to the **Finance Team** and all functional departments to begin the - Notification is sent to the **Finance Team** and all functional departments to begin the
clearance process. clearance process.
```
4.4.2.2 Department-wise Response Collection
```
- The system automatically prompts all mapped **functional departments (16 in total)** to
submit their clearance inputs — including NOC, payables, recoveries, and remarks.
- Each department updates:
o Financial dues (if any)
o Clearance confirmation (NOC)
o Supporting document uploads (e.g., debit note, invoice copy)
- The system dynamically updates progress (e.g., _12/16 Departments Responded_ ) with
color-coded indicators:
o 🟢 **No Dues** Cleared
```
o 🔴 Dues Pending Outstanding financial liability
o ⚪ Pending Awaiting department input
```
- SLA-based reminders are auto-triggered for pending responses nearing the deadline.
```
4.4.2.3 Finance Summary Consolidation
```
- Once all departments respond, the **DD-Admin Team** consolidates inputs into the **Final**
**F&F Summary Sheet** , which consists of:
o **Payables to Dealer** (e.g., refundable deposits, reimbursements)
o **Receivables from Dealer** (e.g., outstanding invoices, recoveries)
o **Deductions** (policy penalties, non-compliance adjustments)
- At this stage, **department-claimed amounts are frozen** and become read-only for
departments.
- Finance does **not overwrite department claim values**. Instead, Finance validates each row
in a dedicated validation layer by recording:
- Finance decision (Accepted / Partially Accepted / Rejected / Under Clarification)
- Finance-validated amount
- Variance amount and mandatory variance reason (if changed)
- Supporting proof/document
- The system automatically calculates:
- Net Settlement = Total Payables Total Receivables Total Deductions
- Final totals are computed from **finance-validated values only**.
- Status updates to _Finance Summary Prepared_ once complete.
```
4.4.2.4 Internal Review & Clarification
```
- The **Finance Team** may use the **Work Note** section to raise clarifications to **DD-**
**Lead** , **Legal** , or concerned departments.
- If discrepancies exist (e.g., mismatched values or missing NOCs), the case remains _Under_
_Clarification_ until resolved.
- Once validated, Finance locks the summary for further edits.
```
4.4.2.5 Dealer Discussion & Acknowledgment
```
- The **Finance Team** , along with **Legal** and **DD-Lead** , discusses the settlement summary
with the dealer.
- Dealer acknowledgment is captured either via written confirmation or attached email
communication.
- The case then proceeds for **Final Finance Approval**.
```
4.4.2.6 Final Finance Approval & Payment Processing
```
- The **Finance Team** reviews the approved summary and enters payment or recovery
details:
o **Transaction Type:** RTGS / NEFT / Cheque
o **Transaction ID & Date**
o **Bank Name & Account Details** (auto-fetched from dealer profile)
o **Settlement Remarks**
- Finance takes one of three actions:
```
o Approve Settlement → Marks the case as “Finance Approved.”
o Request Clarification → Sends query to DD-Lead or Admin.
o Reject Summary → Returns for re-verification.
```
- Upon approval, notifications are sent to DD-Admin and Legal for record update.
```
4.4.2.7 F&F Completion & Closure
```
- Once approved, the case is automatically marked **Completed** , and the **Finance**
**Dashboard** updates status as _F&F Closed_.
- The **Settlement Proof** (e.g., payment confirmation or recovery adjustment) is uploaded
by Finance.
- The **DD-Admin** communicates official closure to the dealer and archives all artefacts.
- System triggers final alerts to DD-Lead, NBH, and Legal confirming completion.
- The case is archived in the **Audit Trail** for future reference.
### 4.5 Finance Team Process Flow
```
4.5.1.1 Overview
```
The **Finance Team Process Flow** governs all financial activities related to dealer lifecycle
management — from **security deposit validation at onboarding** to **final settlement at
resignation or termination**.
It ensures complete financial traceability, proper verification of payments, and compliance with
Royal Enfields financial governance standards.
The process flow integrates with **Admin, Legal, Dealer Development (DD)** , and **Departmental
Modules** , ensuring accurate financial updates and timely closure of all financial transactions.
**4.5.2 Step-by-Step Process Flow**
```
4.5.2.1 Security Deposit Validation (Onboarding Stage)
```
- **Trigger:**
Initiated when a new dealers onboarding application reaches the Finance stage after
DD approval.
- **Action:**
The **Finance Team** verifies the **Security Deposit** payment made by the dealer
via **RTGS/NEFT** or other approved channels.
- **Outcome:**
o Verified deposits are marked as _Approved_ , triggering system notifications to DD-
Admin and DD-Lead.
```
o The verified payment data is stored permanently in the dealers financial profile
for audit and reference.
```
```
4.5.2.2 Financial Summary Preparation
```
- **Action:**
Once departmental inputs are received, Finance consolidates all data into the **F&F**
**Summary Sheet**.
- **System Steps:**
o Segregates entries under:
**Payables to Dealer** (e.g., refundable deposits, reimbursements)
**Receivables from Dealer** (e.g., outstanding payments, penalties)
**Deductions** (e.g., policy recoveries, warranty holdbacks)
o The system auto-calculates:
o Net Settlement = Total Payables Total Receivables Deductions
o Finance validates each record, uploads supporting documents (receipts, invoices,
credit notes), and adds remarks.
- **Outcome:**
The computed **Net Settlement Amount** is reflected in the dashboard, categorized
as _Payable to Dealer_ or _Recoverable from Dealer_.
```
4.5.2.3 Internal Clarification & Approval
```
- **Action:**
Finance initiates clarification rounds with departments or DD-Lead for mismatched data.
- **System Steps:**
o Uses the **Work Notes** section for comments, tagging users like _@DD-_
_Lead_ , _@Legal_ , or _@Admin_.
o Tracks status as _Pending Clarification_ until resolved.
o After reconciliation, Finance locks the summary and updates case status
to _Ready for Approval_.
```
4.5.2.4 Final Review & Dealer Confirmation
```
- **Action:**
Finance conducts an internal review of the consolidated settlement and initiates a
financial discussion with the dealer.
- **System Steps:**
o Reviews summary details on-screen with Legal and DD-Lead.
o Records dealers acknowledgment via Work Note or attached email
confirmation.
o Once confirmed, proceeds to payment verification.
```
4.5.2.5 Payment Processing & Record Update
```
- **Action:**
Finance executes the financial transaction (payment to or recovery from dealer).
- **System Steps:**
o Enters **Mode of Payment** , **Transaction Reference Number** , **Date** , and **Remarks**.
o Uploads proof of payment (RTGS confirmation or bank statement).
o Marks case as _Finance Approved_ and sends completion notification to DD-Admin
and Legal.
o System automatically updates the **Progress Timeline** and **Audit Trail**.
```
4.5.2.6 F&F Completion & Closure
```
- **Action:**
Finance reviews all entries, confirms ledger reconciliations, and marks case
as **Completed**.
- **System Steps:**
o Locks financial data and supporting artefacts.
o Status changes to _Closed F&F Completed_.
o Final confirmation sent to all stakeholders — DD-Lead, NBH, DD-Head, Legal, and
DD-Admin.
o Finance Dashboard updates counters under “Completed Cases.”
## 5 System Features & Requirements
Here, we describe the **system features** along with their respective **Width** and **Depth** to provide
complete visibility of each requirement.
The **Width** defines the **functional coverage** of a feature — outlining what the feature does,
its **boundaries, use cases, and user interactions**. It answers the question: _“What scenarios and
actions are covered by this feature?”_
The **Depth** captures the **operational and behavioral details** — describing how the feature
behaves through its **logic, workflow, system responses, and edge-case handling**. It answers the
question: _“How does the system execute and respond in these scenarios?”_
---
## 8 Termination ## 8 Termination
@ -1577,49 +754,3 @@ only)
``` ```
View SCN and Termination Letter post-issuance. View Only View SCN and Termination Letter post-issuance. View Only
``` ```
---
## 13 Non-Functional Requirements
```
Category Requirement
Performance Average response time < 3 seconds for standard operations.
Scalability Should scale horizontally on GCP.
Security JWT tokens, encrypted passwords, HTTPS enforced.
Usability Intuitive UI, consistent icons, and simple navigation.
Reliability 99% uptime target.
Backup & Recovery Daily database backup and weekly full snapshot.
Compliance Follows RE IT data privacy guidelines.
```
## 14 Technology Matrix
```
Component Specification
Database PGSQL (Managed or local instance)
Application Stack Node.js (Backend) + React.js (Frontend)
Authentication RE SSO Bridge
```
## 15 Infra requirements & System Hygiene
```
Component Specification
Environment QA / Testing
# of Virtual Machines (VMs) 1
CPU Configuration 4 - Core
Memory (RAM) 16 GB
Disk Size 500 GB
Operating System Ubuntu 24.04 LTS
```
```
Storage Type Cloud
```
Backup and Recovery
- Daily incremental and weekly full backups.
- Restore process must not exceed 2 hours.
## 16 Not in scope
Anything which comes beyond the scope defined above in terms of Width and depth

View File

@ -1,107 +1,6 @@
# RE Onboarding & Offboarding System # RE Onboarding & Offboarding System
# Requirements
```
System Requirements Specifications
```
## 16 - Oct- 2025
## Version 1. 4
## Contents
- Change Log
- 1.1 Change Log Version 2.0
- 1.2 Change Log Dealer Self-Service Enablement
- 1 System Overview & Problem Statement
- 2 Intended Audience
- 2.1 Business & Functional Users
- 2.2 External & Integrated Stakeholders
- 3 Definitions and Acronyms
- 4 HiFi Wireframes & Flow of Application
- 4.1 Dealer onboarding - Process Flow Overview
- 4.2 Dealer Resignation Process Flow Overview
- 4.3 Dealer Termination Process Flow Overview
- 4.4 Dealer Full & Final (F&F) Settlement Process Flow
- 4.5 Finance Team Process Flow
- 5 System Features & Requirements
- 6 Dealer onboarding
- 6.1 Dealership Application Form
- 6.2 SSO Login
- 6.3 Dashboard
- 6.4 Opportunity & Non Opportunity
- 6.5 Questionnaire Response
- 6.6 Shortlisting Process
- 6.7 Shortlisted Applicants
- 6.8 Application Detail View
- 6.9 Interview Scheduling & Coordination
- 6.10 Interview Evaluation & Feedback Management
- 6.11 Interview Feedback & Evaluation Summary
- 6.12 Application Approval & Rejection Workflow
- 6.13 Work Notes & Internal Communication Trail
- 6.14 System Notifications & Alerts
- 6.15 FDD (Financial Due Diligence) & Finance Module
- 6.16 LOI Approval & Issuance
- 6.17 Dealer Code Generation, Architectural Work & Statutory Documentation............
- 6.18 LOA Issuance, Essential Operating Requirements & Inauguration
- 6.19 Essential Operating Requirements (EOR) Checklist
- 6.20 Progress Tracker.......................................................................................................
- 6.21 Central Document Repository
- 6.22 Audit Trail & Activity Log..........................................................................................
- 7 Dealer Resignation
- 7.1 Dealer Resignation Request (Initiation)
- 7.2 Resignation Management Dashboard
- 7.3 Resignation Details & Review
- 7.4 Resignation Request Review & Action Management
- 7.5 Resignation Progress Tracker
- 7.6 Documents & Audit Trail
- 8 Termination
- 8.1 Create Termination Request
- 8.2 Termination Ticket overview
- 8.3 Termination Approval & Review Process
- 8.4 Termination Progress Timeline
- 9 Admin Section
- 9.1 Master Configuration Organization
- 9.2 Zone, Region & Area Configuration
- 9.3 Roles & permissions
- 9.4 SLA Configuration & Escalation Management
- 9.5 Email & Letter Templates Management
- 9.6 Opportunity Management (Geography & Window Setup)
- 10 F&F Case
- 10.1 F&F Settlement Progress Timeline
- 10.2 Department Responses
- 11 Finance Dashboard
- 11.1 Finance Dashboard Page
- 11.2 F&F Settlement Module
- 12 Dealer Persona
- 12.1 Dealer Resignation
- 12.2 Dealer Constitutional Change Management
- 13 Non-Functional Requirements
- 14 Technology Matrix
- 15 Infra requirements & System Hygiene
- 16 Not in scope
## Change Log
### 1.1 Change Log Version 2.0
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Clarifications, Role Alignment & Access Control Enhancements
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 31 - Dec- 2025
**1.1.1 Notification Channel Enhancement**
- Added **WhatsApp as a supported notification channel** for reminders and workflow
communications (e.g., questionnaire completion and status updates), while restricting
sensitive document sharing to email only.
**1.1.2 LOI Governance & Communication Clarifications** **1.1.2 LOI Governance & Communication Clarifications**
@ -112,24 +11,7 @@ System Requirements Specifications
- Clarified that **LOA issuance is a parallel statutory activity** and is **not dependent on** - Clarified that **LOA issuance is a parallel statutory activity** and is **not dependent on**
**infrastructure readiness**. **infrastructure readiness**.
**1.1.3 Dealer Code Creation Control** **Send Back or**
- Clarified that **Dealer Codes (SAP Master) are created only upon explicit trigger by the**
**DD Admin** , and not through automatic system generation.
**1.1.4 LOA & EOR Sequencing Correction**
- Corrected the workflow sequence to ensure that **LOA is issued prior to initiating the**
**EOR checklist** , with EOR serving as the final readiness validation before go-live.
**1.1.5 Dealer Resignation Access & Workflow Enhancements**
- Enabled **dealer portal access** for initiating resignation requests and uploading required
information.
- Clarified that the **Legal team issues the Resignation Acceptance Letter** in all cases.
- Expanded review authority to allow **ZBH, DD Lead, DD Head, and NBH** to **Send Back or**
**Revoke resignation requests** , with communication routed through **Work Notes**. **Revoke resignation requests** , with communication routed through **Work Notes**.
- Confirmed that **Full & Final (F&F) settlement is triggered strictly on the Last Working** - Confirmed that **Full & Final (F&F) settlement is triggered strictly on the Last Working**
**Day (LWD)** and not based on approval date. **Day (LWD)** and not based on approval date.
@ -164,155 +46,6 @@ System Requirements Specifications
- Clarified **KT Matrix as Kepner Tregoe Matrix** for consistency and correctness. - Clarified **KT Matrix as Kepner Tregoe Matrix** for consistency and correctness.
**1.1.10 Super Admin Role Introduction**
- Introduced a **Super Admin (Master Role)** with end-to-end access and workflow control
across modules.
- Defined segregation of duties by splitting Super Admin into **two DD Admin roles** with
clearly scoped responsibilities.
### 1.2 Change Log Dealer Self-Service Enablement
**Version:** v2.
**Section Impacted:** Section 12 Dealer Portal (12.1 onwards)
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Dealer Feature Enablement (Section 12 onwards)
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 5 - Jan- 2026
**1.2.1 Introduction of Dealer Portal**
- Introduced a **Dealer Portal capability** enabling onboarded dealers to initiate and track
post-onboarding lifecycle requests through the portal.
- Dealer actions are governed by **role-based access controls** , approval hierarchies, and
audit mechanisms.
**1.2.2 Dealer Resignation Enablement**
- Enabled **dealer-initiated resignation requests** at outlet level via the portal.
- Added structured resignation submission with:
o Last Operational Date (Sales & Services)
o Reason for resignation
o Mandatory document readiness guidance
- Enabled **dealer withdrawal option** for resignation requests **only until the case is**
**pending with NBH**.
- Clarified that **Legal team issues the Resignation Acceptance Letter** post approvals.
- Ensured **F&F settlement is triggered based on Last Working Day (LWD)** and not
approval date.
- Restricted dealer portal access **post resignation closure**.
**1.2.3 Dealer Relocation Request Enablement**
- Enabled dealers to **initiate and track relocation requests** through a guided workflow.
- Added support for:
o Manual or map-based location entry
o Distance calculation from existing location
o Property type selection and expected relocation date
- Introduced **document-driven relocation validation** , including statutory, legal, property,
and infrastructure documents.
- Implemented **multi-level approval workflow** with Work Notesbased communication
and audit trail.
- Ensured dealer has **view and upload access only** , with approvals retained by RE
stakeholders.
**1.2.4 Dealer Constitutional Change Enablement**
- Enabled dealers to **initiate constitutional change requests** post onboarding.
- Supported all approved constitution change scenarios:
o Proprietorship, Partnership, LLP, and Private Limited permutations
- Implemented **dynamic document requirement determination** based on target
constitution.
- Explicitly confirmed **no OCR-based document validation** ; all validations are manual and
role-driven.
- Ensured statutory compliance via Legal review before master data updates.
**1.2.5 Post-Exit Access Control**
- Enforced system rule to **revoke dealer portal access** once resignation or termination is
completed.
## 1 System Overview & Problem Statement
**1.1.1 System Overview**
The **Dealer Onboarding and Offboarding System** for **Royal Enfield (RE)** is designed to **digitize,
standardize, and streamline** the complete dealer lifecycle — from **application and
evaluation** to **approval, resignation, termination, and full-and-final (F&F) settlement**.
At present, the process operates through **manual coordination** , involving **emails, spreadsheets,
and physical documentation** , which makes it difficult to maintain visibility, accountability, and
consistency across teams.
The proposed solution introduces a **centralized digital platform** that brings all stakeholders onto
a single workflow. It ensures that every stage — **onboarding, operational approvals, financial
diligence, legal validation, and final closure** — follows a **structured and traceable process**.
The system integrates seamlessly with existing RE applications such as **SSO** , **SAP** , and **Finance
modules** , providing **role-based access** , **real-time tracking** , and **secure document management**.
It also offers **automated workflows** , **configurable approval hierarchies** , and **AI-assisted decision
support** to improve efficiency and reduce turnaround time.
By moving to a digital workflow, Royal Enfield will achieve higher levels of **process
efficiency** , **data accuracy** , and **transparency** , ensuring faster decision-making and stronger
control over the dealer network lifecycle.
## 2 Intended Audience
This document is intended for all stakeholders involved in the **design, implementation, approval,
and operational use** of the **Dealer Onboarding and Offboarding System** at **Royal Enfield (RE)**.
The following user personas and roles are part of the system:
### 2.1 Business & Functional Users
**2.1.1 Dealer Development (DD) Team**
- **Super Admin (Master Role):**
The **Super Admin has unrestricted access** across all modules and workflows, with
authority to **configure, override, and influence workflow behavior** at every level.
```
The Super Admin role is segregated into two DD Admin roles , each with clearly defined
scopes to ensure segregation of duties and governance control.
```
- **DD-Admin:** System administrator responsible for user setup, role mapping, hierarchy
configuration, and workflow management.
- **DD-AM (Area Manager):** Reviews and manages applications within assigned regions;
performs preliminary screening.
- **DD-ZM (Zonal Manager):** Conducts the first level of dealer evaluation along with RBM;
prepares presentation decks for final interviews.
- **DD-Lead:** Reviews zonal evaluations, validates recommendations, and forwards
shortlisted applicants for senior-level approval.
- **DD-Head: DD Head** is engaged in the **final review and approval** of shortlisted dealer
applications before the **NBH interview** , and later **oversees final verification and LOI**
**issuance** after all evaluations are complete.
**2.1.2 Regional Sales & Business Team**
- **RBM (Regional Business Manager):** Participates in early-stage evaluations, provides
ground-level business insights, and recommends suitable candidates.
- **ZBH (Zonal Business Head):** Conducts the second-level review along with DD-Lead;
provides strategic feedback on market and location viability.
- **NBH (National Business Head):** Holds final authority for approval or rejection of dealer
onboarding; reviews consolidated feedback from all levels.
**2.1.3 Supporting Departments**
- **Finance Team:** Reviews financial due diligence reports, validates F&F (Full and Final)
settlements, and manages monetary closure during offboarding.
- **Legal Team:** Reviews agreements, issues **Letters of Intent (LOI)** or **Termination Letters** ,
and ensures all documentation aligns with company policy.
- **Brand Experience / Architecture Team:** Manages **EOR (Essential Operating**
**Requirements)** and ensures adherence to brand and infrastructure standards.
**2.1.4 Dealers** **2.1.4 Dealers**
Once a dealer is **successfully onboarded and activated in the system** , the Dealer role is enabled Once a dealer is **successfully onboarded and activated in the system** , the Dealer role is enabled
@ -331,342 +64,7 @@ The dealer can initiate the resignation process directly through the portal , su
reason for exit, and track the status of the request across the defined review, clearance, reason for exit, and track the status of the request across the defined review, clearance,
and closure stages. and closure stages.
``` ```
- **Relocation Request Submission**
```
The dealer can submit a relocation request in scenarios where there is an intent to shift
the dealership from the current location to a new proposed location. The request is
routed for internal feasibility assessment, validation, and management approval before
execution.
```
- **Change in Constitution Request**
```
The dealer can initiate a Change in Constitution request to seek approval from RE
management for ownership or structural changes within the dealership. Upon approval,
the dealer may proceed with the legally compliant transition.
```
```
Supported Change in Constitution scenarios include:
```
```
o Proprietorship (Single Owner) → Partnership
o Proprietorship → LLP (Limited Liability Partnership)
o Proprietorship → Private Limited
o Partnership → LLP
o Partnership → Private Limited
o Private Limited → LLP
o Private Limited → Partnership
```
All dealer-initiated requests are subject to **defined validations, mandatory document
submissions, role-based reviews, and approvals**. The dealers access is **restricted to initiation,
document upload, and status visibility** , with **final decision-making authority retained by
authorized internal stakeholders of RE**
### 2.2 External & Integrated Stakeholders
**2.2.1 FDD (Financial Due Diligence Partner)**
External agency responsible for assessing the applicants financial health, verifying credentials,
and uploading due diligence reports into the system.
**2.2.2 Dealer / Applicant**
External user who applies for dealership, uploads required documents, participates in
interviews, and later accesses the portal for resignation or closure status.
## 3 Definitions and Acronyms
```
Acronym Full Form / Description
RE Royal Enfield
DD Dealer Development
DD-AM Dealer Development Area Manager
DD-ZM Dealer Development Zonal Manager
DD-Lead Dealer Development Lead
DD-Head Dealer Development Head
RBM Regional Business Manager
ZBH Zonal Business Head
NBH National Business Head
ASM Area Sales Manager
FDD Financial Due Diligence (External Partner/Agency)
LOI Letter of Intent
EOR Essential Operating Requirements
LOA Letter of Appointment
F&F Full and Final (Dealer Settlement)
KT Matrix Evaluation Matrix used for scoring applicants
```
## 4 HiFi Wireframes & Flow of Application
HiFi Wireframes : https://mono-human-93592950.figma.site
### 4.1 Dealer onboarding - Process Flow Overview
The **Dealer Onboarding Workflow** outlines the end-to-end sequence through which a dealership
application progresses — from initial registration to final inauguration and operational readiness.
**4.1.1 Step-by-Step Process Flow**
```
4.1.1.1 Application Initiation
```
- The **applicant (dealer prospect)** submits an online application through the Dealer
Onboarding Portal.
- The system checks the **locations availability** in the Royal Enfield dealership network:
o If the location has **no open opportunity** , a **Non-Opportunity Email** is triggered
automatically.
o If an opportunity exists, the applicant receives an **Opportunity Email** with login
credentials and a link to the **Dealer Questionnaire**.
```
4.1.1.2 Questionnaire Completion
```
- The applicant fills out the **comprehensive questionnaire** covering business, infrastructure,
and financial readiness.
- The system auto-scores responses, generating a **Questionnaire Score** and **initial**
**ranking** for that applicant.
- Completed applications move to the **Admin review bucket**.
- The system shall trigger automated reminders to users for completing the
questionnaire. These **reminders will be sent through WhatsApp** , to ensure timely
submission. Reminder needs to be configured from Admin.
```
4.1.1.3 Admin Validation & Shortlisting
```
- **DD-Admin** reviews all submitted applications and validates details and attached
documents.
- Based on eligibility, applications are either **shortlisted** for evaluation or **archived** for
future opportunities.
- Shortlisted applications are distributed to respective **zones or regions** for further
assessment.
```
4.1.1.4 Interview Evaluation (Multi-Level Process)
```
- Admin schedules interviews in **Level 1** , **Level 2** , and **Level 3** , as applicable.
- Each interview can be **Virtual or Physical** , with calendar invites sent via Google Calendar.
- Evaluators at each level (DD-ZM, RBM, DD-Lead, ZBH, NBH, DD-Head) record their
feedback through:
o **KT Matrix Scoring** (quantitative)
o **Interview Feedback Form** (qualitative)
- The system consolidates panel feedback and generates an **AI-driven summary and**
**ranking** for decision support.
```
4.1.1.5 Financial Due Diligence (FDD) & Finance Review
```
- Upon shortlisting, the application is assigned to the **FDD Team (external agency)** for
financial validation.
- FDD users, using SSO credentials, can:
o View assigned applications in a restricted interface.
o Upload FDD reports and add remarks in the **Work Notes** section.
o Flag cases of **non-responsiveness** or incomplete data, returning them to Admin.
- The **Finance team** reviews submitted FDD reports, validates findings, and decides
whether the application proceeds to **LOI approval**. The finance team is not the decision
maker for LOI Issuance.
```
4.1.1.6 LOI (Letter of Intent) Approval & Issuance
```
- Based on Finance clearance, **DD-Head and NBH** review and approve the **LOI request**.
- The system tracks document approvals, timestamps, and supporting artefacts.
- Once approved, the LOI document is generated, uploaded, and shared **with the**
**applicant via official email communication** and not on WhatsApp
- Notification emails are triggered to all relevant stakeholders.
```
4.1.1.7 Dealer Code Generation & Setup
```
- After LOI issuance, the **DD-Admin triggers** the Dealer Code creation process. Based on
this trigger, the **Dealer Code is created in the SAP Master** and **mapped to the applicant**
within the system.
- The code links all downstream modules, including Architectural, Statutory, and EOR
checklists.
```
4.1.1.8 Architectural Work & Statutory Documentation
```
- Architectural activities are initiated (site plans, layout approvals, branding elements).
- The applicant and assigned Architecture Team upload documents, drawings, and
blueprints.
- In parallel, the applicant uploads **Statutory Documents** such as:
o GST certificate, PAN, Partnership Deed, Firm Registration, Rental/Lease
Agreement, etc.
- Each upload is timestamped and visible with file name, uploader, and document type.
```
4.1.1.9 Payment Verification & Finance Validation
```
- Applicant uploads proof of advance payment or security deposit.
- The **Finance team** verifies payment details (transaction ID, amount, and bank record).
- Status is updated to **Verified** once the payment is reconciled.
- Verified payment triggers readiness for final operational setup.
```
4.1.1.10 Essential Operating Requirements (EOR) Checklist
```
- All functional teams (Sales, Service, IT, Finance, Training, Architecture) verify their
respective readiness parameters.
- Progress is tracked through a **completion bar** until 100% EOR compliance is achieved.
- The **EOR checklist is initiated only after LOA issuance**. All functional teams verify their
respective readiness parameters, and progress is tracked until **100% EOR compliance** is
achieved.
```
4.1.1.11 LOA (Letter of Authorization) & Final Go-Live
```
- After LOI issuance and Dealer Code generation, the **Letter of Authorization (LOA) is**
**generated and approved by NBH and DD-Head**. Upon successful LOA issuance, the
```
application proceeds to the Essential Operating Requirements (EOR) checklist for final
readiness verification.
```
- Final verification includes:
```
o EOR document review
o Brand readiness assessment
o Site validation and inspection
```
- The **LOA** officially authorizes the dealership to operate under Royal Enfield.
```
4.1.1.12 Inauguration & Closure
```
- Post-authorization, the **Inauguration** event is scheduled and logged.
- Completion of inauguration marks the dealership as **Active** in the system.
```
4.1.1.13 System-Driven Governance & Audit
```
- Each stage automatically logs:
o User action, timestamp, and remarks
o Uploaded artefacts and version control
o Notifications sent and approvals received
- The entire lifecycle remains accessible under **Audit Trail** for future reference, compliance,
or offboarding workflows.
### 4.2 Dealer Resignation Process Flow Overview
**4.2.1.1 Overview**
```
The Dealer Resignation Process manages the structured offboarding of a dealership initiated
by the dealer. The process begins when a dealer formally submits their resignation via
email to the Area Sales Manager (ASM) , after which the workflow transitions into the
system-managed approval sequence.
```
```
Dealer resignation requests are initiated by the dealer through the portal and subsequently
reviewed and processed by Admin, Finance, Legal, and relevant business stakeholders.
```
```
This flow ensures that each resignation is verified, discussed, and approved across all
required levels — maintaining proper documentation, compliance, and traceability until the
final Legal Acceptance Letter is issued.
```
**4.2.2 Step-by-Step Process Flow**
```
4.2.2.1 Dealer Initiation
```
- The dealer submits a **formal resignation email** on the dealerships official letterhead to
the **ASM**.
- The resignation reason must be clearly stated (e.g., personal, financial, business
restructuring).
- The **dealer is provided portal access** to initiate the resignation request directly through
the system. The dealer submits resignation details, reason for exit, and proposed
timeline via the portal, after which the request enters the internal review and clearance
workflow.
```
4.2.2.2 ASM Review
```
- The **ASM** reviews the dealers resignation request and supporting letter.
- Uploads the **resignation email** and **dealers letterhead document** onto the portal.
- Adds remarks summarizing the discussion and reason for resignation.
- Forwards the request to **RBM + DD-ZM** for evaluation.
```
4.2.2.3 RBM + DD-ZM Joint Evaluation
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** review the uploaded documents.
- Conduct a joint discussion with the dealer to confirm the intent and understand any
issues.
- Uploads the **Minutes of Meeting (MOM)** or discussion summary.
- Adds comments and recommendations before forwarding to **Zonal Business Head**
**(ZBH)**.
- Actions available at this stage:
o **Approve** → Send forward for next-level review
o **Send Back for Clarification** → Returns to ASM
o **Withdraw** → Cancels the request (with remarks logged)
```
4.2.2.4 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the resignation summary and all remarks.
- Adds their comments and recommendations.
- Forwards the request to **DD-Lead** through the system.
- Worknote is updated automatically to reflect action and timestamp.
- The resignation request is reviewed by authorized business stakeholders,
including **RBM, ZBH, and DD-Head**. During the review stage, the **ZBH is authorized to**
```
Send Back or Revoke the resignation request for clarification or correction. Send Back
actions are communicated to the dealer and internal teams through Work Notes , with
mandatory remarks captured for traceability.
```
```
4.2.2.5 DD-Lead Review
```
- The **DD-Lead** consolidates all discussions, documents, and feedback.
- Prepares a **Resignation Presentation** with recommendations and supporting data.
- Uploads the presentation to the portal.
- Forwards the case to **NBH** for final decision.
- The resignation request is reviewed by the **DD-Lead and DD-Head**. At this stage, both
roles are authorized to **Send Back or Revoke** the resignation request for clarification,
correction, or reconsideration. **Send Back actions are communicated through Work**
**Notes** , with **mandatory remarks** recorded for audit and traceability.
```
4.2.2.6 NBH Final Approval
```
- The **National Business Head (NBH)** reviews the entire resignation dossier.
- Adds final remarks with one of the following outcomes:
o **Approve** → Case moves automatically to Legal for letter issuance.
o **Send Back for Clarification** → Returns to DD-Lead or ZBH for revalidation.
o **Hold** → Temporarily pauses the process pending further discussion.
- Upon approval, the system triggers a **Worknote Notification** to DD-Lead, RBM, ZBH, and
Finance teams.
- The resignation request is reviewed by the **NBH** , who may **Approve, Send Back, or**
**Revoke** the request based on business considerations. Any **Send Back or Revoke action**
**must be accompanied by remarks recorded in Work Notes** , ensuring transparent
communication and governance.
```
4.2.2.7 Legal Acceptance Letter
```
- Once approved by **NBH** , the request is **auto-assigned to the Legal team**.
- Legal verifies the uploaded resignation and issues a **Resignation Acceptance Letter**.
- The letter is uploaded to the portal, visible to all relevant personas including **DD-**
**Admin** and **DD-AM**.
- Legal can also raise clarifications through worknotes if required.
- Upon completion of all approvals, the **Legal team issues the official Resignation**
**Acceptance Letter** and shares it with the dealer through authorized communication
channels.
```
4.2.2.8 DD-Admin Closure 4.2.2.8 DD-Admin Closure
``` ```
- The **DD-Admin** downloads and shares the final **Resignation Acceptance Letter** with the - The **DD-Admin** downloads and shares the final **Resignation Acceptance Letter** with the
@ -677,136 +75,6 @@ mandatory remarks captured for traceability.
**(LWD) of the dealership**. The system shall **enable and trigger the F&F workflow strictly** **(LWD) of the dealership**. The system shall **enable and trigger the F&F workflow strictly**
**based on the LWD date** , and **not based on the resignation approval date**. **based on the LWD date** , and **not based on the resignation approval date**.
### 4.3 Dealer Termination Process Flow Overview
```
4.3.1.1 Overview
```
```
The Dealer Termination Process governs the structured offboarding of a dealership initiated
internally by Royal Enfield due to operational, contractual, or ethical concerns.
It ensures that any termination—whether due to working-capital issues, poor performance,
or unethical practices —is investigated, documented, reviewed at multiple managerial levels,
and legally validated before final execution. The process maintains full transparency and
traceability through digital records, comments, and worknotes until the Termination
Letter is issued and the Full & Final (F&F) settlement begins.
```
**4.3.2 Step-by-Step Process Flow**
```
4.3.2.1 ASM Case Initiation
```
- The **Area Sales Manager (ASM)** regularly visits dealers and records **Minutes of Meeting**
**(MOM)** for performance or compliance concerns.
- After two consecutive unsatisfactory commitments or escalations, the ASM initiates
a **Termination Request** in the portal.
- Fills all operational details (Dealer Code, LOI, LOA, Sales Data, etc.), selects
a **Termination Category** (Working Capital, Performance, Unethical Practice), and
uploads supporting documents (MOMs, commitments, dealer letters).
- Submits the case to **RBM + DD-ZM** for review.
```
4.3.2.2 RBM + DD-ZM Review
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** jointly evaluate the case.
- Conduct a meeting with the dealer and record fresh MOMs; upload dealer
commitments on letterhead.
- Provide remarks and supporting evidence.
- Actions available:
o **Approve** → Forward to ZBH
o **Send Back for Clarification** → Returns to ASM with comments
o **Withdraw** → Terminates workflow with justification
```
4.3.2.3 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the full chronology (ASM visits, RBM/DD-ZM
remarks, uploaded MOMs).
- Validates escalation authenticity and dealer communication record.
- Adds remarks and forwards to **DD-Lead** for deeper review.
- The termination request is reviewed by the **ZBH** , who is authorized to **Approve, Send**
**Back, or Revoke** the termination request. **Send Back actions are communicated**
**through Work Notes** , with **mandatory remarks** recorded for traceability.
```
4.3.2.4 DD-Lead Review & Legal Assignment
```
- The **DD-Lead** cross-verifies case chronology with all stakeholders (ASM, RBM, ZBH).
- Prepares a **Termination Presentation** summarizing facts, dealer history, and
recommendations.
- Assigns the case to **Legal Team** for inputs through the system (visible in worknotes).
- The termination request is reviewed by the **DD-Lead** , who is authorized to **Send Back or**
**Revoke** the termination request for clarification or reconsideration. All such actions
require **mandatory remarks captured in Work Notes**.
```
4.3.2.5 Legal Verification
```
- The **Legal Team** reviews documentation, ensures contractual breaches are well-
supported, and checks all precedents.
- May raise queries via **Worknotes** or **Send Back** the case to DD-Lead for clarification.
- Once satisfied, forwards the verified case back to **DD-Lead** for next action.
```
4.3.2.6 DD-Lead → DD-Head Review
```
- The **DD-Lead** attaches Legals feedback and forwards the case to **DD-Head** for strategic
review.
- **DD-Head** validates the case, evaluates impact, and presents it to **National Business**
**Head (NBH)** for final business decision.
```
4.3.2.7 NBH Evaluation
```
- The **NBH** reviews all documentation and Legal remarks.
- May choose one of three actions:
o **Go Ahead** → Approve for issuance of **Show Cause Notice (SCN)**
o **Hold Decision** → Pause temporarily for further monitoring or negotiation
o **Raise Query** → Sends back to DD-Lead for additional input
```
4.3.2.8 Show Cause Notice (SCN) Issuance
```
- Upon NBH approval, the system triggers Legal to prepare and issue the **SCN**.
- The **DD-Lead** formally shares the SCN with the dealer through **DD-Admin**.
- Dealer replies to the SCN by email or letter, which **DD-Admin uploads** to the portal.
- For termination cases, the **F&F settlement process is triggered only on the Last**
**Working Day (LWD)**. The system shall **control the F&F trigger based on the LWD date** ,
irrespective of the termination approval date.
```
4.3.2.9 Evaluation of Dealer Response
```
- The **DD-Lead** , **ZBH** , **RBM** , and **DD-Head** jointly review the dealers SCN response.
- Uploads internal comments, Legal feedback, and recommendation for NBHs final
decision.
```
4.3.2.10 NBH Final Decision
```
- The **NBH** reviews the compiled case with Legal advice and decides among:
o **Approve Termination** → Moves to CEO/CCO for confirmation
o **Reconsider** → Allow additional time or corrective action
o **Reject** → Case closed without termination
```
4.3.2.11 11. CEO & CCO Authorization
```
- **CEO** and **Chief Commercial Officer (CCO)** review the NBH-approved termination.
- Provide authorization on the portal.
- Once signed off, the decision becomes final.
```
4.3.2.12 12. Legal Termination Letter
```
- The **Legal Team** generates the **Termination Letter** to the portal.
- The letter is auto-visible to **DD-Lead** , **DD-Admin** , and **Finance**.
- A system notification is triggered to all linked personas.
``` ```
4.3.2.13 13. DD-Admin Communication & F&F Trigger 4.3.2.13 13. DD-Admin Communication & F&F Trigger
@ -1753,50 +1021,3 @@ only)
``` ```
``` ```
View F&F confirmation and settlement proof post-closure. View Only View F&F confirmation and settlement proof post-closure. View Only
```
---
## 13 Non-Functional Requirements
```
Category Requirement
Performance Average response time < 3 seconds for standard operations.
Scalability Should scale horizontally on GCP.
Security JWT tokens, encrypted passwords, HTTPS enforced.
Usability Intuitive UI, consistent icons, and simple navigation.
Reliability 99% uptime target.
Backup & Recovery Daily database backup and weekly full snapshot.
Compliance Follows RE IT data privacy guidelines.
```
## 14 Technology Matrix
```
Component Specification
Database PGSQL (Managed or local instance)
Application Stack Node.js (Backend) + React.js (Frontend)
Authentication RE SSO Bridge
```
## 15 Infra requirements & System Hygiene
```
Component Specification
Environment QA / Testing
# of Virtual Machines (VMs) 1
CPU Configuration 4 - Core
Memory (RAM) 16 GB
Disk Size 500 GB
Operating System Ubuntu 24.04 LTS
```
```
Storage Type Cloud
```
Backup and Recovery
- Daily incremental and weekly full backups.
- Restore process must not exceed 2 hours.
## 16 Not in scope
Anything which comes beyond the scope defined above in terms of Width and depth

File diff suppressed because it is too large Load Diff

View File

@ -13,89 +13,12 @@ System Requirements Specifications
## Contents ## Contents
- Change Log -
- 1.1 Change Log Version 2.0
- 1.2 Change Log Dealer Self-Service Enablement
- 1 System Overview & Problem Statement
- 2 Intended Audience
- 2.1 Business & Functional Users
- 2.2 External & Integrated Stakeholders
- 3 Definitions and Acronyms
- 4 HiFi Wireframes & Flow of Application
- 4.1 Dealer onboarding - Process Flow Overview
- 4.2 Dealer Resignation Process Flow Overview
- 4.3 Dealer Termination Process Flow Overview
- 4.4 Dealer Full & Final (F&F) Settlement Process Flow
- 4.5 Finance Team Process Flow
- 5 System Features & Requirements
- 6 Dealer onboarding
- 6.1 Dealership Application Form
- 6.2 SSO Login
- 6.3 Dashboard
- 6.4 Opportunity & Non Opportunity
- 6.5 Questionnaire Response
- 6.6 Shortlisting Process
- 6.7 Shortlisted Applicants
- 6.8 Application Detail View
- 6.9 Interview Scheduling & Coordination
- 6.10 Interview Evaluation & Feedback Management
- 6.11 Interview Feedback & Evaluation Summary
- 6.12 Application Approval & Rejection Workflow
- 6.13 Work Notes & Internal Communication Trail
- 6.14 System Notifications & Alerts
- 6.15 FDD (Financial Due Diligence) & Finance Module
- 6.16 LOI Approval & Issuance
- 6.17 Dealer Code Generation, Architectural Work & Statutory Documentation............
- 6.18 LOA Issuance, Essential Operating Requirements & Inauguration
- 6.19 Essential Operating Requirements (EOR) Checklist
- 6.20 Progress Tracker.......................................................................................................
- 6.21 Central Document Repository
- 6.22 Audit Trail & Activity Log..........................................................................................
- 7 Dealer Resignation
- 7.1 Dealer Resignation Request (Initiation)
- 7.2 Resignation Management Dashboard
- 7.3 Resignation Details & Review
- 7.4 Resignation Request Review & Action Management
- 7.5 Resignation Progress Tracker
- 7.6 Documents & Audit Trail
- 8 Termination
- 8.1 Create Termination Request
- 8.2 Termination Ticket overview
- 8.3 Termination Approval & Review Process
- 8.4 Termination Progress Timeline
- 9 Admin Section
- 9.1 Master Configuration Organization
- 9.2 Zone, Region & Area Configuration
- 9.3 Roles & permissions
- 9.4 SLA Configuration & Escalation Management
- 9.5 Email & Letter Templates Management
- 9.6 Opportunity Management (Geography & Window Setup)
- 10 F&F Case
- 10.1 F&F Settlement Progress Timeline
- 10.2 Department Responses
- 11 Finance Dashboard
- 11.1 Finance Dashboard Page
- 11.2 F&F Settlement Module
- 12 Dealer Persona
- 12.1 Dealer Resignation
- 12.2 Dealer Constitutional Change Management
- 13 Non-Functional Requirements
- 14 Technology Matrix
- 15 Infra requirements & System Hygiene
- 16 Not in scope
## Change Log ## Change Log
### 1.1 Change Log Version 2.0 ### 1.1 Change Log Version 2.0
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Clarifications, Role Alignment & Access Control Enhancements
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 31 - Dec- 2025
**1.1.1 Notification Channel Enhancement** **1.1.1 Notification Channel Enhancement**
@ -103,52 +26,8 @@ System Requirements Specifications
communications (e.g., questionnaire completion and status updates), while restricting communications (e.g., questionnaire completion and status updates), while restricting
sensitive document sharing to email only. sensitive document sharing to email only.
**1.1.2 LOI Governance & Communication Clarifications**
- Clarified that the **Finance team is not the decision-making authority** for LOI issuance
and is responsible only for financial validation.
- Confirmed that **LOI documents are shared exclusively via official email** and not through
WhatsApp.
- Clarified that **LOA issuance is a parallel statutory activity** and is **not dependent on**
**infrastructure readiness**.
**1.1.3 Dealer Code Creation Control**
- Clarified that **Dealer Codes (SAP Master) are created only upon explicit trigger by the**
**DD Admin** , and not through automatic system generation.
**1.1.4 LOA & EOR Sequencing Correction**
- Corrected the workflow sequence to ensure that **LOA is issued prior to initiating the**
**EOR checklist** , with EOR serving as the final readiness validation before go-live.
**1.1.5 Dealer Resignation Access & Workflow Enhancements**
- Enabled **dealer portal access** for initiating resignation requests and uploading required
information.
- Clarified that the **Legal team issues the Resignation Acceptance Letter** in all cases.
- Expanded review authority to allow **ZBH, DD Lead, DD Head, and NBH** to **Send Back or**
**Revoke resignation requests** , with communication routed through **Work Notes**.
- Confirmed that **Full & Final (F&F) settlement is triggered strictly on the Last Working**
**Day (LWD)** and not based on approval date.
**1.1.6 Termination Workflow Governance Updates**
- Clarified that **CEO is the final approving authority** for dealer termination cases.
- Included **CCO and CEO** as approval authorities with **Approve / Hold / Reject** options.
- Confirmed that the **Legal team issues termination letters only after CEO approval**.
- Removed **dealer portal access** from termination workflows.
- Extended **Send Back / Revoke** authority to **ZBH and DD Lead** for termination reviews.
- Aligned **F&F trigger for termination** to occur strictly on the **Last Working Day (LWD)**.
**1.1.7 Role & Persona Alignment**
- Added **NBH** to the personas section.
- Added **RBM** to applicable review and approval tables.
- Clarified that **DD ASM is responsible for interview scheduling and coordination** , with
no Admin involvement.
**1.1.8 Access Control & Visibility Refinements** **1.1.8 Access Control & Visibility Refinements**
@ -172,17 +51,7 @@ System Requirements Specifications
clearly scoped responsibilities. clearly scoped responsibilities.
### 1.2 Change Log Dealer Self-Service Enablement
**Version:** v2.
**Section Impacted:** Section 12 Dealer Portal (12.1 onwards)
**Module:** Dealer Onboarding & Offboarding System
**Change Type:** Dealer Feature Enablement (Section 12 onwards)
**Scope Enhancement :** Dealer Role and Access control
**Change demarcation** : Highlighted in Yellow
**Changes suggested by** : Ashok & Tariq
**Changed performed by** : Rohit Mandiwal
**Changes done on** : 5 - Jan- 2026
**1.2.1 Introduction of Dealer Portal** **1.2.1 Introduction of Dealer Portal**
@ -191,19 +60,6 @@ System Requirements Specifications
- Dealer actions are governed by **role-based access controls** , approval hierarchies, and - Dealer actions are governed by **role-based access controls** , approval hierarchies, and
audit mechanisms. audit mechanisms.
**1.2.2 Dealer Resignation Enablement**
- Enabled **dealer-initiated resignation requests** at outlet level via the portal.
- Added structured resignation submission with:
o Last Operational Date (Sales & Services)
o Reason for resignation
o Mandatory document readiness guidance
- Enabled **dealer withdrawal option** for resignation requests **only until the case is**
**pending with NBH**.
- Clarified that **Legal team issues the Resignation Acceptance Letter** post approvals.
- Ensured **F&F settlement is triggered based on Last Working Day (LWD)** and not
approval date.
- Restricted dealer portal access **post resignation closure**.
**1.2.3 Dealer Relocation Request Enablement** **1.2.3 Dealer Relocation Request Enablement**
@ -221,21 +77,7 @@ System Requirements Specifications
- Ensured dealer has **view and upload access only** , with approvals retained by RE - Ensured dealer has **view and upload access only** , with approvals retained by RE
stakeholders. stakeholders.
**1.2.4 Dealer Constitutional Change Enablement**
- Enabled dealers to **initiate constitutional change requests** post onboarding.
- Supported all approved constitution change scenarios:
o Proprietorship, Partnership, LLP, and Private Limited permutations
- Implemented **dynamic document requirement determination** based on target
constitution.
- Explicitly confirmed **no OCR-based document validation** ; all validations are manual and
role-driven.
- Ensured statutory compliance via Legal review before master data updates.
**1.2.5 Post-Exit Access Control**
- Enforced system rule to **revoke dealer portal access** once resignation or termination is
completed.
## 1 System Overview & Problem Statement ## 1 System Overview & Problem Statement
@ -272,28 +114,6 @@ The following user personas and roles are part of the system:
### 2.1 Business & Functional Users ### 2.1 Business & Functional Users
**2.1.1 Dealer Development (DD) Team**
- **Super Admin (Master Role):**
The **Super Admin has unrestricted access** across all modules and workflows, with
authority to **configure, override, and influence workflow behavior** at every level.
```
The Super Admin role is segregated into two DD Admin roles , each with clearly defined
scopes to ensure segregation of duties and governance control.
```
- **DD-Admin:** System administrator responsible for user setup, role mapping, hierarchy
configuration, and workflow management.
- **DD-AM (Area Manager):** Reviews and manages applications within assigned regions;
performs preliminary screening.
- **DD-ZM (Zonal Manager):** Conducts the first level of dealer evaluation along with RBM;
prepares presentation decks for final interviews.
- **DD-Lead:** Reviews zonal evaluations, validates recommendations, and forwards
shortlisted applicants for senior-level approval.
- **DD-Head: DD Head** is engaged in the **final review and approval** of shortlisted dealer
applications before the **NBH interview** , and later **oversees final verification and LOI**
**issuance** after all evaluations are complete.
**2.1.2 Regional Sales & Business Team** **2.1.2 Regional Sales & Business Team**
@ -304,33 +124,6 @@ scopes to ensure segregation of duties and governance control.
- **NBH (National Business Head):** Holds final authority for approval or rejection of dealer - **NBH (National Business Head):** Holds final authority for approval or rejection of dealer
onboarding; reviews consolidated feedback from all levels. onboarding; reviews consolidated feedback from all levels.
**2.1.3 Supporting Departments**
- **Finance Team:** Reviews financial due diligence reports, validates F&F (Full and Final)
settlements, and manages monetary closure during offboarding.
- **Legal Team:** Reviews agreements, issues **Letters of Intent (LOI)** or **Termination Letters** ,
and ensures all documentation aligns with company policy.
- **Brand Experience / Architecture Team:** Manages **EOR (Essential Operating**
**Requirements)** and ensures adherence to brand and infrastructure standards.
**2.1.4 Dealers**
Once a dealer is **successfully onboarded and activated in the system** , the Dealer role is enabled
with controlled, role-based access to initiate and track select lifecycle requests. This
enhancement introduces **structured self-service capabilities for dealers** , while ensuring all
actions remain governed by defined validations, internal reviews, and approval workflows as per
RE standards.
The Dealer role is enabled to perform the following activities:
- **Resignation Initiation**
```
The dealer can initiate the resignation process directly through the portal , submit the
reason for exit, and track the status of the request across the defined review, clearance,
and closure stages.
```
- **Relocation Request Submission** - **Relocation Request Submission**
``` ```
@ -339,600 +132,13 @@ the dealership from the current location to a new proposed location. The request
routed for internal feasibility assessment, validation, and management approval before routed for internal feasibility assessment, validation, and management approval before
execution. execution.
``` ```
- **Change in Constitution Request**
```
The dealer can initiate a Change in Constitution request to seek approval from RE
management for ownership or structural changes within the dealership. Upon approval,
the dealer may proceed with the legally compliant transition.
```
```
Supported Change in Constitution scenarios include:
```
```
o Proprietorship (Single Owner) → Partnership
o Proprietorship → LLP (Limited Liability Partnership)
o Proprietorship → Private Limited
o Partnership → LLP
o Partnership → Private Limited
o Private Limited → LLP
o Private Limited → Partnership
```
All dealer-initiated requests are subject to **defined validations, mandatory document All dealer-initiated requests are subject to **defined validations, mandatory document
submissions, role-based reviews, and approvals**. The dealers access is **restricted to initiation, submissions, role-based reviews, and approvals**. The dealers access is **restricted to initiation,
document upload, and status visibility** , with **final decision-making authority retained by document upload, and status visibility** , with **final decision-making authority retained by
authorized internal stakeholders of RE** authorized internal stakeholders of RE**
### 2.2 External & Integrated Stakeholders
**2.2.1 FDD (Financial Due Diligence Partner)**
External agency responsible for assessing the applicants financial health, verifying credentials,
and uploading due diligence reports into the system.
**2.2.2 Dealer / Applicant**
External user who applies for dealership, uploads required documents, participates in
interviews, and later accesses the portal for resignation or closure status.
## 3 Definitions and Acronyms
```
Acronym Full Form / Description
RE Royal Enfield
DD Dealer Development
DD-AM Dealer Development Area Manager
DD-ZM Dealer Development Zonal Manager
DD-Lead Dealer Development Lead
DD-Head Dealer Development Head
RBM Regional Business Manager
ZBH Zonal Business Head
NBH National Business Head
ASM Area Sales Manager
FDD Financial Due Diligence (External Partner/Agency)
LOI Letter of Intent
EOR Essential Operating Requirements
LOA Letter of Appointment
F&F Full and Final (Dealer Settlement)
KT Matrix Evaluation Matrix used for scoring applicants
```
## 4 HiFi Wireframes & Flow of Application
HiFi Wireframes : https://mono-human-93592950.figma.site
### 4.1 Dealer onboarding - Process Flow Overview
The **Dealer Onboarding Workflow** outlines the end-to-end sequence through which a dealership
application progresses — from initial registration to final inauguration and operational readiness.
**4.1.1 Step-by-Step Process Flow**
```
4.1.1.1 Application Initiation
```
- The **applicant (dealer prospect)** submits an online application through the Dealer
Onboarding Portal.
- The system checks the **locations availability** in the Royal Enfield dealership network:
o If the location has **no open opportunity** , a **Non-Opportunity Email** is triggered
automatically.
o If an opportunity exists, the applicant receives an **Opportunity Email** with login
credentials and a link to the **Dealer Questionnaire**.
```
4.1.1.2 Questionnaire Completion
```
- The applicant fills out the **comprehensive questionnaire** covering business, infrastructure,
and financial readiness.
- The system auto-scores responses, generating a **Questionnaire Score** and **initial**
**ranking** for that applicant.
- Completed applications move to the **Admin review bucket**.
- The system shall trigger automated reminders to users for completing the
questionnaire. These **reminders will be sent through WhatsApp** , to ensure timely
submission. Reminder needs to be configured from Admin.
```
4.1.1.3 Admin Validation & Shortlisting
```
- **DD-Admin** reviews all submitted applications and validates details and attached
documents.
- Based on eligibility, applications are either **shortlisted** for evaluation or **archived** for
future opportunities.
- Shortlisted applications are distributed to respective **zones or regions** for further
assessment.
```
4.1.1.4 Interview Evaluation (Multi-Level Process)
```
- Admin schedules interviews in **Level 1** , **Level 2** , and **Level 3** , as applicable.
- Each interview can be **Virtual or Physical** , with calendar invites sent via Google Calendar.
- Evaluators at each level (DD-ZM, RBM, DD-Lead, ZBH, NBH, DD-Head) record their
feedback through:
o **KT Matrix Scoring** (quantitative)
o **Interview Feedback Form** (qualitative)
- The system consolidates panel feedback and generates an **AI-driven summary and**
**ranking** for decision support.
```
4.1.1.5 Financial Due Diligence (FDD) & Finance Review
```
- Upon shortlisting, the application is assigned to the **FDD Team (external agency)** for
financial validation.
- FDD users, using SSO credentials, can:
o View assigned applications in a restricted interface.
o Upload FDD reports and add remarks in the **Work Notes** section.
o Flag cases of **non-responsiveness** or incomplete data, returning them to Admin.
- The **Finance team** reviews submitted FDD reports, validates findings, and decides
whether the application proceeds to **LOI approval**. The finance team is not the decision
maker for LOI Issuance.
```
4.1.1.6 LOI (Letter of Intent) Approval & Issuance
```
- Based on Finance clearance, **DD-Head and NBH** review and approve the **LOI request**.
- The system tracks document approvals, timestamps, and supporting artefacts.
- Once approved, the LOI document is generated, uploaded, and shared **with the**
**applicant via official email communication** and not on WhatsApp
- Notification emails are triggered to all relevant stakeholders.
```
4.1.1.7 Dealer Code Generation & Setup
```
- After LOI issuance, the **DD-Admin triggers** the Dealer Code creation process. Based on
this trigger, the **Dealer Code is created in the SAP Master** and **mapped to the applicant**
within the system.
- The code links all downstream modules, including Architectural, Statutory, and EOR
checklists.
```
4.1.1.8 Architectural Work & Statutory Documentation
```
- Architectural activities are initiated (site plans, layout approvals, branding elements).
- The applicant and assigned Architecture Team upload documents, drawings, and
blueprints.
- In parallel, the applicant uploads **Statutory Documents** such as:
o GST certificate, PAN, Partnership Deed, Firm Registration, Rental/Lease
Agreement, etc.
- Each upload is timestamped and visible with file name, uploader, and document type.
```
4.1.1.9 Payment Verification & Finance Validation
```
- Applicant uploads proof of advance payment or security deposit.
- The **Finance team** verifies payment details (transaction ID, amount, and bank record).
- Status is updated to **Verified** once the payment is reconciled.
- Verified payment triggers readiness for final operational setup.
```
4.1.1.10 Essential Operating Requirements (EOR) Checklist
```
- All functional teams (Sales, Service, IT, Finance, Training, Architecture) verify their
respective readiness parameters.
- Progress is tracked through a **completion bar** until 100% EOR compliance is achieved.
- The **EOR checklist is initiated only after LOA issuance**. All functional teams verify their
respective readiness parameters, and progress is tracked until **100% EOR compliance** is
achieved.
```
4.1.1.11 LOA (Letter of Authorization) & Final Go-Live
```
- After LOI issuance and Dealer Code generation, the **Letter of Authorization (LOA) is**
**generated and approved by NBH and DD-Head**. Upon successful LOA issuance, the
```
application proceeds to the Essential Operating Requirements (EOR) checklist for final
readiness verification.
```
- Final verification includes:
```
o EOR document review
o Brand readiness assessment
o Site validation and inspection
```
- The **LOA** officially authorizes the dealership to operate under Royal Enfield.
```
4.1.1.12 Inauguration & Closure
```
- Post-authorization, the **Inauguration** event is scheduled and logged.
- Completion of inauguration marks the dealership as **Active** in the system.
```
4.1.1.13 System-Driven Governance & Audit
```
- Each stage automatically logs:
o User action, timestamp, and remarks
o Uploaded artefacts and version control
o Notifications sent and approvals received
- The entire lifecycle remains accessible under **Audit Trail** for future reference, compliance,
or offboarding workflows.
### 4.2 Dealer Resignation Process Flow Overview
**4.2.1.1 Overview**
```
The Dealer Resignation Process manages the structured offboarding of a dealership initiated
by the dealer. The process begins when a dealer formally submits their resignation via
email to the Area Sales Manager (ASM) , after which the workflow transitions into the
system-managed approval sequence.
```
```
Dealer resignation requests are initiated by the dealer through the portal and subsequently
reviewed and processed by Admin, Finance, Legal, and relevant business stakeholders.
```
```
This flow ensures that each resignation is verified, discussed, and approved across all
required levels — maintaining proper documentation, compliance, and traceability until the
final Legal Acceptance Letter is issued.
```
**4.2.2 Step-by-Step Process Flow**
```
4.2.2.1 Dealer Initiation
```
- The dealer submits a **formal resignation email** on the dealerships official letterhead to
the **ASM**.
- The resignation reason must be clearly stated (e.g., personal, financial, business
restructuring).
- The **dealer is provided portal access** to initiate the resignation request directly through
the system. The dealer submits resignation details, reason for exit, and proposed
timeline via the portal, after which the request enters the internal review and clearance
workflow.
```
4.2.2.2 ASM Review
```
- The **ASM** reviews the dealers resignation request and supporting letter.
- Uploads the **resignation email** and **dealers letterhead document** onto the portal.
- Adds remarks summarizing the discussion and reason for resignation.
- Forwards the request to **RBM + DD-ZM** for evaluation.
```
4.2.2.3 RBM + DD-ZM Joint Evaluation
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** review the uploaded documents.
- Conduct a joint discussion with the dealer to confirm the intent and understand any
issues.
- Uploads the **Minutes of Meeting (MOM)** or discussion summary.
- Adds comments and recommendations before forwarding to **Zonal Business Head**
**(ZBH)**.
- Actions available at this stage:
o **Approve** → Send forward for next-level review
o **Send Back for Clarification** → Returns to ASM
o **Withdraw** → Cancels the request (with remarks logged)
```
4.2.2.4 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the resignation summary and all remarks.
- Adds their comments and recommendations.
- Forwards the request to **DD-Lead** through the system.
- Worknote is updated automatically to reflect action and timestamp.
- The resignation request is reviewed by authorized business stakeholders,
including **RBM, ZBH, and DD-Head**. During the review stage, the **ZBH is authorized to**
```
Send Back or Revoke the resignation request for clarification or correction. Send Back
actions are communicated to the dealer and internal teams through Work Notes , with
mandatory remarks captured for traceability.
```
```
4.2.2.5 DD-Lead Review
```
- The **DD-Lead** consolidates all discussions, documents, and feedback.
- Prepares a **Resignation Presentation** with recommendations and supporting data.
- Uploads the presentation to the portal.
- Forwards the case to **NBH** for final decision.
- The resignation request is reviewed by the **DD-Lead and DD-Head**. At this stage, both
roles are authorized to **Send Back or Revoke** the resignation request for clarification,
correction, or reconsideration. **Send Back actions are communicated through Work**
**Notes** , with **mandatory remarks** recorded for audit and traceability.
```
4.2.2.6 NBH Final Approval
```
- The **National Business Head (NBH)** reviews the entire resignation dossier.
- Adds final remarks with one of the following outcomes:
o **Approve** → Case moves automatically to Legal for letter issuance.
o **Send Back for Clarification** → Returns to DD-Lead or ZBH for revalidation.
o **Hold** → Temporarily pauses the process pending further discussion.
- Upon approval, the system triggers a **Worknote Notification** to DD-Lead, RBM, ZBH, and
Finance teams.
- The resignation request is reviewed by the **NBH** , who may **Approve, Send Back, or**
**Revoke** the request based on business considerations. Any **Send Back or Revoke action**
**must be accompanied by remarks recorded in Work Notes** , ensuring transparent
communication and governance.
```
4.2.2.7 Legal Acceptance Letter
```
- Once approved by **NBH** , the request is **auto-assigned to the Legal team**.
- Legal verifies the uploaded resignation and issues a **Resignation Acceptance Letter**.
- The letter is uploaded to the portal, visible to all relevant personas including **DD-**
**Admin** and **DD-AM**.
- Legal can also raise clarifications through worknotes if required.
- Upon completion of all approvals, the **Legal team issues the official Resignation**
**Acceptance Letter** and shares it with the dealer through authorized communication
channels.
```
4.2.2.8 DD-Admin Closure
```
- The **DD-Admin** downloads and shares the final **Resignation Acceptance Letter** with the
dealer.
- Marks the resignation as completed and triggers the **F&F (Full and Final) process** by
forwarding the case to the Finance team.
- The **Full & Final (F&F) settlement process is initiated only on the Last Working Day**
**(LWD) of the dealership**. The system shall **enable and trigger the F&F workflow strictly**
**based on the LWD date** , and **not based on the resignation approval date**.
### 4.3 Dealer Termination Process Flow Overview
```
4.3.1.1 Overview
```
```
The Dealer Termination Process governs the structured offboarding of a dealership initiated
internally by Royal Enfield due to operational, contractual, or ethical concerns.
It ensures that any termination—whether due to working-capital issues, poor performance,
or unethical practices —is investigated, documented, reviewed at multiple managerial levels,
and legally validated before final execution. The process maintains full transparency and
traceability through digital records, comments, and worknotes until the Termination
Letter is issued and the Full & Final (F&F) settlement begins.
```
**4.3.2 Step-by-Step Process Flow**
```
4.3.2.1 ASM Case Initiation
```
- The **Area Sales Manager (ASM)** regularly visits dealers and records **Minutes of Meeting**
**(MOM)** for performance or compliance concerns.
- After two consecutive unsatisfactory commitments or escalations, the ASM initiates
a **Termination Request** in the portal.
- Fills all operational details (Dealer Code, LOI, LOA, Sales Data, etc.), selects
a **Termination Category** (Working Capital, Performance, Unethical Practice), and
uploads supporting documents (MOMs, commitments, dealer letters).
- Submits the case to **RBM + DD-ZM** for review.
```
4.3.2.2 RBM + DD-ZM Review
```
- The **Regional Business Manager (RBM)** and **Dealer Development Zonal Manager (DD-**
**ZM)** jointly evaluate the case.
- Conduct a meeting with the dealer and record fresh MOMs; upload dealer
commitments on letterhead.
- Provide remarks and supporting evidence.
- Actions available:
o **Approve** → Forward to ZBH
o **Send Back for Clarification** → Returns to ASM with comments
o **Withdraw** → Terminates workflow with justification
```
4.3.2.3 ZBH Review
```
- The **Zonal Business Head (ZBH)** reviews the full chronology (ASM visits, RBM/DD-ZM
remarks, uploaded MOMs).
- Validates escalation authenticity and dealer communication record.
- Adds remarks and forwards to **DD-Lead** for deeper review.
- The termination request is reviewed by the **ZBH** , who is authorized to **Approve, Send**
**Back, or Revoke** the termination request. **Send Back actions are communicated**
**through Work Notes** , with **mandatory remarks** recorded for traceability.
```
4.3.2.4 DD-Lead Review & Legal Assignment
```
- The **DD-Lead** cross-verifies case chronology with all stakeholders (ASM, RBM, ZBH).
- Prepares a **Termination Presentation** summarizing facts, dealer history, and
recommendations.
- Assigns the case to **Legal Team** for inputs through the system (visible in worknotes).
- The termination request is reviewed by the **DD-Lead** , who is authorized to **Send Back or**
**Revoke** the termination request for clarification or reconsideration. All such actions
require **mandatory remarks captured in Work Notes**.
```
4.3.2.5 Legal Verification
```
- The **Legal Team** reviews documentation, ensures contractual breaches are well-
supported, and checks all precedents.
- May raise queries via **Worknotes** or **Send Back** the case to DD-Lead for clarification.
- Once satisfied, forwards the verified case back to **DD-Lead** for next action.
```
4.3.2.6 DD-Lead → DD-Head Review
```
- The **DD-Lead** attaches Legals feedback and forwards the case to **DD-Head** for strategic
review.
- **DD-Head** validates the case, evaluates impact, and presents it to **National Business**
**Head (NBH)** for final business decision.
```
4.3.2.7 NBH Evaluation
```
- The **NBH** reviews all documentation and Legal remarks.
- May choose one of three actions:
o **Go Ahead** → Approve for issuance of **Show Cause Notice (SCN)**
o **Hold Decision** → Pause temporarily for further monitoring or negotiation
o **Raise Query** → Sends back to DD-Lead for additional input
```
4.3.2.8 Show Cause Notice (SCN) Issuance
```
- Upon NBH approval, the system triggers Legal to prepare and issue the **SCN**.
- The **DD-Lead** formally shares the SCN with the dealer through **DD-Admin**.
- Dealer replies to the SCN by email or letter, which **DD-Admin uploads** to the portal.
- For termination cases, the **F&F settlement process is triggered only on the Last**
**Working Day (LWD)**. The system shall **control the F&F trigger based on the LWD date** ,
irrespective of the termination approval date.
```
4.3.2.9 Evaluation of Dealer Response
```
- The **DD-Lead** , **ZBH** , **RBM** , and **DD-Head** jointly review the dealers SCN response.
- Uploads internal comments, Legal feedback, and recommendation for NBHs final
decision.
```
4.3.2.10 NBH Final Decision
```
- The **NBH** reviews the compiled case with Legal advice and decides among:
o **Approve Termination** → Moves to CEO/CCO for confirmation
o **Reconsider** → Allow additional time or corrective action
o **Reject** → Case closed without termination
```
4.3.2.11 11. CEO & CCO Authorization
```
- **CEO** and **Chief Commercial Officer (CCO)** review the NBH-approved termination.
- Provide authorization on the portal.
- Once signed off, the decision becomes final.
```
4.3.2.12 12. Legal Termination Letter
```
- The **Legal Team** generates the **Termination Letter** to the portal.
- The letter is auto-visible to **DD-Lead** , **DD-Admin** , and **Finance**.
- A system notification is triggered to all linked personas.
```
4.3.2.13 13. DD-Admin Communication & F&F Trigger
```
- The **DD-Admin** shares the official **Termination Letter** with the dealer and field team.
- Marks the case as “Terminated” in the portal.
- Forwards the case to **Finance** for **Full & Final Settlement** initiation.
- Updates the worknote with final remarks and due-date for settlement.
### 4.4 Dealer Full & Final (F&F) Settlement Process Flow
```
4.4.1.1 Overview
```
The **Full & Final (F&F) Settlement Process** governs the financial closure of a dealership
following **Resignation** or **Termination**.
It ensures that all financial obligations between Royal Enfield and the dealer —
including **security deposits, recoveries, payables, and department-wise dues** — are
transparently reconciled, verified, and documented before closure.
**4.4.2 Step-by-Step Process Flow**
```
4.4.2.1 F&F Initiation
```
- Triggered automatically once the **Resignation Acceptance Letter** or **Termination**
**Letter** is uploaded by **Legal**.
- The **DD-Admin** or **DD-Lead** initiates the F&F case in the **Finance Dashboard** , which
creates a unique **FNF Case ID** linked to the dealer code.
- The system auto-fetches dealer details, associated documents, resignation/termination
date, and due dates.
- Notification is sent to the **Finance Team** and all functional departments to begin the
clearance process.
```
4.4.2.2 Department-wise Response Collection
```
- The system automatically prompts all mapped **functional departments (16 in total)** to
submit their clearance inputs — including NOC, payables, recoveries, and remarks.
- Each department updates:
o Financial dues (if any)
o Clearance confirmation (NOC)
o Supporting document uploads (e.g., debit note, invoice copy)
- The system dynamically updates progress (e.g., _12/16 Departments Responded_ ) with
color-coded indicators:
o 🟢 **No Dues** Cleared
```
o 🔴 Dues Pending Outstanding financial liability
o ⚪ Pending Awaiting department input
```
- SLA-based reminders are auto-triggered for pending responses nearing the deadline.
```
4.4.2.3 Finance Summary Consolidation
```
- Once all departments respond, the **DD-Admin Team** consolidates inputs into the **Final**
**F&F Summary Sheet** , which consists of:
o **Payables to Dealer** (e.g., refundable deposits, reimbursements)
o **Receivables from Dealer** (e.g., outstanding invoices, recoveries)
o **Deductions** (policy penalties, non-compliance adjustments)
- At this stage, **department-claimed amounts are frozen** and become read-only for
departments.
- Finance does **not overwrite department claim values**. Instead, Finance validates each row
in a dedicated validation layer by recording:
- Finance decision (Accepted / Partially Accepted / Rejected / Under Clarification)
- Finance-validated amount
- Variance amount and mandatory variance reason (if changed)
- Supporting proof/document
- The system automatically calculates:
- Net Settlement = Total Payables Total Receivables Total Deductions
- Final totals are computed from **finance-validated values only**.
- Status updates to _Finance Summary Prepared_ once complete.
```
4.4.2.4 Internal Review & Clarification
```
- The **Finance Team** may use the **Work Note** section to raise clarifications to **DD-**
**Lead** , **Legal** , or concerned departments.
- If discrepancies exist (e.g., mismatched values or missing NOCs), the case remains _Under_
_Clarification_ until resolved.
- Once validated, Finance locks the summary for further edits.
```
4.4.2.5 Dealer Discussion & Acknowledgment
```
- The **Finance Team** , along with **Legal** and **DD-Lead** , discusses the settlement summary
with the dealer.
- Dealer acknowledgment is captured either via written confirmation or attached email
communication.
- The case then proceeds for **Final Finance Approval**.
```
4.4.2.6 Final Finance Approval & Payment Processing
```
- The **Finance Team** reviews the approved summary and enters payment or recovery
details:
o **Transaction Type:** RTGS / NEFT / Cheque
o **Transaction ID & Date**
o **Bank Name & Account Details** (auto-fetched from dealer profile)
o **Settlement Remarks**
- Finance takes one of three actions:
```
o Approve Settlement → Marks the case as “Finance Approved.”
o Request Clarification → Sends query to DD-Lead or Admin.
o Reject Summary → Returns for re-verification.
```
- Upon approval, notifications are sent to DD-Admin and Legal for record update.
```
4.4.2.7 F&F Completion & Closure
```
- Once approved, the case is automatically marked **Completed** , and the **Finance**
**Dashboard** updates status as _F&F Closed_.
- The **Settlement Proof** (e.g., payment confirmation or recovery adjustment) is uploaded
by Finance.
- The **DD-Admin** communicates official closure to the dealer and archives all artefacts.
- System triggers final alerts to DD-Lead, NBH, and Legal confirming completion.
- The case is archived in the **Audit Trail** for future reference.
### 4.5 Finance Team Process Flow
```
4.5.1.1 Overview 4.5.1.1 Overview
``` ```
The **Finance Team Process Flow** governs all financial activities related to dealer lifecycle The **Finance Team Process Flow** governs all financial activities related to dealer lifecycle
@ -945,42 +151,6 @@ Modules** , ensuring accurate financial updates and timely closure of all financ
**4.5.2 Step-by-Step Process Flow** **4.5.2 Step-by-Step Process Flow**
```
4.5.2.1 Security Deposit Validation (Onboarding Stage)
```
- **Trigger:**
Initiated when a new dealers onboarding application reaches the Finance stage after
DD approval.
- **Action:**
The **Finance Team** verifies the **Security Deposit** payment made by the dealer
via **RTGS/NEFT** or other approved channels.
- **Outcome:**
o Verified deposits are marked as _Approved_ , triggering system notifications to DD-
Admin and DD-Lead.
```
o The verified payment data is stored permanently in the dealers financial profile
for audit and reference.
```
```
4.5.2.2 Financial Summary Preparation
```
- **Action:**
Once departmental inputs are received, Finance consolidates all data into the **F&F**
**Summary Sheet**.
- **System Steps:**
o Segregates entries under:
**Payables to Dealer** (e.g., refundable deposits, reimbursements)
**Receivables from Dealer** (e.g., outstanding payments, penalties)
**Deductions** (e.g., policy recoveries, warranty holdbacks)
o The system auto-calculates:
o Net Settlement = Total Payables Total Receivables Deductions
o Finance validates each record, uploads supporting documents (receipts, invoices,
credit notes), and adds remarks.
- **Outcome:**
The computed **Net Settlement Amount** is reflected in the dashboard, categorized
as _Payable to Dealer_ or _Recoverable from Dealer_.
``` ```
4.5.2.3 Internal Clarification & Approval 4.5.2.3 Internal Clarification & Approval
@ -994,44 +164,9 @@ for audit and reference.
o After reconciliation, Finance locks the summary and updates case status o After reconciliation, Finance locks the summary and updates case status
to _Ready for Approval_. to _Ready for Approval_.
``` `
4.5.2.4 Final Review & Dealer Confirmation
```
- **Action:**
Finance conducts an internal review of the consolidated settlement and initiates a
financial discussion with the dealer.
- **System Steps:**
o Reviews summary details on-screen with Legal and DD-Lead.
o Records dealers acknowledgment via Work Note or attached email
confirmation.
o Once confirmed, proceeds to payment verification.
```
4.5.2.5 Payment Processing & Record Update
```
- **Action:**
Finance executes the financial transaction (payment to or recovery from dealer).
- **System Steps:**
o Enters **Mode of Payment** , **Transaction Reference Number** , **Date** , and **Remarks**.
o Uploads proof of payment (RTGS confirmation or bank statement).
o Marks case as _Finance Approved_ and sends completion notification to DD-Admin
and Legal.
o System automatically updates the **Progress Timeline** and **Audit Trail**.
```
4.5.2.6 F&F Completion & Closure
```
- **Action:**
Finance reviews all entries, confirms ledger reconciliations, and marks case
as **Completed**.
- **System Steps:**
o Locks financial data and supporting artefacts.
o Status changes to _Closed F&F Completed_.
o Final confirmation sent to all stakeholders — DD-Lead, NBH, DD-Head, Legal, and
DD-Admin.
o Finance Dashboard updates counters under “Completed Cases.”
## 5 System Features & Requirements ## 5 System Features & Requirements
Here, we describe the **system features** along with their respective **Width** and **Depth** to provide Here, we describe the **system features** along with their respective **Width** and **Depth** to provide
@ -1207,49 +342,3 @@ rules.
- Track document status and progress - Track document status and progress
- Maintain history and audit trail - Maintain history and audit trail
---
## 13 Non-Functional Requirements
```
Category Requirement
Performance Average response time < 3 seconds for standard operations.
Scalability Should scale horizontally on GCP.
Security JWT tokens, encrypted passwords, HTTPS enforced.
Usability Intuitive UI, consistent icons, and simple navigation.
Reliability 99% uptime target.
Backup & Recovery Daily database backup and weekly full snapshot.
Compliance Follows RE IT data privacy guidelines.
```
## 14 Technology Matrix
```
Component Specification
Database PGSQL (Managed or local instance)
Application Stack Node.js (Backend) + React.js (Frontend)
Authentication RE SSO Bridge
```
## 15 Infra requirements & System Hygiene
```
Component Specification
Environment QA / Testing
# of Virtual Machines (VMs) 1
CPU Configuration 4 - Core
Memory (RAM) 16 GB
Disk Size 500 GB
Operating System Ubuntu 24.04 LTS
```
```
Storage Type Cloud
```
Backup and Recovery
- Daily incremental and weekly full backups.
- Restore process must not exceed 2 hours.
## 16 Not in scope
Anything which comes beyond the scope defined above in terms of Width and depth

View File

@ -176,7 +176,7 @@ export const OVERALL_STATUS_TO_DB_CURRENT_STAGE: Record<
// Termination Stages // Termination Stages
export const TERMINATION_STAGES = { export const TERMINATION_STAGES = {
SUBMITTED: 'Submitted', SUBMITTED: 'Submitted',
RBM_REVIEW: 'RBM Review', RBM_REVIEW: 'RBM + DD-ZM Review',
ZBH_REVIEW: 'ZBH Review', ZBH_REVIEW: 'ZBH Review',
DD_LEAD_REVIEW: 'DD Lead Review', DD_LEAD_REVIEW: 'DD Lead Review',
LEGAL_VERIFICATION: 'Legal Verification', LEGAL_VERIFICATION: 'Legal Verification',
@ -496,6 +496,7 @@ export const RESIGNATION_DOCUMENT_TYPES = [
'Legal Communication', 'Legal Communication',
'Handover Document', 'Handover Document',
'Settlement Supporting Document', 'Settlement Supporting Document',
'PPT Presentation',
'Other' 'Other'
] as const; ] as const;
@ -523,7 +524,7 @@ export const TERMINATION_DOCUMENT_TYPES = [
export const TERMINATION_DOCUMENT_STAGES = [ export const TERMINATION_DOCUMENT_STAGES = [
'Submitted', 'Submitted',
'RBM Review', 'RBM + DD-ZM Review',
'ZBH Review', 'ZBH Review',
'DD Lead Review', 'DD Lead Review',
'Legal Verification', 'Legal Verification',
@ -569,5 +570,5 @@ export const STAGES_MAP = {
'RESIGNATION': ['Submission', 'Regional Review', 'ZM Review', 'ZBH Review', 'Finance Review', 'DDL Review', 'Approved'], 'RESIGNATION': ['Submission', 'Regional Review', 'ZM Review', 'ZBH Review', 'Finance Review', 'DDL Review', 'Approved'],
'RELOCATION': ['Initiated', 'ASM Review', 'ZM Review', 'ZBH Review', 'Completed'], 'RELOCATION': ['Initiated', 'ASM Review', 'ZM Review', 'ZBH Review', 'Completed'],
'CONSTITUTIONAL_CHANGE': ['Draft', 'Legal Review', 'Approved'], 'CONSTITUTIONAL_CHANGE': ['Draft', 'Legal Review', 'Approved'],
'TERMINATION': ['Hearing', 'Review', 'Closed'] 'TERMINATION': ['Submitted', 'RBM + DD-ZM Review', 'ZBH Review', 'DD Lead Review', 'Legal Verification', 'NBH Evaluation', 'SCN', 'Personal Hearing', 'Completed']
} as const; } as const;

View File

@ -48,7 +48,9 @@ const fileFilter = (req: Request, file: Express.Multer.File, cb: FileFilterCallb
'application/msword', 'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel', 'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
]; ];
if (allowedTypes.includes(file.mimetype)) { if (allowedTypes.includes(file.mimetype)) {

View File

@ -61,7 +61,8 @@ export function registerEmailPartials(h: typeof handlebars = handlebars): void {
const map: Record<string, string> = { const map: Record<string, string> = {
email_header: 'email_header.html', email_header: 'email_header.html',
email_footer: 'email_footer.html', email_footer: 'email_footer.html',
primary_cta: 'primary_cta.html' primary_cta: 'primary_cta.html',
cta_button: 'primary_cta.html'
}; };
let loaded = 0; let loaded = 0;

View File

@ -2,7 +2,14 @@ import db from '../../database/models/index.js';
import { Op } from 'sequelize'; import { Op } from 'sequelize';
import { sendEmail } from './email.service.js'; import { sendEmail } from './email.service.js';
import { NotificationService } from '../../services/NotificationService.js'; import { NotificationService } from '../../services/NotificationService.js';
import { REQUEST_TYPES, ROLES } from '../config/constants.js'; import {
APPLICATION_STAGES,
TERMINATION_STAGES,
CONSTITUTIONAL_STAGES,
RELOCATION_STAGES,
REQUEST_TYPES,
ROLES
} from '../config/constants.js';
const { RequestParticipant, User, Outlet, District } = db; const { RequestParticipant, User, Outlet, District } = db;
@ -134,7 +141,8 @@ export async function notifyRelocationSubmittedEmails(
dealerName, dealerName,
requestId: code, requestId: code,
link: `${base}/relocation-requests/${request.id}`, link: `${base}/relocation-requests/${request.id}`,
ctaLabel: 'View request' ctaLabel: 'View request',
distance: request.distance || '0'
} }
).catch((err) => console.error('[notifyRelocationSubmittedEmails] dealer:', err)); ).catch((err) => console.error('[notifyRelocationSubmittedEmails] dealer:', err));
} }
@ -157,9 +165,10 @@ export async function notifyRelocationSubmittedEmails(
placeholders: { placeholders: {
dealerName, dealerName,
requestId: code, requestId: code,
outletCode: outlet?.code || '', outletCode: outlet?.code || 'N/A',
link: `${base}/relocation-requests/${request.id}`, link: `${base}/relocation-requests/${request.id}`,
ctaLabel: 'Review relocation', ctaLabel: 'Review request',
distance: request.distance || '0',
phone: asmPhone || '' phone: asmPhone || ''
} }
}).catch((err) => console.error('[notifyRelocationSubmittedEmails] ASM:', err)); }).catch((err) => console.error('[notifyRelocationSubmittedEmails] ASM:', err));
@ -184,7 +193,7 @@ export async function resolveNextActors(requestId: string, requestType: string,
'ASM': [ROLES.ASM], 'ASM': [ROLES.ASM],
'ASM Review': [ROLES.ASM], 'ASM Review': [ROLES.ASM],
'RBM': [ROLES.RBM], 'RBM': [ROLES.RBM],
'RBM Review': [ROLES.RBM], 'RBM + DD-ZM Review': [ROLES.RBM, ROLES.DD_ZM],
'ZM Review': [ROLES.DD_ZM], 'ZM Review': [ROLES.DD_ZM],
'DD ZM Review': [ROLES.DD_ZM], 'DD ZM Review': [ROLES.DD_ZM],
'ZBH': [ROLES.ZBH], 'ZBH': [ROLES.ZBH],
@ -239,10 +248,12 @@ export async function resolveNextActors(requestId: string, requestType: string,
'Service Clearance': [ROLES.SERVICE_MANAGER], 'Service Clearance': [ROLES.SERVICE_MANAGER],
'Accounts Clearance': [ROLES.ACCOUNTS_MANAGER], 'Accounts Clearance': [ROLES.ACCOUNTS_MANAGER],
'F&F Initiated': [ROLES.DD_ADMIN], 'F&F Initiated': [ROLES.DD_ADMIN],
// SRS §7.5.2 — Legal acceptance letter upload triggers notification to DD-Admin + ASM
'Resignation Legal Closure': [ROLES.DD_ADMIN, ROLES.ASM],
// --- Termination Specific --- // --- Termination Specific ---
'Show Cause Notice': [ROLES.NBH], 'Show Cause Notice': [ROLES.LEGAL_ADMIN],
'Personal Hearing': [ROLES.NBH], 'Personal Hearing': [ROLES.NBH, ROLES.DD_LEAD, ROLES.ZBH, ROLES.RBM, ROLES.DD_HEAD],
'Legal - Termination Letter': [ROLES.LEGAL_ADMIN] 'Legal - Termination Letter': [ROLES.LEGAL_ADMIN]
}; };
@ -376,39 +387,67 @@ export async function notifyStakeholdersOnTransition(
} else if (isDealer) { } else if (isDealer) {
// ── Dealer: in-app always; email + WhatsApp only on terminal events ── // ── Dealer: in-app always; email + WhatsApp only on terminal events ──
// SRS §2052: rejection notifies dealer/applicant via email & WhatsApp
// SRS §2324: approvals/outcomes delivered via email & WhatsApp
const terminalChannels: Array<'system' | 'email' | 'whatsapp'> = ['system', 'email']; const terminalChannels: Array<'system' | 'email' | 'whatsapp'> = ['system', 'email'];
if (phone) terminalChannels.push('whatsapp'); if (phone) terminalChannels.push('whatsapp');
let templateCode = 'WORKFLOW_STATUS_UPDATE_DEALER';
const placeholders: any = {
requestId: metadata.code,
link: metadata.link,
targetStage,
dealerName: metadata.dealerName,
phone: phone || ''
};
// Override for Termination Final Closure
if (targetStage === TERMINATION_STAGES.TERMINATED) {
templateCode = 'TERMINATION_FINAL_CLOSURE_DEALER';
placeholders.terminationDate = new Date().toLocaleDateString('en-IN', { dateStyle: 'medium' });
}
// Override for Constitutional Change Completion
if (targetStage === CONSTITUTIONAL_STAGES.COMPLETED && requestType === REQUEST_TYPES.CONSTITUTIONAL) {
templateCode = 'CONSTITUTIONAL_CHANGE_APPROVED';
placeholders.proposedConstitution = metadata.remarks || 'Approved Structure'; // Remarks often contain the final structure or approval note
}
// Override for Relocation Completion
if (targetStage === RELOCATION_STAGES.COMPLETED && requestType === REQUEST_TYPES.RELOCATION) {
templateCode = 'RELOCATION_APPROVED';
placeholders.newLocation = metadata.remarks || 'Approved Location'; // Remarks usually contain the site address
}
await NotificationService.notify(u.id, u.email, { await NotificationService.notify(u.id, u.email, {
title: isTerminalEvent title: isTerminalEvent
? `Application ${isRejected ? 'Rejected' : isRevoked ? 'Revoked' : 'Completed'}: ${metadata.code}` ? `Application ${isRejected ? 'Rejected' : isRevoked ? 'Revoked' : 'Completed'}: ${metadata.code}`
: `Application Update: ${metadata.code}`, : `Application Update: ${metadata.code}`,
message: `Your request is now at "${targetStage}". ${metadata.action}`, message: `Your request is now at "${targetStage}". ${metadata.action}`,
channels: isTerminalEvent ? terminalChannels : ['system'], channels: isTerminalEvent ? terminalChannels : ['system'],
templateCode: 'WORKFLOW_STATUS_UPDATE_DEALER', templateCode,
placeholders: { placeholders
requestId: metadata.code,
link: metadata.link,
targetStage,
dealerName: metadata.dealerName,
phone: phone || ''
}
}).catch(e => console.error('[notifyStakeholders] dealer:', e)); }).catch(e => console.error('[notifyStakeholders] dealer:', e));
} else if (isTerminalEvent && isKeyObserverRole) { } else if (isTerminalEvent && isKeyObserverRole) {
// ── Key observers (DD Lead, DD Head, NBH, DD Admin) on terminal events — in-app only ── // ── Key observers (DD Lead, DD Head, NBH, DD Admin) on terminal events ──
let templateCode = 'WORKFLOW_STATUS_UPDATE_DEALER';
const placeholders: any = {
requestId: metadata.code,
link: metadata.link,
targetStage,
recipientName: u.fullName || 'Team'
};
// Override for Internal Notification of Legal Letter
if (targetStage === TERMINATION_STAGES.LEGAL_LETTER) {
templateCode = 'TERMINATION_LETTER_ISSUED';
}
await NotificationService.notify(u.id, u.email, { await NotificationService.notify(u.id, u.email, {
title: `Case Closed: ${metadata.code}`, title: `Case Closed: ${metadata.code}`,
message: `${metadata.code} has been ${isRejected ? 'rejected' : isRevoked ? 'revoked' : 'completed'} at stage "${targetStage}".`, message: `${metadata.code} has been ${isRejected ? 'rejected' : isRevoked ? 'revoked' : 'completed'} at stage "${targetStage}".`,
channels: ['system'], channels: ['system', 'email'], // Internal teams get email too on closure
templateCode: 'WORKFLOW_STATUS_UPDATE_DEALER', templateCode,
placeholders: { placeholders
requestId: metadata.code,
link: metadata.link,
targetStage
}
}).catch(e => console.error('[notifyStakeholders] observer:', e)); }).catch(e => console.error('[notifyStakeholders] observer:', e));
} }
} }

View File

@ -5,23 +5,33 @@ export const ALLOWED_EMAIL_TEMPLATE_CODES = [
'APPLICANT_SHORTLISTED', 'APPLICANT_SHORTLISTED',
'APPLICANT_REJECTED', 'APPLICANT_REJECTED',
'CONSTITUTIONAL_CHANGE_SUBMITTED', 'CONSTITUTIONAL_CHANGE_SUBMITTED',
'CONSTITUTIONAL_CHANGE_APPROVED',
'CONSTITUTIONAL_CHANGE_UPDATE', 'CONSTITUTIONAL_CHANGE_UPDATE',
'DEALER_CODE_READY', 'DEALER_CODE_READY',
'EOR_COMPLETED', 'EOR_COMPLETED',
'FNF_INITIATED', 'FNF_INITIATED',
'FNF_SUMMARY_PREPARED',
'FNF_SETTLEMENT_APPROVED',
'GENERIC_NOTIFICATION', 'GENERIC_NOTIFICATION',
'INAUGURATION_COMPLETED',
'INTERVIEW_SCHEDULED', 'INTERVIEW_SCHEDULED',
'INTERVIEW_SCHEDULED_APPLICANT', 'INTERVIEW_SCHEDULED_APPLICANT',
'INTERVIEW_SCHEDULED_PANELIST', 'INTERVIEW_SCHEDULED_PANELIST',
'INTERVIEW_RESCHEDULED_APPLICANT',
'INTERVIEW_RESCHEDULED_PANELIST',
'INTERVIEW_CANCELLED_APPLICANT',
'INTERVIEW_CANCELLED_PANELIST',
'LOA_ISSUED', 'LOA_ISSUED',
'LOI_ISSUED', 'LOI_ISSUED',
'NON_OPPORTUNITY', 'NON_OPPORTUNITY',
'ONBOARDING_PAYMENT_VERIFIED',
'ONBOARDING_STATUS_UPDATE', 'ONBOARDING_STATUS_UPDATE',
'OPPORTUNITY', 'OPPORTUNITY',
'QUESTIONNAIRE_REMINDER', 'QUESTIONNAIRE_REMINDER',
'QUESTIONNAIRE_SUBMITTED', 'QUESTIONNAIRE_SUBMITTED',
'RELOCATION_RECEIVED', 'RELOCATION_RECEIVED',
'RELOCATION_SUBMITTED', 'RELOCATION_SUBMITTED',
'RELOCATION_APPROVED',
'RELOCATION_UPDATE', 'RELOCATION_UPDATE',
'RESIGNATION_APPROVED', 'RESIGNATION_APPROVED',
'RESIGNATION_RECEIVED', 'RESIGNATION_RECEIVED',
@ -33,6 +43,8 @@ export const ALLOWED_EMAIL_TEMPLATE_CODES = [
'SLA_ESCALATION', 'SLA_ESCALATION',
'TERMINATION_INITIATED', 'TERMINATION_INITIATED',
'TERMINATION_SCN_ISSUED', 'TERMINATION_SCN_ISSUED',
'TERMINATION_LETTER_ISSUED',
'TERMINATION_FINAL_CLOSURE_DEALER',
'TERMINATION_UPDATE', 'TERMINATION_UPDATE',
'USER_ASSIGNED', 'USER_ASSIGNED',
'WORKNOTE_NOTIFICATION', 'WORKNOTE_NOTIFICATION',

View File

@ -0,0 +1,31 @@
{{> email_header}}
<div class="section">
<h2 style="color:#2e7d32;">Constitutional Change Approved — {{requestId}}</h2>
<p>Dear {{dealerName}},</p>
<p>
We are pleased to inform you that your request for a **Change in Constitution** (Request ID: <strong>{{requestId}}</strong>)
has been officially approved by the Royal Enfield management.
</p>
<div style="background:#e8f5e9; border-left:4px solid #2e7d32; padding:12px 16px; margin: 16px 0;">
<strong>New Constitution:</strong> {{proposedConstitution}}<br/>
<strong>Status:</strong> Approved & Updated
</div>
<p>
The system records have been updated to reflect this change. You can now proceed with the legally compliant transition
as per the approved structure.
</p>
<div style="text-align:center; margin: 24px 0;">
<a href="{{link}}" class="btn">View Request Details</a>
</div>
<p style="color:#888; font-size:12px;">
Best Regards,<br/>
<strong>Royal Enfield Dealer Development Team</strong>
</p>
</div>
{{> email_footer}}

View File

@ -0,0 +1,29 @@
{{> email_header}}
<div class="section">
<h2 style="color:#2e7d32;">F&F Settlement Approved — {{fnfId}}</h2>
<p>Dear Team,</p>
<p>
The final Full & Final (F&F) settlement for dealer <strong>{{dealerName}}</strong>
(F&F ID: <strong>{{fnfId}}</strong>) has been <strong>Approved</strong> by Finance.
</p>
<div style="background:#e8f5e9; border-left:4px solid #2e7d32; padding:12px 16px; margin: 16px 0;">
<strong>Settlement Amount:</strong> ₹{{settlementAmount}}<br/>
<strong>Status:</strong> Approved & Closed
</div>
<p>
The DD-Admin and Legal teams are requested to update their records and proceed with final account closure.
</p>
<div style="text-align:center; margin: 24px 0;">
{{> cta_button}}
</div>
<p style="color:#888; font-size:12px;">
All financial transactions related to this dealership exit are now finalized.
</p>
</div>
{{> email_footer}}

View File

@ -0,0 +1,29 @@
{{> email_header}}
<div class="section">
<h2>F&F Settlement Summary Prepared — {{fnfId}}</h2>
<p>Dear Finance Team,</p>
<p>
The initial Full & Final (F&F) settlement summary has been prepared for
<strong>{{dealerName}}</strong> (F&F ID: <strong>{{fnfId}}</strong>).
</p>
<div style="background:#f5f5f5; border-left:4px solid #333; padding:12px 16px; margin: 16px 0;">
<strong>Calculated Net Amount:</strong> ₹{{netAmount}}<br/>
<strong>Status:</strong> Pending Final Approval
</div>
<p>
Please review the consolidated departmental responses and the settlement summary to proceed with final approval and payment processing.
</p>
<div style="text-align:center; margin: 24px 0;">
{{> cta_button}}
</div>
<p style="color:#888; font-size:12px;">
Confidential: This summary contains sensitive financial data. Review only via authorized portal access.
</p>
</div>
{{> email_footer}}

View File

@ -0,0 +1,22 @@
{{> email_header}}
<div class="section">
<h2 style="color:#2e7d32;">Dealership Inauguration Logged — {{applicationId}}</h2>
<p>Dear Team,</p>
<p>
We are pleased to inform you that the inauguration for dealer
<strong>{{dealerName}}</strong> (Application ID: <strong>{{applicationId}}</strong>)
at <strong>{{location}}</strong> has been successfully logged on <strong>{{date}}</strong>.
</p>
<p>
The dealership is now marked as <strong>Active</strong> in the system. All relevant teams are requested to
update their records accordingly.
</p>
<p style="color:#888; font-size:12px;">
This is an automated notification confirming the completion of the onboarding lifecycle.
</p>
</div>
{{> email_footer}}

View File

@ -0,0 +1,29 @@
{{> email_header}}
<div class="section">
<h2 style="color:#2e7d32;">Payment Verified — {{applicationId}}</h2>
<p>Dear Team,</p>
<p>
Finance has successfully verified the <strong>{{paymentType}}</strong> for
<strong>{{dealerName}}</strong> (Application ID: <strong>{{applicationId}}</strong>).
</p>
<div style="background:#e8f5e9; border-left:4px solid #2e7d32; padding:12px 16px; margin: 16px 0;">
<strong>Verified Amount:</strong> ₹{{amount}}<br/>
<strong>Status:</strong> Verified & Approved
</div>
<p>
The onboarding process can now proceed to the next stage.
</p>
<div style="text-align:center; margin: 24px 0;">
<a href="{{link}}" class="btn">View Application</a>
</div>
<p style="color:#888; font-size:12px;">
This is an automated notification from the Royal Enfield Dealer Onboarding System.
</p>
</div>
{{> email_footer}}

View File

@ -0,0 +1,31 @@
{{> email_header}}
<div class="section">
<h2 style="color:#2e7d32;">Relocation Approved — {{requestId}}</h2>
<p>Dear {{dealerName}},</p>
<p>
We are pleased to inform you that your request for **Dealership Relocation** (Request ID: <strong>{{requestId}}</strong>)
has been officially approved by the Royal Enfield management.
</p>
<div style="background:#e8f5e9; border-left:4px solid #2e7d32; padding:12px 16px; margin: 16px 0;">
<strong>New Location:</strong> {{newLocation}}<br/>
<strong>Status:</strong> Approved & Records Updated
</div>
<p>
Our team will coordinate with you for the physical transition and site readiness audit. You can track the next steps
via the portal.
</p>
<div style="text-align:center; margin: 24px 0;">
<a href="{{link}}" class="btn">View Request Details</a>
</div>
<p style="color:#888; font-size:12px;">
Best Regards,<br/>
<strong>Royal Enfield Dealer Development Team</strong>
</p>
</div>
{{> email_footer}}

View File

@ -1,6 +1,33 @@
{{> email_header}} {{> email_header}}
<h2>Hi {{dealerName}},</h2>
<p>Your outlet relocation request <strong>{{requestId}}</strong> has been received.</p> <div class="section">
<p>You will receive email updates as the request moves through approvals.</p> <h2>Relocation Request Received — {{requestId}}</h2>
{{> primary_cta}} <p>Dear {{dealerName}},</p>
<p>
We have received your request for dealership relocation (Request ID: <strong>{{requestId}}</strong>).
</p>
<p>
The internal feasibility assessment and multi-level review process have been initiated.
You will be notified of any document requirements or status updates via the portal and email.
</p>
<div style="background:#fff3e0; border-left:4px solid #ff9800; padding:12px 16px; margin: 16px 0;">
<strong>Current Status:</strong> ASM Review (In Progress)
</div>
<div style="text-align:center; margin: 24px 0;">
{{> cta_button}}
</div>
<p>
You can track the real-time progress of your request by logging into the Dealer Portal.
</p>
<p style="color:#888; font-size:12px;">
Best Regards,<br/>
<strong>Royal Enfield Dealer Development Team</strong>
</p>
</div>
{{> email_footer}} {{> email_footer}}

View File

@ -1,7 +1,31 @@
{{> email_header}} {{> email_header}}
<h2>New relocation request</h2>
<p>A dealer has submitted an outlet relocation request.</p> <div class="section">
<p><strong>Request ID:</strong> {{requestId}}<br><strong>Outlet:</strong> {{outletCode}}</p> <h2 style="color:#e31837;">New Relocation Request: {{requestId}}</h2>
<p>Please review in the Dealer Development portal.</p> <p>Dear Team,</p>
{{> primary_cta}} <p>
A new dealership relocation request has been submitted by <strong>{{dealerName}}</strong>
for outlet <strong>{{outletCode}}</strong>.
</p>
<div style="background:#f5f5f5; border-left:4px solid #e31837; padding:12px 16px; margin: 16px 0;">
<strong>Request ID:</strong> {{requestId}}<br/>
<strong>Outlet Code:</strong> {{outletCode}}<br/>
<strong>Distance from Existing Site:</strong> {{distance}} km
</div>
<p>
Please log in to the Dealer Development portal to review the proposed location, property documents,
and feasibility details.
</p>
<div style="text-align:center; margin: 24px 0;">
{{> cta_button}}
</div>
<p style="color:#888; font-size:12px;">
This is an internal workflow notification. Audit logs and case chronology are available on the portal.
</p>
</div>
{{> email_footer}} {{> email_footer}}

View File

@ -0,0 +1,30 @@
{{> email_header}}
<div class="section">
<h2 style="color:#e31837;">Notice of Termination — {{requestId}}</h2>
<p>Dear {{dealerName}},</p>
<p>
This is the official notification that your dealership agreement with Royal Enfield (Request ID: <strong>{{requestId}}</strong>)
has been formally terminated effective <strong>{{terminationDate}}</strong>.
</p>
<p>
The final Termination Letter is available for your reference in the dealer portal. Your portal access will remain active
for a limited period to allow you to download relevant documents and track the Full & Final (F&F) settlement progress.
</p>
<div style="text-align:center; margin: 24px 0;">
{{> cta_button}}
</div>
<p>
For any clarifications regarding the settlement process, please contact the Dealer Development Admin team.
</p>
<p style="color:#888; font-size:12px;">
Best Regards,<br/>
<strong>Royal Enfield Dealer Development Team</strong>
</p>
</div>
{{> email_footer}}

View File

@ -0,0 +1,25 @@
{{> email_header}}
<div class="section">
<h2 style="color:#e31837;">Termination Letter Generated — {{requestId}}</h2>
<p>Dear {{recipientName}},</p>
<p>
The official <strong>Termination Letter</strong> has been generated and uploaded to the portal for dealer
<strong>{{dealerName}}</strong> (Request ID: <strong>{{requestId}}</strong>).
</p>
<p>
This letter is now visible to the DD-Lead, DD-Admin, and Finance teams. Please proceed with the necessary
administrative and financial closure steps.
</p>
<div style="text-align:center; margin: 24px 0;">
{{> cta_button}}
</div>
<p style="color:#888; font-size:12px;">
This is an internal system notification. Detailed case chronology and audit logs are available on the portal.
</p>
</div>
{{> email_footer}}

View File

@ -20,6 +20,18 @@ const getLocationAncestors = async (locationId: string): Promise<string[]> => {
const interviewStageCode = (level: number) => `INTERVIEW_LEVEL_${level}`; const interviewStageCode = (level: number) => `INTERVIEW_LEVEL_${level}`;
const formatIST = (date: Date) => {
return new Intl.DateTimeFormat('en-IN', {
timeZone: 'Asia/Kolkata',
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: true
}).format(date);
};
const normalizeRoleCode = (value: unknown) => const normalizeRoleCode = (value: unknown) =>
String(value || '') String(value || '')
.trim() .trim()
@ -567,8 +579,9 @@ export const scheduleInterview = async (req: AuthRequest, res: Response) => {
applicantName: application.applicantName, applicantName: application.applicantName,
applicationId: application.applicationId, applicationId: application.applicationId,
type, type,
scheduledAt: scheduledAtIso, scheduledAt: formatIST(scheduledDateObj),
link: meetLink, meetLink,
appLink: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/onboarding/application/${application.id}`,
phone: applicantPhone, phone: applicantPhone,
ctaLabel: 'View Schedule' ctaLabel: 'View Schedule'
} }
@ -682,8 +695,9 @@ export const scheduleInterview = async (req: AuthRequest, res: Response) => {
applicantName: application?.applicantName || 'Applicant', applicantName: application?.applicantName || 'Applicant',
applicationId: application?.applicationId || '', applicationId: application?.applicationId || '',
type, type,
scheduledAt: scheduledAtIso, scheduledAt: formatIST(scheduledDateObj),
link: meetLink, meetLink,
appLink: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/onboarding/application/${application.id}`,
phone: pPhone || '', phone: pPhone || '',
ctaLabel: 'Open Assessment' ctaLabel: 'Open Assessment'
} }
@ -749,11 +763,81 @@ export const updateInterview = async (req: AuthRequest, res: Response) => {
} }
await interview.update(updatePayload); await interview.update(updatePayload);
await interview.reload({
include: [
{
model: InterviewParticipant,
as: 'participants',
include: [{ model: User, as: 'user' }]
}
]
});
const isCancelled = String(status || '').toLowerCase() === 'cancelled' && String(oldStatus || '').toLowerCase() !== 'cancelled'; const isCancelled = String(status || '').toLowerCase() === 'cancelled' && String(oldStatus || '').toLowerCase() !== 'cancelled';
const isRescheduled = typeof scheduledAt !== 'undefined' && String(status || '').toLowerCase() !== 'cancelled'; const isRescheduled = typeof scheduledAt !== 'undefined' && String(status || '').toLowerCase() !== 'cancelled';
const eventType = isCancelled ? 'interview_cancelled' : (isRescheduled ? 'interview_rescheduled' : 'interview_updated'); const eventType = isCancelled ? 'interview_cancelled' : (isRescheduled ? 'interview_rescheduled' : 'interview_updated');
if (isRescheduled || isCancelled) {
const application = await db.Application.findByPk(interview.applicationId);
if (application) {
const scheduledAtIso = interview.scheduleDate.toISOString();
const type = interview.interviewType;
const meetLink = interview.linkOrLocation;
const notificationPromises: Promise<any>[] = [];
// Notify Applicant
notificationPromises.push(
NotificationService.notify(null, application.email, {
title: isCancelled ? `Interview Cancelled: ${application.applicationId}` : `Interview Rescheduled: ${application.applicationId}`,
message: isCancelled
? `Dear ${application.applicantName}, your ${type} has been cancelled.`
: `Dear ${application.applicantName}, your ${type} has been rescheduled to ${formatIST(interview.scheduleDate)}.`,
channels: application.mobileNumber ? ['email', 'whatsapp', 'system'] : ['email', 'system'],
templateCode: isCancelled ? 'INTERVIEW_CANCELLED_APPLICANT' : 'INTERVIEW_RESCHEDULED_APPLICANT',
placeholders: {
applicantName: application.applicantName,
applicationId: application.applicationId,
type,
scheduledAt: formatIST(interview.scheduleDate),
meetLink,
appLink: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/onboarding/application/${application.id}`,
phone: application.mobileNumber || '',
ctaLabel: 'View Schedule'
}
}).catch(err => console.error('Failed to notify applicant of reschedule/cancellation:', err))
);
// Notify Panelists
const participants = (interview as any).participants || [];
for (const p of participants) {
const panelist = p.user;
if (panelist?.email) {
notificationPromises.push(
NotificationService.notify(panelist.id, panelist.email, {
title: isCancelled ? `Interview Cancelled: ${application.applicationId}` : `Interview Rescheduled: ${application.applicationId}`,
message: isCancelled
? `The ${type} for ${application.applicantName} has been cancelled.`
: `The ${type} for ${application.applicantName} has been rescheduled to ${formatIST(interview.scheduleDate)}.`,
channels: panelist.mobileNumber ? ['email', 'system', 'whatsapp'] : ['email', 'system'],
templateCode: isCancelled ? 'INTERVIEW_CANCELLED_PANELIST' : 'INTERVIEW_RESCHEDULED_PANELIST',
placeholders: {
panelistName: panelist.fullName,
applicantName: application.applicantName,
applicationId: application.applicationId,
type,
scheduledAt: formatIST(interview.scheduleDate),
meetLink,
appLink: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/onboarding/application/${application.id}`,
phone: panelist.mobileNumber || '',
ctaLabel: 'Open Assessment'
}
}).catch(err => console.error(`Failed to notify panelist (${panelist.id}) of reschedule/cancellation:`, err))
);
}
}
await Promise.all(notificationPromises);
}
}
await db.AuditLog.create({ await db.AuditLog.create({
userId: req.user?.id || null, userId: req.user?.id || null,
action: AUDIT_ACTIONS.INTERVIEW_UPDATED, action: AUDIT_ACTIONS.INTERVIEW_UPDATED,

View File

@ -208,9 +208,11 @@ const getNormalizedAuditPayload = (logData: any, entityType: string, entityId: s
(payload?.context as any)?.currentStage || (payload?.context as any)?.currentStage ||
null, null,
actor: { actor: {
id: logData.userId || logData.actorId || logData.user?.id || null,
name: actorName, name: actorName,
email: logData.user?.email || logData.userEmail || null email: logData.user?.email || logData.userEmail || null
}, },
actorId: logData.userId || logData.actorId || logData.user?.id || null,
userName: actorName, userName: actorName,
userEmail: logData.user?.email || logData.userEmail || null, userEmail: logData.user?.email || logData.userEmail || null,
remarks: logData.remarks || payload?.remarks || '', remarks: logData.remarks || payload?.remarks || '',

View File

@ -3,6 +3,8 @@ import { Op } from 'sequelize';
import db from '../../database/models/index.js'; import db from '../../database/models/index.js';
const { EorChecklist, EorChecklistItem, OnboardingDocument, RelocationDocument } = db; const { EorChecklist, EorChecklistItem, OnboardingDocument, RelocationDocument } = db;
import { AuthRequest } from '../../types/express.types.js'; import { AuthRequest } from '../../types/express.types.js';
import { NotificationService } from '../../services/NotificationService.js';
import { ROLES } from '../../common/config/constants.js';
/** Default EOR rows for relocation (SRS 12.2.8) — must stay aligned with relocation required-doc labels. */ /** Default EOR rows for relocation (SRS 12.2.8) — must stay aligned with relocation required-doc labels. */
export const RELOCATION_EOR_DEFAULT_ITEMS = [ export const RELOCATION_EOR_DEFAULT_ITEMS = [
@ -338,6 +340,27 @@ export const submitAudit = async (req: AuthRequest, res: Response) => {
const { updateApplicationProgress } = await import('../../common/utils/progress.js'); const { updateApplicationProgress } = await import('../../common/utils/progress.js');
await updateApplicationProgress(checklist.applicationId, 'EOR Complete', 'completed', 100); await updateApplicationProgress(checklist.applicationId, 'EOR Complete', 'completed', 100);
await updateApplicationProgress(checklist.applicationId, 'Inauguration', 'active', 50); await updateApplicationProgress(checklist.applicationId, 'Inauguration', 'active', 50);
// SRS §6.19.3.4 — Readiness alert to DD-Head and NBH on EOR 100% completion
const app = await db.Application.findByPk(checklist.applicationId);
const eorAlertRoles = [ROLES.DD_HEAD, ROLES.NBH, ROLES.DD_ADMIN];
for (const role of eorAlertRoles) {
const roleUsers = await db.User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `EOR Completed: ${app?.applicationId || checklist.applicationId}`,
message: `EOR checklist is 100% complete for ${app?.applicantName || 'the applicant'}. Dealership is ready for inauguration.`,
channels: ['system', 'email'],
templateCode: 'EOR_COMPLETED',
placeholders: {
applicantName: app?.applicantName || '',
applicationId: app?.applicationId || '',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${checklist.applicationId}`,
ctaLabel: 'View Application'
}
}).catch((e: any) => console.error('[EOR] Completion notify failed:', e));
}
}
} else if (checklist.relocationId) { } else if (checklist.relocationId) {
await db.RelocationRequest.update({ await db.RelocationRequest.update({
status: 'Completed', status: 'Completed',
@ -345,7 +368,22 @@ export const submitAudit = async (req: AuthRequest, res: Response) => {
currentStage: 'Completed' currentStage: 'Completed'
}, { where: { id: checklist.relocationId } }); }, { where: { id: checklist.relocationId } });
// The workflow service can handle timeline/audit but here we just finalized the status // SRS §6.19.3.4 — Relocation EOR complete — notify DD-Admin
const adminUsers = await db.User.findAll({ where: { roleCode: ROLES.DD_ADMIN } });
for (const u of adminUsers) {
NotificationService.notify(u.id, u.email, {
title: `Relocation EOR Completed`,
message: `The EOR checklist for relocation ${checklist.relocationId} has been fully verified.`,
channels: ['system', 'email'],
templateCode: 'EOR_COMPLETED',
placeholders: {
applicantName: '',
applicationId: checklist.relocationId,
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/relocation-requests/${checklist.relocationId}`,
ctaLabel: 'View Request'
}
}).catch((e: any) => console.error('[EOR] Relocation notify failed:', e));
}
} }
} }
} }

View File

@ -3,9 +3,10 @@ import { Op } from 'sequelize';
import db from '../../database/models/index.js'; import db from '../../database/models/index.js';
const { FddAssignment, FddReport, Application } = db; const { FddAssignment, FddReport, Application } = db;
import { AuthRequest } from '../../types/express.types.js'; import { AuthRequest } from '../../types/express.types.js';
import { AUDIT_ACTIONS, APPLICATION_STATUS, APPLICATION_STAGES } from '../../common/config/constants.js'; import { AUDIT_ACTIONS, APPLICATION_STATUS, APPLICATION_STAGES, ROLES } from '../../common/config/constants.js';
import { WorkflowService } from '../../services/WorkflowService.js'; import { WorkflowService } from '../../services/WorkflowService.js';
import { pickApplicationAuditContext, safeAuditLogCreate } from '../../services/applicationAuditLog.service.js'; import { pickApplicationAuditContext, safeAuditLogCreate } from '../../services/applicationAuditLog.service.js';
import { NotificationService } from '../../services/NotificationService.js';
export const getAssignment = async (req: Request, res: Response) => { export const getAssignment = async (req: Request, res: Response) => {
try { try {
@ -88,6 +89,25 @@ export const assignAgency = async (req: AuthRequest, res: Response) => {
}, },
}); });
// SRS §6.15.3.1 — Notify assigned FDD agency user of their assignment
const fddUser = await db.User.findByPk(assignedToAgency);
if (fddUser) {
const phone = (fddUser as any).mobileNumber || null;
NotificationService.notify(fddUser.id, fddUser.email, {
title: `FDD Assignment: ${application.applicationId}`,
message: `You have been assigned to conduct Financial Due Diligence for application ${application.applicationId}.`,
channels: phone ? ['system', 'email', 'whatsapp'] : ['system', 'email'],
templateCode: 'USER_ASSIGNED',
placeholders: {
applicantName: application.applicantName || '',
applicationId: application.applicationId,
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${application.id}`,
ctaLabel: 'View Assignment',
phone: phone || ''
}
}).catch((e: any) => console.error('[FDD] Agency notify failed:', e));
}
res.status(201).json({ success: true, message: 'FDD Agency assigned', data: assignment }); res.status(201).json({ success: true, message: 'FDD Agency assigned', data: assignment });
} catch (error) { } catch (error) {
console.error('Assign FDD agency error:', error); console.error('Assign FDD agency error:', error);
@ -158,6 +178,27 @@ export const uploadReport = async (req: AuthRequest, res: Response) => {
reason: 'FDD Report uploaded. Pending review to proceed to LOI stage.', reason: 'FDD Report uploaded. Pending review to proceed to LOI stage.',
forceLog: true // Log even if status is same forceLog: true // Log even if status is same
}); });
// SRS §6.15.3.1 — Notify Finance + DD-Admin that FDD report is submitted
const fddReportRoles = [ROLES.FINANCE, ROLES.DD_ADMIN];
for (const role of fddReportRoles) {
const roleUsers = await db.User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `FDD Report Submitted: ${application.applicationId}`,
message: `The FDD agency has submitted their financial due diligence report for ${application.applicationId}. Review is required before LOI stage.`,
channels: ['system', 'email'],
templateCode: 'WORKFLOW_ACTION_REQUIRED',
placeholders: {
dealerName: application.applicantName || '',
requestId: application.applicationId,
targetStage: 'FDD Review',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${application.id}`,
phone: ''
}
}).catch((e: any) => console.error('[FDD] Finance/Admin notify failed:', e));
}
}
} }
} }

View File

@ -2,8 +2,9 @@ import { Request, Response } from 'express';
import db from '../../database/models/index.js'; import db from '../../database/models/index.js';
const { LoaRequest, LoaApproval, LoaDocumentGenerated, SecurityDeposit, AuditLog, StageApprovalPolicy, StageApprovalAction, User } = db; const { LoaRequest, LoaApproval, LoaDocumentGenerated, SecurityDeposit, AuditLog, StageApprovalPolicy, StageApprovalAction, User } = db;
import { AuthRequest } from '../../types/express.types.js'; import { AuthRequest } from '../../types/express.types.js';
import { AUDIT_ACTIONS, APPLICATION_STATUS, APPLICATION_STAGES } from '../../common/config/constants.js'; import { AUDIT_ACTIONS, APPLICATION_STATUS, APPLICATION_STAGES, ROLES } from '../../common/config/constants.js';
import { WorkflowService } from '../../services/WorkflowService.js'; import { WorkflowService } from '../../services/WorkflowService.js';
import { NotificationService } from '../../services/NotificationService.js';
const LOA_STAGE_CODE = 'LOA_APPROVAL'; const LOA_STAGE_CODE = 'LOA_APPROVAL';
@ -86,6 +87,25 @@ export const createRequest = async (req: AuthRequest, res: Response) => {
progressPercentage: 92 progressPercentage: 92
}); });
// SRS §6.18.3.1 — Notify DD-Head that LOA needs their approval
const ddHeadUsers = await User.findAll({ where: { roleCode: ROLES.DD_HEAD } });
for (const ddHead of ddHeadUsers) {
const phone = (ddHead as any).mobileNumber || null;
NotificationService.notify(ddHead.id, ddHead.email, {
title: `Action Required: LOA Approval for ${application.applicationId}`,
message: `LOA request has been initiated for ${application.applicationId}. Your approval is required.`,
channels: phone ? ['system', 'email', 'whatsapp'] : ['system', 'email'],
templateCode: 'WORKFLOW_ACTION_REQUIRED',
placeholders: {
dealerName: application.applicantName || application.applicationId,
requestId: application.applicationId,
targetStage: 'LOA Approval',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${application.id}`,
phone: phone || ''
}
}).catch((e: any) => console.error('[LOA] DD-Head notify failed:', e));
}
res.status(201).json({ success: true, message: 'LOA Request initiated with DD Head approval', data: request }); res.status(201).json({ success: true, message: 'LOA Request initiated with DD Head approval', data: request });
} catch (error) { } catch (error) {
console.error('Create LOA request error:', error); console.error('Create LOA request error:', error);
@ -207,6 +227,28 @@ export const approveRequest = async (req: AuthRequest, res: Response) => {
progressPercentage: 97 progressPercentage: 97
}); });
} }
// SRS §6.18.3.1 — LOA issued: notify all relevant teams (System + Email)
const app = await db.Application.findByPk(request.applicationId);
const loaTeamRoles = [ROLES.DD_ADMIN, ROLES.FINANCE, ROLES.LEGAL_ADMIN, ROLES.DD_HEAD, ROLES.NBH];
for (const role of loaTeamRoles) {
const roleUsers = await User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `LOA Issued: ${app?.applicationId || request.applicationId}`,
message: `Letter of Appointment fully approved and issued for ${app?.applicantName || 'the applicant'}. EOR process may now begin.`,
channels: ['system', 'email'],
templateCode: 'LOA_ISSUED',
placeholders: {
applicantName: app?.applicantName || '',
applicationId: app?.applicationId || '',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${request.applicationId}`,
ctaLabel: 'View Application'
}
}).catch((e: any) => console.error('[LOA] team notify failed:', e));
}
}
res.json({ success: true, message: 'LOA fully approved and issued' }); res.json({ success: true, message: 'LOA fully approved and issued' });
} else { } else {
// SEQUENTIAL APPROVAL BRIDGE: // SEQUENTIAL APPROVAL BRIDGE:
@ -225,6 +267,27 @@ export const approveRequest = async (req: AuthRequest, res: Response) => {
} }
}); });
console.log(`[LOA] Generated sequential approval record for Level ${nextLevel}: ${nextRole}`); console.log(`[LOA] Generated sequential approval record for Level ${nextLevel}: ${nextRole}`);
// SRS §6.18.3.1 — Sequential: DD-Head approved → notify NBH
if (req.user.roleCode === ROLES.DD_HEAD) {
const nbhUsers = await User.findAll({ where: { roleCode: ROLES.NBH } });
for (const nbh of nbhUsers) {
const phone = (nbh as any).mobileNumber || null;
NotificationService.notify(nbh.id, nbh.email, {
title: `Action Required: LOA Final Approval`,
message: `DD Head has approved LOA request ${requestId}. Your final sign-off is required.`,
channels: phone ? ['system', 'email', 'whatsapp'] : ['system', 'email'],
templateCode: 'WORKFLOW_ACTION_REQUIRED',
placeholders: {
dealerName: '',
requestId,
targetStage: 'NBH LOA Approval',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${request.applicationId}`,
phone: phone || ''
}
}).catch((e: any) => console.error('[LOA] NBH notify failed:', e));
}
}
} }
res.json({ res.json({

View File

@ -2,8 +2,10 @@ import { Request, Response } from 'express';
import db from '../../database/models/index.js'; import db from '../../database/models/index.js';
const { LoiRequest, LoiApproval, LoiDocumentGenerated, LoiAcknowledgement, AuditLog, StageApprovalPolicy, StageApprovalAction, User } = db; const { LoiRequest, LoiApproval, LoiDocumentGenerated, LoiAcknowledgement, AuditLog, StageApprovalPolicy, StageApprovalAction, User } = db;
import { AuthRequest } from '../../types/express.types.js'; import { AuthRequest } from '../../types/express.types.js';
import { AUDIT_ACTIONS, APPLICATION_STATUS } from '../../common/config/constants.js'; import { AUDIT_ACTIONS, APPLICATION_STATUS, ROLES } from '../../common/config/constants.js';
import { WorkflowService } from '../../services/WorkflowService.js'; import { WorkflowService } from '../../services/WorkflowService.js';
import { NotificationService } from '../../services/NotificationService.js';
import { sendEmail } from '../../common/utils/email.service.js';
const LOI_STAGE_CODE = 'LOI_APPROVAL'; const LOI_STAGE_CODE = 'LOI_APPROVAL';
@ -125,6 +127,25 @@ export const createRequest = async (req: AuthRequest, res: Response) => {
progressPercentage: 75 progressPercentage: 75
}); });
// SRS §6.16.3.5 — Notify DD-Head that LOI needs their approval (System + Email + WhatsApp)
const ddHeadUsers = await User.findAll({ where: { roleCode: ROLES.DD_HEAD } });
for (const ddHead of ddHeadUsers) {
const phone = (ddHead as any).mobileNumber || null;
NotificationService.notify(ddHead.id, ddHead.email, {
title: `Action Required: LOI Approval for ${application.applicationId}`,
message: `LOI request initiated for application ${application.applicationId}. Your approval is required.`,
channels: phone ? ['system', 'email', 'whatsapp'] : ['system', 'email'],
templateCode: 'WORKFLOW_ACTION_REQUIRED',
placeholders: {
dealerName: application.applicantName || application.applicationId,
requestId: application.applicationId,
targetStage: 'LOI Approval',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${application.id}`,
phone: phone || ''
}
}).catch((e: any) => console.error('[LOI] DD-Head notify failed:', e));
}
res.status(201).json({ success: true, message: 'LOI Request initiated for DD Head approval', data: request }); res.status(201).json({ success: true, message: 'LOI Request initiated for DD Head approval', data: request });
} catch (error) { } catch (error) {
console.error('Create LOI request error:', error); console.error('Create LOI request error:', error);
@ -259,8 +280,48 @@ export const approveRequest = async (req: AuthRequest, res: Response) => {
}); });
} }
// SRS §6.16.3.5 — Notify Finance + DD-Admin that LOI is fully approved
const notifyRoles = [ROLES.FINANCE, ROLES.DD_ADMIN];
const application2 = await db.Application.findByPk(request.applicationId);
for (const role of notifyRoles) {
const roleUsers = await User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `LOI Fully Approved: ${application2?.applicationId || request.applicationId}`,
message: `LOI request has been approved by all required stakeholders and is ready to issue.`,
channels: ['system', 'email'],
templateCode: 'ONBOARDING_STATUS_UPDATE',
placeholders: {
dealerName: application2?.applicantName || '',
requestId: application2?.applicationId || '',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${request.applicationId}`,
ctaLabel: 'View Application'
}
}).catch((e: any) => console.error('[LOI] finance/admin notify failed:', e));
}
}
res.json({ success: true, message: 'LOI Request fully approved and document generated' }); res.json({ success: true, message: 'LOI Request fully approved and document generated' });
} else { } else {
// SRS §6.16.3.5 — Sequential: DD-Head approved → now notify NBH
if (action === 'Approved' && req.user.roleCode === ROLES.DD_HEAD) {
const nbhUsers = await User.findAll({ where: { roleCode: ROLES.NBH } });
for (const nbh of nbhUsers) {
const phone = (nbh as any).mobileNumber || null;
NotificationService.notify(nbh.id, nbh.email, {
title: `Action Required: LOI Final Approval`,
message: `DD Head has approved the LOI for ${request.applicationId}. Your final sign-off is required.`,
channels: phone ? ['system', 'email', 'whatsapp'] : ['system', 'email'],
templateCode: 'WORKFLOW_ACTION_REQUIRED',
placeholders: {
dealerName: '',
requestId: String(request.applicationId),
targetStage: 'NBH LOI Approval',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${request.applicationId}`,
phone: phone || ''
}
}).catch((e: any) => console.error('[LOI] NBH notify failed:', e));
}
}
res.json({ res.json({
success: true, success: true,
message: 'Approval recorded. Waiting for remaining required approvers.', message: 'Approval recorded. Waiting for remaining required approvers.',
@ -359,6 +420,41 @@ export const generateDocument = async (req: AuthRequest, res: Response) => {
reason: 'LOI Document issued. Proceeding to Dealer Code Generation.', reason: 'LOI Document issued. Proceeding to Dealer Code Generation.',
progressPercentage: 85 progressPercentage: 85
}); });
// SRS §6.16.3.6 — LOI issued: email ONLY to applicant (explicitly NO WhatsApp per SRS)
if (application.email) {
sendEmail(
application.email,
`Letter of Intent Issued: ${application.applicationId}`,
'LOI_ISSUED',
{
applicantName: application.applicantName || 'Applicant',
applicationId: application.applicationId,
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/prospect-login`,
ctaLabel: 'View Your Application'
}
).catch((e: any) => console.error('[LOI] Applicant email failed:', e));
}
// SRS §6.16.3.6 — Alert Finance, DD-Head, NBH confirming LOI issuance (System + Email)
const stakeholderRoles = [ROLES.FINANCE, ROLES.DD_HEAD, ROLES.NBH];
for (const role of stakeholderRoles) {
const roleUsers = await User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `LOI Issued: ${application.applicationId}`,
message: `Letter of Intent has been issued for ${application.applicantName || application.applicationId}. Dealer code generation is now pending.`,
channels: ['system', 'email'],
templateCode: 'LOI_ISSUED',
placeholders: {
applicantName: application.applicantName || '',
applicationId: application.applicationId,
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/applications/${application.id}`,
ctaLabel: 'View Application'
}
}).catch((e: any) => console.error('[LOI] stakeholder notify failed:', e));
}
}
} }
} }

View File

@ -13,6 +13,7 @@ import { WorkflowIntegrityService } from '../../services/WorkflowIntegrityServic
import { NomenclatureService } from '../../common/utils/nomenclature.js'; import { NomenclatureService } from '../../common/utils/nomenclature.js';
import { pickApplicationAuditContext, safeAuditLogCreate } from '../../services/applicationAuditLog.service.js'; import { pickApplicationAuditContext, safeAuditLogCreate } from '../../services/applicationAuditLog.service.js';
import { isAutoAssignmentEnabled } from '../../services/AutoAssignmentConfigService.js'; import { isAutoAssignmentEnabled } from '../../services/AutoAssignmentConfigService.js';
import { NotificationService } from '../../services/NotificationService.js';
const { DocumentStageConfig } = db; const { DocumentStageConfig } = db;
@ -195,6 +196,27 @@ export const submitApplication = async (req: AuthRequest, res: Response) => {
entityId: application.id entityId: application.id
}); });
// SRS §6.1.3 — WhatsApp acknowledgement to applicant on submission (alongside email)
// The email is handled above; now send WhatsApp if phone is available
if (phone) {
NotificationService.notify(null, email, {
title: isOpportunityAvailable
? `Your Royal Enfield Dealership Application: ${applicationId}`
: `We received your interest: ${applicationId}`,
message: isOpportunityAvailable
? `Hi ${displayApplicantName}, your application for ${displayLocation} has been received. We will contact you soon.`
: `Hi ${displayApplicantName}, we have noted your interest for ${displayLocation}. We'll reach out when an opportunity arises.`,
channels: ['whatsapp'],
templateCode: isOpportunityAvailable ? 'OPPORTUNITY' : 'NON_OPPORTUNITY',
placeholders: {
applicantName: displayApplicantName,
location: displayLocation,
applicationId,
phone
}
}).catch((err: any) => console.error('[Onboarding] WhatsApp ack failed:', err));
}
res.status(201).json({ res.status(201).json({
success: true, success: true,
message: 'Application submitted successfully', message: 'Application submitted successfully',

View File

@ -1,4 +1,4 @@
import { Response, NextFunction } from 'express'; import { Response, NextFunction } from 'express'; // Triggering reload to pick up constants changes
import db from '../../database/models/index.js'; import db from '../../database/models/index.js';
import logger from '../../common/utils/logger.js'; import logger from '../../common/utils/logger.js';
import { import {
@ -17,7 +17,7 @@ import ExternalMocksService from '../../common/utils/externalMocks.service.js';
import { ResignationWorkflowService } from '../../services/ResignationWorkflowService.js'; import { ResignationWorkflowService } from '../../services/ResignationWorkflowService.js';
import { NomenclatureService } from '../../common/utils/nomenclature.js'; import { NomenclatureService } from '../../common/utils/nomenclature.js';
import { ParticipantService } from '../../services/ParticipantService.js'; import { ParticipantService } from '../../services/ParticipantService.js';
import { notifyResignationSubmittedEmails } from '../../common/utils/workflow-email-notifications.js'; import { notifyResignationSubmittedEmails, notifyStakeholdersOnTransition } from '../../common/utils/workflow-email-notifications.js';
import { getResignationStatusForStage, normalizeClearanceStatus } from '../../common/utils/offboardingStatus.js'; import { getResignationStatusForStage, normalizeClearanceStatus } from '../../common/utils/offboardingStatus.js';
import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js'; import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js';
import { OFFBOARDING_ACTIONS } from '../../common/config/constants.js'; import { OFFBOARDING_ACTIONS } from '../../common/config/constants.js';
@ -309,6 +309,30 @@ export const uploadResignationDocument = async (req: AuthRequest, res: Response,
await resignation.update({ timeline }, { transaction }); await resignation.update({ timeline }, { transaction });
await transaction.commit(); await transaction.commit();
// SRS §7.5.2 — When Legal uploads the acceptance letter, notify DD-Admin and ASM
// so they can communicate official closure to the dealer (field hierarchy).
if (stage === RESIGNATION_STAGES.LEGAL && resignation.currentStage === RESIGNATION_STAGES.LEGAL) {
const portalBase = process.env.FRONTEND_URL || 'http://localhost:5173';
const resignationCode = resignation.resignationId || resignation.id;
setImmediate(() =>
notifyStakeholdersOnTransition(
resignation.id,
REQUEST_TYPES.RESIGNATION,
'Resignation Legal Closure', // synthetic stage key mapped to DD_ADMIN + ASM in resolveNextActors
{
code: resignationCode,
dealerName: 'Dealer', // enriched below if needed
dealerId: resignation.dealerId,
actionUserFullName: req.user!.fullName || 'Legal Team',
action: 'Legal acceptance letter uploaded — ready for DD-Admin review and ASM communication',
remarks: `Document: ${req.file!.originalname}`,
link: `${portalBase}/dealer-resignation/${resignation.id}`
}
).catch((err: any) => logger.error('[uploadResignationDocument] legal-closure notify:', err))
);
}
res.status(201).json({ success: true, message: 'Document uploaded successfully', document }); res.status(201).json({ success: true, message: 'Document uploaded successfully', document });
} catch (error) { } catch (error) {
await transaction.rollback(); await transaction.rollback();
@ -354,11 +378,9 @@ export const approveResignation = async (req: AuthRequest, res: Response, next:
[RESIGNATION_STAGES.RBM]: RESIGNATION_STAGES.ZBH, [RESIGNATION_STAGES.RBM]: RESIGNATION_STAGES.ZBH,
[RESIGNATION_STAGES.ZBH]: RESIGNATION_STAGES.DD_LEAD, [RESIGNATION_STAGES.ZBH]: RESIGNATION_STAGES.DD_LEAD,
[RESIGNATION_STAGES.DD_LEAD]: RESIGNATION_STAGES.NBH, [RESIGNATION_STAGES.DD_LEAD]: RESIGNATION_STAGES.NBH,
[RESIGNATION_STAGES.NBH]: RESIGNATION_STAGES.DD_ADMIN, [RESIGNATION_STAGES.NBH]: RESIGNATION_STAGES.LEGAL,
[RESIGNATION_STAGES.DD_ADMIN]: RESIGNATION_STAGES.LEGAL, [RESIGNATION_STAGES.LEGAL]: RESIGNATION_STAGES.DD_ADMIN,
// Legal approval should complete only the Legal stage. [RESIGNATION_STAGES.DD_ADMIN]: RESIGNATION_STAGES.FNF_INITIATED, // DD Admin approval moves to F&F initiation
// F&F initiation is explicitly triggered via `pushfnf` action (with LWD/force gates).
[RESIGNATION_STAGES.LEGAL]: RESIGNATION_STAGES.LEGAL,
[RESIGNATION_STAGES.FNF_INITIATED]: RESIGNATION_STAGES.COMPLETED [RESIGNATION_STAGES.FNF_INITIATED]: RESIGNATION_STAGES.COMPLETED
}; };

View File

@ -10,6 +10,9 @@ import { safeAuditLogCreate } from '../../services/applicationAuditLog.service.j
import { writeWorkflowActivityWorknote } from '../../common/utils/workflowWorknote.js'; import { writeWorkflowActivityWorknote } from '../../common/utils/workflowWorknote.js';
import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js'; import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js';
import { NomenclatureService } from '../../common/utils/nomenclature.js'; import { NomenclatureService } from '../../common/utils/nomenclature.js';
import { NotificationService } from '../../services/NotificationService.js';
const portalBase = process.env.FRONTEND_URL || 'http://localhost:5173';
const LINE_ITEM_DESCRIPTION_PREFIX = { const LINE_ITEM_DESCRIPTION_PREFIX = {
DEPARTMENT_CLAIM: '[DEPARTMENT_CLAIM]', DEPARTMENT_CLAIM: '[DEPARTMENT_CLAIM]',
@ -202,6 +205,31 @@ export const updatePayment = async (req: AuthRequest, res: Response) => {
}, },
}); });
// SRS §11.1.3.1 — Notify DD-Admin and DD-Lead when payment is verified
if (isVerifying && status === 'Paid') {
const notifyRoles = [ROLES.DD_ADMIN, ROLES.DD_LEAD];
for (const role of notifyRoles) {
const roleUsers = await User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `Payment Verified: ${p.application?.applicationId || 'New Dealer'}`,
message: `Finance has verified the ${p.paymentType || 'Security Deposit'} for ${p.application?.applicantName || 'Dealer'}.`,
channels: ['system', 'email'],
templateCode: 'ONBOARDING_PAYMENT_VERIFIED',
placeholders: {
applicationId: p.application?.applicationId || 'N/A',
dealerName: p.application?.applicantName || 'Dealer',
paymentType: p.paymentType || 'Security Deposit',
amount: p.amount,
link: `${portalBase}/applications/${p.applicationId}`
}
}).catch((e: any) => console.error('[Finance] Payment verification notify failed:', e));
}
}
}
res.json({ success: true, message: 'Payment updated successfully', data: updatedPayment }); res.json({ success: true, message: 'Payment updated successfully', data: updatedPayment });
} catch (error) { } catch (error) {
console.error('Update payment error:', error); console.error('Update payment error:', error);
@ -258,6 +286,48 @@ export const updateFnF = async (req: AuthRequest, res: Response) => {
}); });
} }
} }
// SRS §4.4.2.7 — F&F Completed: final alerts to DD-Lead, NBH, Legal
const completionRoles = [ROLES.DD_LEAD, ROLES.NBH, ROLES.LEGAL_ADMIN, ROLES.DD_ADMIN];
for (const role of completionRoles) {
const roleUsers = await User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `F&F Settlement Completed: ${fnf.fnfId || id}`,
message: `Full & Final Settlement has been completed and closed. All departmental clearances confirmed.`,
channels: ['system', 'email'],
templateCode: 'FNF_SETTLEMENT_APPROVED',
placeholders: {
fnfId: fnf.fnfId || id,
dealerName: 'Dealer', // Can be refined if dealer info is fetched
settlementAmount: fnf.settlementAmount || fnf.netAmount,
link: `${portalBase}/fnf/${id}`
}
}).catch((e: any) => console.error('[FnF] Completion notify failed:', e));
}
}
}
// SRS §4.4.2.6 — Finance approval reached: notify DD-Admin + Legal
if (normalizedStatus === FNF_STATUS.FINANCE_APPROVAL) {
const financeApprovalRoles = [ROLES.DD_ADMIN, ROLES.LEGAL_ADMIN];
for (const role of financeApprovalRoles) {
const roleUsers = await User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `F&F Finance Approval Stage: ${fnf.fnfId || id}`,
message: `All departments have submitted their clearances. F&F is now pending Finance approval.`,
channels: ['system', 'email'],
templateCode: 'FNF_INITIATED',
placeholders: {
dealerName: '',
fnfId: fnf.fnfId || id,
link: `${portalBase}/fnf/${id}`,
ctaLabel: 'Review Settlement'
}
}).catch((e: any) => console.error('[FnF] Finance approval notify failed:', e));
}
}
} }
res.json({ success: true, message: 'F&F settlement updated successfully', data: fnf }); res.json({ success: true, message: 'F&F settlement updated successfully', data: fnf });

View File

@ -20,6 +20,8 @@ import { getTerminationStatusForStage, normalizeClearanceStatus } from '../../co
import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js'; import { resolveEntityUuidByType } from '../../common/utils/requestResolver.js';
import { OFFBOARDING_ACTIONS, REQUEST_TYPES } from '../../common/config/constants.js'; import { OFFBOARDING_ACTIONS, REQUEST_TYPES } from '../../common/config/constants.js';
import { validateOffboardingAction, getPreviousStage } from '../../common/utils/offboardingWorkflow.utils.js'; import { validateOffboardingAction, getPreviousStage } from '../../common/utils/offboardingWorkflow.utils.js';
import { NotificationService } from '../../services/NotificationService.js';
import { sendEmail } from '../../common/utils/email.service.js';
const resolveTerminationUuid = async (id: string) => { const resolveTerminationUuid = async (id: string) => {
const { resolvedId } = await resolveEntityUuidByType(db as any, id, 'termination'); const { resolvedId } = await resolveEntityUuidByType(db as any, id, 'termination');
@ -68,6 +70,29 @@ export const createTermination = async (req: AuthRequest, res: Response, next: N
ParticipantService.assignTerminationParticipants(termination.id) ParticipantService.assignTerminationParticipants(termination.id)
.catch(err => logger.error('Error assigning participants to termination:', err)); .catch(err => logger.error('Error assigning participants to termination:', err));
// SRS §4.3.2.1 — Notify RBM + DD-ZM that a new termination has been initiated
const notifyOnCreateRoles = [ROLES.RBM, ROLES.DD_ZM];
for (const role of notifyOnCreateRoles) {
const roleUsers = await db.User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
const phone = (u as any).mobileNumber || null;
NotificationService.notify(u.id, u.email, {
title: `New Termination Request: ${termination.requestId}`,
message: `A termination request has been initiated by ${req.user!.fullName || 'Admin'}. Your review is required.`,
channels: phone ? ['system', 'email', 'whatsapp'] : ['system', 'email'],
templateCode: 'TERMINATION_INITIATED',
placeholders: {
dealerName: '',
requestId: termination.requestId,
reason: reason || '',
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/termination/${termination.id}`,
ctaLabel: 'Review Request',
phone: phone || ''
}
}).catch((e: any) => logger.error('[Termination] Create notify failed:', e));
}
}
res.status(201).json({ success: true, message: 'Termination request created', termination }); res.status(201).json({ success: true, message: 'Termination request created', termination });
} catch (error) { } catch (error) {
if (transaction) await transaction.rollback(); if (transaction) await transaction.rollback();
@ -257,11 +282,11 @@ export const uploadTerminationDocument = async (req: AuthRequest, res: Response,
}, { transaction }); }, { transaction });
const timeline = [...(termination.timeline || []), { const timeline = [...(termination.timeline || []), {
stage: termination.currentStage, stage: stage || termination.currentStage,
timestamp: new Date(), timestamp: new Date(),
user: req.user.fullName, user: req.user.fullName,
action: `Document uploaded: ${documentType}`, action: `Document uploaded: ${documentType}`,
remarks: req.file.originalname remarks: `Attachment: ${req.file.originalname}`
}]; }];
await termination.update({ timeline }, { transaction }); await termination.update({ timeline }, { transaction });
@ -384,18 +409,86 @@ export const updateTerminationStatus = async (req: AuthRequest, res: Response, n
[TERMINATION_STAGES.LEGAL_LETTER]: TERMINATION_STAGES.TERMINATED [TERMINATION_STAGES.LEGAL_LETTER]: TERMINATION_STAGES.TERMINATED
}; };
const nextStage = stageFlow[termination.currentStage]; const sourceStage = termination.currentStage;
logger.info(`[TerminationController] transitioning from ${termination.currentStage} to ${nextStage}`); const nextStage = stageFlow[sourceStage];
logger.info(`[TerminationController] attempting transition from ${sourceStage} to ${nextStage}`);
if (!nextStage) { if (!nextStage) {
await transaction.rollback(); await transaction.rollback();
return res.status(400).json({ success: false, message: 'Cannot approve from current stage' }); return res.status(400).json({ success: false, message: 'Cannot approve from current stage' });
} }
// SRS §4.3.2.2 — JOINT APPROVAL LOGIC FOR RBM STAGE
if (sourceStage === TERMINATION_STAGES.RBM_REVIEW && req.user.roleCode !== ROLES.SUPER_ADMIN) {
// Prevent duplicate approval from same user
const existingUserApproval = await db.TerminationAudit.findOne({
where: {
terminationRequestId: termination.id,
userId: req.user.id,
action: 'PARTIAL_APPROVE',
'details.stage': sourceStage
},
transaction
});
if (existingUserApproval) {
await transaction.rollback();
return res.status(400).json({ success: false, message: 'You have already recorded your approval for this stage.' });
}
// 1. Record this partial approval in Audit Logs
await db.TerminationAudit.create({
userId: req.user.id,
terminationRequestId: termination.id,
action: 'PARTIAL_APPROVE',
remarks: `Partial approval by ${req.user.roleCode}${remarks ? ': ' + remarks : ''}`,
details: { roleCode: req.user.roleCode, stage: sourceStage }
}, { transaction });
// 2. Check for both RBM and DD_ZM approvals in this stage
const requiredRoles = [ROLES.RBM, ROLES.DD_ZM];
const partialLogs = await db.TerminationAudit.findAll({
where: {
terminationRequestId: termination.id,
action: 'PARTIAL_APPROVE',
'details.stage': sourceStage
},
transaction
});
const approvedRoles = partialLogs.map(log => (log as any).details?.roleCode);
const isComplete = requiredRoles.every(role => approvedRoles.includes(role));
if (!isComplete) {
// Record partial approval in timeline ONLY if not complete yet
// (The final approver's entry will be handled by transitionTermination)
const partialTimeline = [...(termination.timeline || []), {
stage: sourceStage,
timestamp: new Date(),
user: req.user.fullName,
action: 'Partial Approved',
remarks: remarks || `Partial approval recorded by ${req.user.roleCode}`
}];
await termination.update({ timeline: partialTimeline }, { transaction });
await transaction.commit();
return res.json({
success: true,
message: `Partial approval recorded. Waiting for ${requiredRoles.find(r => !approvedRoles.includes(r))} approval to proceed to ZBH Review.`,
isPartial: true
});
}
logger.info(`[TerminationController] Joint approval complete for ${termination.requestId}. Moving to ${nextStage}.`);
}
approvedToStage = nextStage; approvedToStage = nextStage;
await TerminationWorkflowService.transitionTermination(termination, nextStage, req.user.id, { await TerminationWorkflowService.transitionTermination(termination, nextStage, req.user.id, {
remarks, remarks: remarks || `Jointly approved by RBM & DD-ZM`,
status: getTerminationStatusForStage(nextStage) status: getTerminationStatusForStage(nextStage),
transaction
}); });
// If Terminated, trigger F&F initiation via Workflow Service // If Terminated, trigger F&F initiation via Workflow Service
@ -472,6 +565,45 @@ export const issueScn = async (req: AuthRequest, res: Response, next: NextFuncti
status: 'Show Cause Notice', status: 'Show Cause Notice',
remarks: remarks || 'Show Cause Notice issued' remarks: remarks || 'Show Cause Notice issued'
}); });
// SRS §4.3.2.8 — SCN issued: send official email to dealer (no WhatsApp)
const dealer = await db.Dealer.findByPk(termination.dealerId, {
include: [{ model: db.User, as: 'user', attributes: ['email', 'mobileNumber', 'fullName'] }]
});
const dealerUser = (dealer as any)?.user;
if (dealerUser?.email) {
sendEmail(
dealerUser.email,
`Show Cause Notice: ${termination.requestId}`,
'TERMINATION_SCN_ISSUED',
{
dealerName: dealerUser.fullName || 'Dealer',
requestId: termination.requestId,
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/dealer-termination/${termination.id}`,
ctaLabel: 'View Notice'
}
).catch((e: any) => logger.error('[Termination] SCN email to dealer failed:', e));
}
// Notify DD-Admin + Legal of SCN issuance
const scnAlertRoles = [ROLES.DD_ADMIN, ROLES.LEGAL_ADMIN];
for (const role of scnAlertRoles) {
const roleUsers = await db.User.findAll({ where: { roleCode: role } });
for (const u of roleUsers) {
NotificationService.notify(u.id, u.email, {
title: `SCN Issued: ${termination.requestId}`,
message: `Show Cause Notice has been issued for termination case ${termination.requestId}.`,
channels: ['system', 'email'],
templateCode: 'TERMINATION_SCN_ISSUED',
placeholders: {
dealerName: dealerUser?.fullName || '',
requestId: termination.requestId,
link: `${process.env.FRONTEND_URL || 'http://localhost:5173'}/termination/${termination.id}`,
ctaLabel: 'View Case'
}
}).catch((e: any) => logger.error('[Termination] SCN admin/legal notify failed:', e));
}
}
} }
await transaction.commit(); await transaction.commit();

View File

@ -14,13 +14,16 @@ const seedInterviewTemplates = async () => {
<h2>Dear {{applicantName}},</h2> <h2>Dear {{applicantName}},</h2>
<p>Your <strong>{{type}}</strong> for Royal Enfield Dealership Application ({{applicationId}}) has been scheduled.</p> <p>Your <strong>{{type}}</strong> for Royal Enfield Dealership Application ({{applicationId}}) has been scheduled.</p>
<p><strong>Scheduled Time:</strong> {{scheduledAt}}</p> <p><strong>Scheduled Time:</strong> {{scheduledAt}}</p>
<p><strong>Meeting Link/Location:</strong> {{link}}</p> <p><strong>Meeting Link/Location:</strong> {{meetLink}}</p>
<p>Please ensure you are available at the scheduled time.</p> <p>Please ensure you are available at the scheduled time.</p>
<p><a href="{{link}}">Join Interview / View Details</a></p> <div style="margin: 20px 0;">
<a href="{{meetLink}}" style="background: #c8102e; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;">Join Meeting</a>
<a href="{{appLink}}" style="background: #f4f4f4; color: #333; padding: 10px 20px; text-decoration: none; border-radius: 5px; border: 1px solid #ccc;">View Application</a>
</div>
<p>Best Regards,<br>Royal Enfield Onboarding Team</p> <p>Best Regards,<br>Royal Enfield Onboarding Team</p>
</body></html> </body></html>
`, `,
placeholders: ['applicantName', 'applicationId', 'type', 'scheduledAt', 'link'] placeholders: ['applicantName', 'applicationId', 'type', 'scheduledAt', 'meetLink', 'appLink']
}, },
{ {
templateCode: 'INTERVIEW_SCHEDULED_PANELIST', templateCode: 'INTERVIEW_SCHEDULED_PANELIST',
@ -32,13 +35,84 @@ const seedInterviewTemplates = async () => {
<p>You have been assigned as a panelist for <strong>{{type}}</strong> with <strong>{{applicantName}}</strong>.</p> <p>You have been assigned as a panelist for <strong>{{type}}</strong> with <strong>{{applicantName}}</strong>.</p>
<p><strong>Application ID:</strong> {{applicationId}}</p> <p><strong>Application ID:</strong> {{applicationId}}</p>
<p><strong>Scheduled Time:</strong> {{scheduledAt}}</p> <p><strong>Scheduled Time:</strong> {{scheduledAt}}</p>
<p><strong>Meeting Link/Location:</strong> {{link}}</p> <p><strong>Meeting Link/Location:</strong> {{meetLink}}</p>
<p><a href="{{link}}">Open Assessment Dashboard</a></p> <div style="margin: 20px 0;">
<a href="{{meetLink}}" style="background: #c8102e; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;">Join Meeting</a>
<a href="{{appLink}}" style="background: #f4f4f4; color: #333; padding: 10px 20px; text-decoration: none; border-radius: 5px; border: 1px solid #ccc;">Open Assessment Dashboard</a>
</div>
<p>Please review the applicant's profile before the session.</p> <p>Please review the applicant's profile before the session.</p>
<p>Regards,<br>System Administrator</p> <p>Regards,<br>System Administrator</p>
</body></html> </body></html>
`, `,
placeholders: ['panelistName', 'applicantName', 'applicationId', 'type', 'scheduledAt', 'link'] placeholders: ['panelistName', 'applicantName', 'applicationId', 'type', 'scheduledAt', 'meetLink', 'appLink']
},
{
templateCode: 'INTERVIEW_RESCHEDULED_APPLICANT',
description: 'Notification sent to the applicant when an interview is rescheduled',
subject: 'Interview Rescheduled: {{applicationId}}',
body: `
<html><body>
<h2>Dear {{applicantName}},</h2>
<p>Your <strong>{{type}}</strong> for Royal Enfield Dealership Application ({{applicationId}}) has been <strong>rescheduled</strong>.</p>
<p><strong>New Scheduled Time:</strong> {{scheduledAt}}</p>
<p><strong>Meeting Link/Location:</strong> {{meetLink}}</p>
<p>Please ensure you are available at the new scheduled time.</p>
<div style="margin: 20px 0;">
<a href="{{meetLink}}" style="background: #c8102e; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;">Join Meeting</a>
<a href="{{appLink}}" style="background: #f4f4f4; color: #333; padding: 10px 20px; text-decoration: none; border-radius: 5px; border: 1px solid #ccc;">View Application</a>
</div>
<p>Best Regards,<br>Royal Enfield Onboarding Team</p>
</body></html>
`,
placeholders: ['applicantName', 'applicationId', 'type', 'scheduledAt', 'meetLink', 'appLink']
},
{
templateCode: 'INTERVIEW_RESCHEDULED_PANELIST',
description: 'Notification sent to the panelist when an interview is rescheduled',
subject: 'Interview Rescheduled: {{applicationId}}',
body: `
<html><body>
<h2>Hi {{panelistName}},</h2>
<p>The <strong>{{type}}</strong> for <strong>{{applicantName}}</strong> ({{applicationId}}) has been <strong>rescheduled</strong>.</p>
<p><strong>New Scheduled Time:</strong> {{scheduledAt}}</p>
<p><strong>Meeting Link/Location:</strong> {{meetLink}}</p>
<div style="margin: 20px 0;">
<a href="{{meetLink}}" style="background: #c8102e; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;">Join Meeting</a>
<a href="{{appLink}}" style="background: #f4f4f4; color: #333; padding: 10px 20px; text-decoration: none; border-radius: 5px; border: 1px solid #ccc;">Open Assessment Dashboard</a>
</div>
<p>Please update your calendar accordingly.</p>
<p>Regards,<br>System Administrator</p>
</body></html>
`,
placeholders: ['panelistName', 'applicantName', 'applicationId', 'type', 'scheduledAt', 'meetLink', 'appLink']
},
{
templateCode: 'INTERVIEW_CANCELLED_APPLICANT',
description: 'Notification sent to the applicant when an interview is cancelled',
subject: 'Interview Cancelled: {{applicationId}}',
body: `
<html><body>
<h2>Dear {{applicantName}},</h2>
<p>We inform you that your <strong>{{type}}</strong> for Royal Enfield Dealership Application ({{applicationId}}) has been <strong>cancelled</strong>.</p>
<p>Our team will reach out to you if a new session is required.</p>
<p>Best Regards,<br>Royal Enfield Onboarding Team</p>
</body></html>
`,
placeholders: ['applicantName', 'applicationId', 'type']
},
{
templateCode: 'INTERVIEW_CANCELLED_PANELIST',
description: 'Notification sent to the panelist when an interview is cancelled',
subject: 'Interview Cancelled: {{applicationId}}',
body: `
<html><body>
<h2>Hi {{panelistName}},</h2>
<p>The <strong>{{type}}</strong> for <strong>{{applicantName}}</strong> ({{applicationId}}) has been <strong>cancelled</strong>.</p>
<p>You no longer need to attend this session.</p>
<p>Regards,<br>System Administrator</p>
</body></html>
`,
placeholders: ['panelistName', 'applicantName', 'applicationId', 'type']
}, },
{ {
templateCode: 'WORKFLOW_ACTION_REQUIRED', templateCode: 'WORKFLOW_ACTION_REQUIRED',

View File

@ -87,6 +87,13 @@ const seedTemplates = async () => {
fileName: 'onboarding_status_update.html', fileName: 'onboarding_status_update.html',
placeholders: ['applicantName', 'applicationId', 'status', 'reason', 'salesCode', 'serviceCode'] placeholders: ['applicantName', 'applicationId', 'status', 'reason', 'salesCode', 'serviceCode']
}, },
{
templateCode: 'EOR_COMPLETED',
description: 'Notification when EOR readiness is 100% complete',
subject: 'EOR Readiness 100% Completed: {{applicationId}}',
fileName: 'eor_completed.html',
placeholders: ['applicantName', 'applicationId', 'location']
},
{ {
templateCode: 'RESIGNATION_SUBMITTED', templateCode: 'RESIGNATION_SUBMITTED',
description: 'Notification for new Resignation submission', description: 'Notification for new Resignation submission',
@ -101,12 +108,47 @@ const seedTemplates = async () => {
fileName: 'resignation_approved.html', fileName: 'resignation_approved.html',
placeholders: ['dealerName', 'resignationId', 'lwd'] placeholders: ['dealerName', 'resignationId', 'lwd']
}, },
{
templateCode: 'TERMINATION_INITIATED',
description: 'Notification for new Termination request initiation',
subject: 'Dealer Termination Case Initiated — {{requestId}}',
fileName: 'termination_initiated.html',
placeholders: ['recipientName', 'dealerName', 'requestId', 'category', 'initiatedBy', 'currentStage', 'remarks', 'link', 'ctaLabel']
},
{ {
templateCode: 'TERMINATION_SCN_ISSUED', templateCode: 'TERMINATION_SCN_ISSUED',
description: 'Notification for Show Cause Notice issuance', description: 'Notification for Show Cause Notice issuance',
subject: 'URGENT: Show Cause Notice Issued: {{terminationId}}', subject: 'URGENT: Show Cause Notice Issued: {{terminationId}}',
fileName: 'termination_scn.html', fileName: 'termination_scn.html',
placeholders: ['dealerName', 'terminationId', 'deadline'] placeholders: ['dealerName', 'terminationId', 'deadline', 'link', 'ctaLabel']
},
{
templateCode: 'FNF_INITIATED',
description: 'Notification for F&F Settlement initiation',
subject: 'F&F Settlement Initiated — {{requestId}}',
fileName: 'fnf_initiated.html',
placeholders: ['recipientName', 'dealerName', 'requestId', 'initiatedBy', 'lwd', 'link', 'ctaLabel']
},
{
templateCode: 'FNF_SUMMARY_PREPARED',
description: 'Notification to Finance team when F&F summary is ready for review',
subject: 'F&F Settlement Summary Prepared: {{fnfId}}',
fileName: 'fnf_summary_prepared.html',
placeholders: ['fnfId', 'dealerName', 'netAmount', 'link', 'ctaLabel']
},
{
templateCode: 'FNF_SETTLEMENT_APPROVED',
description: 'Notification when Finance approves the final settlement',
subject: 'F&F Settlement Approved: {{fnfId}}',
fileName: 'fnf_settlement_approved.html',
placeholders: ['fnfId', 'dealerName', 'settlementAmount', 'link', 'ctaLabel']
},
{
templateCode: 'ONBOARDING_PAYMENT_VERIFIED',
description: 'Notification when security deposit or initial payment is verified',
subject: 'Payment Verified: {{applicationId}}',
fileName: 'onboarding_payment_verified.html',
placeholders: ['applicationId', 'dealerName', 'paymentType', 'amount', 'link']
}, },
{ {
templateCode: 'WORKNOTE_NOTIFICATION', templateCode: 'WORKNOTE_NOTIFICATION',
@ -143,6 +185,20 @@ const seedTemplates = async () => {
fileName: 'resignation_update.html', fileName: 'resignation_update.html',
placeholders: ['dealerName', 'status', 'remarks'] placeholders: ['dealerName', 'status', 'remarks']
}, },
{
templateCode: 'TERMINATION_LETTER_ISSUED',
description: 'Internal alert to DD-Lead, Admin, and Finance when termination letter is generated',
subject: 'Termination Letter Generated: {{requestId}}',
fileName: 'termination_letter_issued.html',
placeholders: ['recipientName', 'dealerName', 'requestId', 'link', 'ctaLabel']
},
{
templateCode: 'TERMINATION_FINAL_CLOSURE_DEALER',
description: 'Final closure notification sent to the dealer upon termination completion',
subject: 'Official Notice: Termination of Dealership — {{requestId}}',
fileName: 'termination_final_closure.html',
placeholders: ['dealerName', 'requestId', 'terminationDate', 'link', 'ctaLabel']
},
{ {
templateCode: 'TERMINATION_UPDATE', templateCode: 'TERMINATION_UPDATE',
description: 'General status update for Termination', description: 'General status update for Termination',
@ -150,6 +206,20 @@ const seedTemplates = async () => {
fileName: 'termination_update.html', fileName: 'termination_update.html',
placeholders: ['dealerName', 'status', 'remarks'] placeholders: ['dealerName', 'status', 'remarks']
}, },
{
templateCode: 'INAUGURATION_COMPLETED',
description: 'Notification to relevant teams when a dealership inauguration is logged',
subject: 'Dealership Inauguration Logged: {{applicationId}}',
fileName: 'inauguration_completed.html',
placeholders: ['dealerName', 'applicationId', 'location', 'date']
},
{
templateCode: 'CONSTITUTIONAL_CHANGE_APPROVED',
description: 'Final approval notification for Constitutional Change',
subject: 'Constitutional Change Approved — {{requestId}}',
fileName: 'constitutional_change_approved.html',
placeholders: ['dealerName', 'requestId', 'proposedConstitution', 'link']
},
{ {
templateCode: 'CONSTITUTIONAL_CHANGE_UPDATE', templateCode: 'CONSTITUTIONAL_CHANGE_UPDATE',
description: 'General status update for Constitutional Change', description: 'General status update for Constitutional Change',
@ -178,6 +248,13 @@ const seedTemplates = async () => {
fileName: 'relocation_submitted.html', fileName: 'relocation_submitted.html',
placeholders: ['dealerName', 'requestId', 'outletCode'] placeholders: ['dealerName', 'requestId', 'outletCode']
}, },
{
templateCode: 'RELOCATION_APPROVED',
description: 'Final approval notification for Relocation',
subject: 'Relocation Approved — {{requestId}}',
fileName: 'relocation_approved.html',
placeholders: ['dealerName', 'requestId', 'newLocation', 'link']
},
{ {
templateCode: 'RELOCATION_UPDATE', templateCode: 'RELOCATION_UPDATE',
description: 'Dealer-visible status updates during relocation workflow', description: 'Dealer-visible status updates during relocation workflow',
@ -212,6 +289,20 @@ const seedTemplates = async () => {
subject: 'SLA ESCALATION [L{{level}}]: {{applicationId}} — {{stageName}}', subject: 'SLA ESCALATION [L{{level}}]: {{applicationId}} — {{stageName}}',
fileName: 'sla_escalation.html', fileName: 'sla_escalation.html',
placeholders: ['applicationId', 'stageName', 'level', 'timeValue', 'timeUnit', 'link'] placeholders: ['applicationId', 'stageName', 'level', 'timeValue', 'timeUnit', 'link']
},
{
templateCode: 'WORKFLOW_ACTION_REQUIRED',
description: 'Turn-based notification for next reviewer/actor in any workflow',
subject: 'Action Required: {{requestId}} — {{targetStage}}',
fileName: 'workflow_action_required.html',
placeholders: ['requestId', 'dealerName', 'targetStage', 'remarks', 'link', 'ctaLabel']
},
{
templateCode: 'WORKFLOW_STATUS_UPDATE_DEALER',
description: 'Status update notification sent to dealer for interim workflow stages',
subject: 'Update on Your Request — {{requestId}}',
fileName: 'workflow_status_update_dealer.html',
placeholders: ['dealerName', 'requestId', 'targetStage', 'remarks', 'link', 'ctaLabel']
} }
]; ];

View File

@ -131,9 +131,9 @@ export class ResignationWorkflowService {
[RESIGNATION_STAGES.RBM]: 30, [RESIGNATION_STAGES.RBM]: 30,
[RESIGNATION_STAGES.ZBH]: 40, [RESIGNATION_STAGES.ZBH]: 40,
[RESIGNATION_STAGES.DD_LEAD]: 50, [RESIGNATION_STAGES.DD_LEAD]: 50,
[RESIGNATION_STAGES.NBH]: 60, [RESIGNATION_STAGES.NBH]: 65,
[RESIGNATION_STAGES.DD_ADMIN]: 75, [RESIGNATION_STAGES.LEGAL]: 80,
[RESIGNATION_STAGES.LEGAL]: 85, [RESIGNATION_STAGES.DD_ADMIN]: 90,
[RESIGNATION_STAGES.FNF_INITIATED]: 95, [RESIGNATION_STAGES.FNF_INITIATED]: 95,
[RESIGNATION_STAGES.COMPLETED]: 100, [RESIGNATION_STAGES.COMPLETED]: 100,
[RESIGNATION_STAGES.REJECTED]: 100 [RESIGNATION_STAGES.REJECTED]: 100
@ -154,8 +154,8 @@ export class ResignationWorkflowService {
[RESIGNATION_STAGES.ZBH]: ROLES.ZBH, [RESIGNATION_STAGES.ZBH]: ROLES.ZBH,
[RESIGNATION_STAGES.DD_LEAD]: ROLES.DD_LEAD, [RESIGNATION_STAGES.DD_LEAD]: ROLES.DD_LEAD,
[RESIGNATION_STAGES.NBH]: ROLES.NBH, [RESIGNATION_STAGES.NBH]: ROLES.NBH,
[RESIGNATION_STAGES.DD_ADMIN]: ROLES.DD_ADMIN,
[RESIGNATION_STAGES.LEGAL]: ROLES.LEGAL_ADMIN, [RESIGNATION_STAGES.LEGAL]: ROLES.LEGAL_ADMIN,
[RESIGNATION_STAGES.DD_ADMIN]: ROLES.DD_ADMIN,
[RESIGNATION_STAGES.FNF_INITIATED]: ROLES.DD_ADMIN [RESIGNATION_STAGES.FNF_INITIATED]: ROLES.DD_ADMIN
}; };

View File

@ -16,7 +16,7 @@ export class TerminationWorkflowService {
* Standardized method to transition a termination request status * Standardized method to transition a termination request status
*/ */
static async transitionTermination(termination: any, targetStage: string, userId: string | null = null, metadata: any = {}) { static async transitionTermination(termination: any, targetStage: string, userId: string | null = null, metadata: any = {}) {
const { action, remarks, status } = metadata; const { action, remarks, status, transaction } = metadata;
const sourceStage = termination.currentStage; const sourceStage = termination.currentStage;
const updateData: any = { const updateData: any = {
@ -45,7 +45,7 @@ export class TerminationWorkflowService {
await termination.update({ await termination.update({
...updateData, ...updateData,
timeline: updatedTimeline timeline: updatedTimeline
}); }, transaction ? { transaction } : undefined);
// 4. Create Audit Log using standardized mapper // 4. Create Audit Log using standardized mapper
const { actionType } = metadata; const { actionType } = metadata;
@ -57,7 +57,7 @@ export class TerminationWorkflowService {
action: formatOffboardingAction(auditAction), action: formatOffboardingAction(auditAction),
remarks: remarks || '', remarks: remarks || '',
details: { status: updateData.status, stage: sourceStage, targetStage: formatOffboardingAction(targetStage) } details: { status: updateData.status, stage: sourceStage, targetStage: formatOffboardingAction(targetStage) }
}); }, transaction ? { transaction } : undefined);
// 5. Create Worknote for standardized communication trail // 5. Create Worknote for standardized communication trail
if (remarks && userId) { if (remarks && userId) {
@ -227,7 +227,7 @@ export class TerminationWorkflowService {
placeholders: { placeholders: {
dealerName: dealerUser?.fullName || 'Dealer', dealerName: dealerUser?.fullName || 'Dealer',
requestId: termination.requestId, requestId: termination.requestId,
link: `${portalBase}/fnf-settlements/${fnf.id}`, link: `${portalBase}/fnf/${fnf.id}`,
phone: phone || '' phone: phone || ''
} }
}); });
@ -308,4 +308,33 @@ export class TerminationWorkflowService {
remarks: summary remarks: summary
}); });
} }
/**
* Checks if a user is authorized to perform an action based on their role and current stage
*/
static async canUserAction(termination: any, user: any) {
if (!user) return false;
if (user.roleCode === ROLES.SUPER_ADMIN) return true;
const stageToRole: Record<string, string | string[]> = {
[TERMINATION_STAGES.SUBMITTED]: ROLES.ASM,
[TERMINATION_STAGES.RBM_REVIEW]: [ROLES.RBM, ROLES.DD_ZM],
[TERMINATION_STAGES.ZBH_REVIEW]: ROLES.ZBH,
[TERMINATION_STAGES.DD_LEAD_REVIEW]: ROLES.DD_LEAD,
[TERMINATION_STAGES.LEGAL_VERIFICATION]: ROLES.LEGAL_ADMIN,
[TERMINATION_STAGES.DD_HEAD_REVIEW]: ROLES.DD_HEAD,
[TERMINATION_STAGES.NBH_EVALUATION]: ROLES.NBH,
[TERMINATION_STAGES.SCN_ISSUED]: [ROLES.LEGAL_ADMIN, ROLES.DD_ADMIN],
[TERMINATION_STAGES.PERSONAL_HEARING]: [ROLES.NBH, ROLES.DD_LEAD],
[TERMINATION_STAGES.NBH_FINAL_APPROVAL]: ROLES.NBH,
[TERMINATION_STAGES.CCO_APPROVAL]: ROLES.CCO,
[TERMINATION_STAGES.CEO_APPROVAL]: ROLES.CEO,
[TERMINATION_STAGES.LEGAL_LETTER]: ROLES.LEGAL_ADMIN
};
const requiredRole = stageToRole[termination.currentStage];
if (Array.isArray(requiredRole)) {
return requiredRole.includes(user.roleCode);
}
return user.roleCode === requiredRole;
}
} }

View File

@ -93,7 +93,7 @@ async function run() {
console.log(`[INFO] Current stage before progression: ${currentStage}`); console.log(`[INFO] Current stage before progression: ${currentStage}`);
const approvals = [ const approvals = [
{ name: 'RBM Review', email: EMAILS.RBM, remarks: 'Performance concerns validated on-ground. Proceed with termination.' }, { name: 'RBM + DD-ZM Review', email: EMAILS.RBM, remarks: 'Performance concerns validated on-ground. Proceed with termination.' },
{ name: 'ZBH Review', email: EMAILS.ZBH, remarks: 'Strategic decision aligned with regional growth targets. Approved.' }, { name: 'ZBH Review', email: EMAILS.ZBH, remarks: 'Strategic decision aligned with regional growth targets. Approved.' },
{ name: 'DD Lead Review', email: EMAILS.DD_LEAD, remarks: 'Contractual breaches documented. Verified.' }, { name: 'DD Lead Review', email: EMAILS.DD_LEAD, remarks: 'Contractual breaches documented. Verified.' },
{ name: 'Legal Verification', email: EMAILS.LEGAL, remarks: 'Legal audit complete. Case is legally sound.' }, { name: 'Legal Verification', email: EMAILS.LEGAL, remarks: 'Legal audit complete. Case is legally sound.' },
@ -110,7 +110,7 @@ async function run() {
const stageOrder = [ const stageOrder = [
'Submitted', 'RBM Review', 'ZBH Review', 'DD Lead Review', 'Legal Verification', 'DD Head Review', 'Submitted', 'RBM + DD-ZM Review', 'ZBH Review', 'DD Lead Review', 'Legal Verification', 'DD Head Review',
'NBH Evaluation', 'Show Cause Notice', 'Personal Hearing', 'NBH Final Approval', 'CCO Approval', 'NBH Evaluation', 'Show Cause Notice', 'Personal Hearing', 'NBH Final Approval', 'CCO Approval',
'CEO Final Approval', 'Legal - Termination Letter', 'Terminated' 'CEO Final Approval', 'Legal - Termination Letter', 'Terminated'
]; ];