# 🏍️ Royal Enfield Approval Portal

A modern, enterprise-grade approval and request management system built with React, TypeScript, and Tailwind CSS.

## 📋 Table of Contents

- [Features](#-features)
- [Tech Stack](#️-tech-stack)
- [Prerequisites](#-prerequisites)
- [Installation](#-installation)
- [Development](#-development)
- [Project Structure](#-project-structure)
- [Available Scripts](#-available-scripts)
- [Configuration](#️-configuration)
- [Key Features Deep Dive](#-key-features-deep-dive)
- [Troubleshooting](#-troubleshooting)
- [Contributing](#-contributing)

## ✨ Features

### 🔄 Dual Workflow System
- **Custom Request Workflow** - User-defined approvers, spectators, and workflow steps
- **Claim Management Workflow** - 8-step predefined process for dealer claim management
- Flexible approval chains with multi-level approvers
- TAT (Turnaround Time) tracking at each approval level

### 📊 Comprehensive Dashboard
- Real-time statistics and metrics
- High-priority alerts and critical request tracking
- Recent activity feed with pagination
- Upcoming deadlines and SLA breach warnings
- Department-wise performance metrics
- Customizable KPI widgets (Admin only)

### 🎯 Request Management
- Create, track, and manage approval requests
- Document upload and management with file type validation
- Work notes and comprehensive audit trails
- Spectator and stakeholder management
- Request filtering, search, and export capabilities
- Detailed request lifecycle tracking

### 👥 Admin Control Panel
- **User Management** - Search, assign roles (USER, MANAGEMENT, ADMIN), and manage user permissions
- **User Role Management** - Assign and manage user roles with Okta integration
- **System Configuration** - Comprehensive admin settings:
  - **KPI Configuration** - Configure dashboard KPIs, visibility, and thresholds
  - **Analytics Configuration** - Data retention, export formats, and analytics features
  - **TAT Configuration** - Working hours, priority-based TAT, escalation settings
  - **Notification Configuration** - Email templates, notification channels, and settings
  - **Notification Preferences** - User-configurable notification settings
  - **Document Configuration** - File type restrictions, size limits, upload policies
  - **Dashboard Configuration** - Customize dashboard layout and widgets per role
  - **AI Configuration** - AI provider settings, parameters, and features
  - **Sharing Configuration** - Sharing policies and permissions
- **Holiday Management** - Configure business holidays for SLA calculations

### 📈 Approver Performance Analytics
- Detailed approver performance metrics and statistics
- Request approval history and trends
- Average approval time analysis
- Approval rate and efficiency metrics
- TAT compliance tracking per approver
- Performance comparison and benchmarking
- Export capabilities for performance reports

### 💬 Real-Time Live Chat (Work Notes)
- **WebSocket Integration** - Real-time bidirectional communication
- **Live Work Notes** - Instant messaging within request context
- **Presence Indicators** - See who's online/offline in real-time
- **Mention System** - @mention participants for notifications
- **File Attachments** - Share documents directly in chat
- **Message History** - Persistent chat history per request
- **Auto-reconnection** - Automatic reconnection on network issues
- **Room-based Communication** - Isolated chat rooms per request

### 🔔 Advanced Notifications
- **Web Push Notifications** - Browser push notifications using VAPID
- **Service Worker Integration** - Background notification delivery
- **Real-time Toast Notifications** - In-app notification system
- **SLA Tracking & Reminders** - Automated TAT breach alerts
- **Approval Status Updates** - Real-time status change notifications
- **Email Notifications** - Configurable email notification channels
- **Notification Preferences** - User-configurable notification settings

### 🎨 Modern UI/UX
- Responsive design (mobile, tablet, desktop)
- Dark mode support
- Accessible components (WCAG compliant)
- Royal Enfield brand theming
- Smooth animations and transitions
- Intuitive navigation and user flows

## 🛠️ Tech Stack

- **Framework:** React 18.3+
- **Language:** TypeScript 5.6+
- **Build Tool:** Vite 5.4+
- **Styling:** Tailwind CSS 3.4+
- **UI Components:** shadcn/ui + Radix UI
- **Icons:** Lucide React
- **Notifications:** Sonner (Toast) + Web Push API (VAPID)
- **Real-Time Communication:** Socket.IO Client
- **State Management:** React Hooks (useState, useMemo, useContext)
- **Authentication:** Okta SSO Integration
- **HTTP Client:** Axios

## 📦 Prerequisites

- **Node.js:** >= 18.0.0
- **npm:** >= 9.0.0 (or yarn/pnpm)
- **Git:** Latest version

## 🚀 Installation

### Quick Start Checklist

- [ ] Clone the repository
- [ ] Install Node.js (>= 18.0.0) and npm (>= 9.0.0)
- [ ] Install project dependencies
- [ ] Set up environment variables (`.env.local`)
- [ ] Ensure backend API is running (optional for initial setup)
- [ ] Start development server

### 1. Clone the repository

\`\`\`bash
git clone <repository-url>
cd Re_Frontend_Code
\`\`\`

### 2. Install dependencies

\`\`\`bash
npm install
\`\`\`

### 3. Set up environment variables

#### Option A: Automated Setup (Recommended - Unix/Linux/Mac)

Run the setup script to automatically create environment files:

\`\`\`bash
chmod +x setup-env.sh
./setup-env.sh
\`\`\`

This script will:
- Create `.env.example` with all required variables
- Create `.env.local` for local development
- Create `.env.production` with your production configuration (interactive)

#### Option B: Manual Setup (Windows or Custom Configuration)

**For Windows (PowerShell):**

1. Create `.env.local` file in the project root:

\`\`\`powershell
# Create .env.local file
New-Item -Path .env.local -ItemType File
\`\`\`

2. Add the following content to `.env.local`:

\`\`\`env
# Local Development Environment
VITE_API_BASE_URL=http://localhost:5000/api/v1
VITE_BASE_URL=http://localhost:5000

# Okta Authentication Configuration
VITE_OKTA_DOMAIN=your-okta-domain.okta.com
VITE_OKTA_CLIENT_ID=your-okta-client-id

# Push Notifications (Web Push / VAPID)
VITE_PUBLIC_VAPID_KEY=your-vapid-public-key
\`\`\`

**For Production:**

Create `.env.production` with production values:

\`\`\`env
# Production Environment
VITE_API_BASE_URL=https://your-backend-url.com/api/v1
VITE_BASE_URL=https://your-backend-url.com

# Okta Authentication Configuration
VITE_OKTA_DOMAIN=https://your-org.okta.com
VITE_OKTA_CLIENT_ID=your-production-client-id

# Push Notifications (Web Push / VAPID)
VITE_PUBLIC_VAPID_KEY=your-production-vapid-key
\`\`\`

#### Environment Variables Reference

| Variable | Description | Required | Default |
|----------|-------------|----------|---------|
| `VITE_API_BASE_URL` | Backend API base URL (with `/api/v1`) | Yes | `http://localhost:5000/api/v1` |
| `VITE_BASE_URL` | Base URL for WebSocket and direct file access (without `/api/v1`) | Yes | `http://localhost:5000` |
| `VITE_OKTA_DOMAIN` | Okta domain for SSO authentication | Yes* | - |
| `VITE_OKTA_CLIENT_ID` | Okta client ID for authentication | Yes* | - |
| `VITE_PUBLIC_VAPID_KEY` | Public VAPID key for web push notifications | No | - |

**Notes:**
- `VITE_BASE_URL` is used for WebSocket connections and must point to the base backend URL (not `/api/v1`)
- `VITE_PUBLIC_VAPID_KEY` is required for web push notifications. Generate using:
  \`\`\`bash
  npm install -g web-push
  web-push generate-vapid-keys
  \`\`\`
  Use the **public key** in the frontend `.env.local` file

\*Required if using Okta authentication

### 4. Verify setup

Check that all required files exist:

\`\`\`bash
# Check environment file exists
ls -la .env.local  # Unix/Linux/Mac
# or
Test-Path .env.local  # Windows PowerShell
\`\`\`

## 💻 Development

### Prerequisites

Before starting development, ensure:

1. **Backend API is running:**
   - The backend should be running on `http://localhost:5000` (or your configured URL)
   - Backend API should be accessible at `/api/v1` endpoint
   - CORS should be configured to allow your frontend origin

2. **Environment variables are configured:**
   - `.env.local` file exists and contains valid configuration
   - All required variables are set (see [Environment Variables Reference](#environment-variables-reference))

3. **Node.js and npm versions:**
   - Verify Node.js version: `node --version` (should be >= 18.0.0)
   - Verify npm version: `npm --version` (should be >= 9.0.0)

### Start development server

\`\`\`bash
npm run dev
\`\`\`

The application will open at `http://localhost:5173` (Vite default port)

> **Note:** If port 5173 is in use, Vite will automatically use the next available port.

### Build for production

\`\`\`bash
npm run build
\`\`\`

### Preview production build

\`\`\`bash
npm run preview
\`\`\`

## 📁 Project Structure

\`\`\`
Re_Figma_Code/
├── src/
│   ├── components/
│   │   ├── ui/                      # Reusable UI components (40+)
│   │   ├── admin/                   # Admin components
│   │   │   ├── AIConfig/            # AI configuration
│   │   │   ├── AnalyticsConfig/     # Analytics settings
│   │   │   ├── DashboardConfig/     # Dashboard customization
│   │   │   ├── DocumentConfig/      # Document policies
│   │   │   ├── NotificationConfig/  # Notification settings
│   │   │   ├── SharingConfig/      # Sharing policies
│   │   │   ├── TATConfig/          # TAT configuration
│   │   │   ├── UserManagement/      # User management
│   │   │   └── UserRoleManager/    # Role assignment
│   │   ├── approval/                # Approval workflow components
│   │   ├── common/                  # Common reusable components
│   │   ├── dashboard/               # Dashboard widgets
│   │   ├── modals/                  # Modal components
│   │   ├── participant/             # Participant management
│   │   ├── workflow/                # Workflow components
│   │   └── workNote/                # Work notes/chat components
│   ├── pages/
│   │   ├── Admin/                   # Admin control panel
│   │   ├── ApproverPerformance/     # Approver analytics
│   │   ├── Auth/                    # Authentication pages
│   │   ├── Dashboard/               # Main dashboard
│   │   ├── RequestDetail/           # Request detail view
│   │   ├── Requests/                # Request listing
│   │   └── ...
│   ├── hooks/                       # Custom React hooks
│   │   ├── useRequestSocket.ts      # WebSocket integration
│   │   ├── useDocumentUpload.ts     # Document management
│   │   ├── useSLATracking.ts        # SLA tracking
│   │   └── ...
│   ├── services/                    # API services
│   │   ├── adminApi.ts              # Admin API calls
│   │   ├── authApi.ts               # Authentication API
│   │   ├── workflowApi.ts           # Workflow API
│   │   └── ...
│   ├── utils/
│   │   ├── socket.ts                # Socket.IO utilities
│   │   ├── pushNotifications.ts    # Web push notifications
│   │   ├── slaTracker.ts            # SLA calculation utilities
│   │   └── ...
│   ├── contexts/
│   │   └── AuthContext.tsx          # Authentication context
│   ├── styles/
│   │   └── globals.css
│   ├── types/
│   │   └── index.ts
│   ├── App.tsx
│   └── main.tsx
├── public/
│   └── service-worker.js            # Service worker for push notifications
├── .vscode/
├── index.html
├── vite.config.ts
├── tsconfig.json
├── tailwind.config.ts
├── postcss.config.js
├── eslint.config.js
├── .prettierrc
├── .gitignore
├── package.json
└── README.md
\`\`\`

## 📜 Available Scripts

| Script | Description |
|--------|-------------|
| `npm run dev` | Start development server |
| `npm run build` | Build for production |
| `npm run preview` | Preview production build |
| `npm run lint` | Run ESLint |
| `npm run lint:fix` | Fix ESLint errors |
| `npm run format` | Format code with Prettier |
| `npm run type-check` | Check TypeScript types |

## ⚙️ Configuration

### TypeScript Path Aliases

The project uses path aliases for cleaner imports:

\`\`\`typescript
import { Button } from '@/components/ui/button';
import { getSocket } from '@/utils/socket';
\`\`\`

Path aliases are configured in:
- `tsconfig.json` - TypeScript path mapping
- `vite.config.ts` - Vite resolver configuration

### Tailwind CSS Customization

Custom Royal Enfield colors are defined in `tailwind.config.ts`:

\`\`\`typescript
colors: {
  're-green': '#2d4a3e',
  're-gold': '#c9b037',
  're-dark': '#1a1a1a',
  're-light-green': '#8a9b8e',
}
\`\`\`

### Environment Variables

All environment variables must be prefixed with `VITE_` to be accessible in the app:

\`\`\`typescript
// Access environment variables
const apiUrl = import.meta.env.VITE_API_BASE_URL;
const baseUrl = import.meta.env.VITE_BASE_URL;
const oktaDomain = import.meta.env.VITE_OKTA_DOMAIN;
\`\`\`

**Important Notes:**
- Environment variables are embedded at build time, not runtime
- Changes to `.env` files require restarting the dev server
- `.env.local` takes precedence over `.env` in development
- `.env.production` is used when building for production (`npm run build`)

### Backend Integration

To connect to the backend API:

1. **Update API base URL** in `.env.local`:
   \`\`\`env
   VITE_API_BASE_URL=http://localhost:5000/api/v1
   VITE_BASE_URL=http://localhost:5000
   \`\`\`

2. **Configure CORS** in your backend to allow your frontend origin

3. **Authentication:**
   - Configure Okta credentials in environment variables
   - Ensure backend validates JWT tokens from Okta
   - Backend should handle token exchange and refresh

4. **WebSocket Configuration:**
   - Backend must support Socket.IO on the base URL
   - Socket.IO path: `/socket.io`
   - CORS must allow WebSocket connections
   - Events: `worknote:new`, `presence:join`, `presence:leave`, `request:online-users`

5. **Web Push Notifications:**
   - Backend must support VAPID push notification delivery
   - Service worker registration endpoint required
   - Push subscription management API needed
   - Generate VAPID keys using: `npm install -g web-push && web-push generate-vapid-keys`

6. **API Services:**
   - API services are located in `src/services/`
   - All API calls use `axios` configured with base URL from environment
   - WebSocket utilities in `src/utils/socket.ts`

### Development vs Production

- **Development:** Uses `.env.local` (git-ignored)
- **Production:** Uses `.env.production` or environment variables set in deployment platform
- **Never commit:** `.env.local` or `.env.production` (use `.env.example` as template)

## 🚀 Key Features Deep Dive

### 👥 Admin Control Panel

The Admin Control Panel (`/admin`) provides comprehensive system management capabilities accessible only to ADMIN role users:

#### User Management
- **User Search**: Search users via Okta integration with real-time search
- **Role Assignment**: Assign and manage user roles (USER, MANAGEMENT, ADMIN)
- **User Statistics**: View role distribution and user counts
- **Pagination**: Efficient pagination for large user lists
- **Filtering**: Filter users by role (ELEVATED, ADMIN, MANAGEMENT, USER, ALL)

#### System Configuration Tabs

1. **KPI Configuration**
   - Configure dashboard KPIs with visibility settings per role
   - Set alert thresholds and breach conditions
   - Organize KPIs by categories (Request Volume, TAT Efficiency, Approver Load, etc.)
   - Enable/disable KPIs dynamically

2. **Analytics Configuration**
   - Data retention policies
   - Export format settings (CSV, Excel, PDF)
   - Analytics feature toggles
   - Data collection preferences

3. **TAT Configuration**
   - Working hours configuration (start/end time, days of week)
   - Priority-based TAT settings (express, standard, urgent)
   - Escalation rules and thresholds
   - Holiday calendar integration

4. **Notification Configuration**
   - Email template customization
   - Notification channel management (email, push, in-app)
   - Notification frequency settings
   - Delivery preferences
   - **Notification Preferences** - User-configurable notification settings

5. **Document Configuration**
   - Allowed file types and extensions
   - File size limits (per file and total)
   - Upload validation rules
   - Document policy enforcement

6. **Dashboard Configuration**
   - Customize dashboard layout per role
   - Widget visibility settings
   - Dashboard widget ordering
   - Role-specific dashboard views

7. **AI Configuration**
   - AI provider settings (OpenAI, Anthropic, etc.)
   - AI parameters and model selection
   - AI feature toggles
   - API key management

8. **Sharing Configuration**
   - Sharing policies and permissions
   - External sharing settings
   - Access control rules

#### Holiday Management
- Configure business holidays for accurate SLA calculations
- Holiday calendar integration
- Regional holiday support

### 📈 Approver Performance Dashboard

Comprehensive analytics dashboard (`/approver-performance`) for tracking and analyzing approver performance:

#### Key Metrics
- **Approval Statistics**: Total approvals, approval rate, average approval time
- **TAT Compliance**: Percentage of approvals within TAT
- **Request History**: Complete list of requests handled by approver
- **Performance Trends**: Time-based performance analysis
- **SLA Metrics**: TAT breach analysis and compliance tracking

#### Features
- **Advanced Filtering**: Filter by date range, status, priority, SLA compliance
- **Search Functionality**: Search requests by title, ID, or description
- **Export Capabilities**: Export performance data in CSV/Excel formats
- **Visual Analytics**: Charts and graphs for performance visualization
- **Comparison Tools**: Compare performance across different time periods
- **Detailed Request List**: View all requests with approval details

### 💬 Real-Time Live Chat (Work Notes)

Powered by Socket.IO for instant, bidirectional communication within request context:

#### Core Features
- **Real-Time Messaging**: Instant message delivery with Socket.IO
- **Presence Indicators**: See who's online/offline in real-time
- **@Mention System**: Mention participants using @username syntax
- **File Attachments**: Upload and share documents directly in chat
- **Message History**: Persistent chat history per request
- **Rich Text Support**: Format messages with mentions and links

#### Technical Implementation
- **Socket.IO Client**: Real-time WebSocket communication
- **Room-Based Architecture**: Each request has isolated chat room
- **Auto-Reconnection**: Automatic reconnection on network issues
- **Presence Management**: Real-time user presence tracking
- **Message Persistence**: Messages stored in backend database

#### Usage
- Access via Request Detail page > Work Notes tab
- Full-screen chat interface available
- Real-time updates for all participants
- Notification on new messages

### 🔔 Web Push Notifications

Browser push notifications using VAPID (Voluntary Application Server Identification) protocol:

#### Features
- **Service Worker Integration**: Background notification delivery
- **VAPID Protocol**: Secure, standards-based push notifications
- **Permission Management**: User-friendly permission requests
- **Notification Preferences**: User-configurable notification settings
- **Cross-Platform Support**: Works on desktop and mobile browsers
- **Offline Queue**: Notifications queued when browser is offline

#### Configuration
1. Generate VAPID keys (public/private pair)
2. Set `VITE_PUBLIC_VAPID_KEY` in environment variables
3. Backend must support VAPID push notification delivery
4. Service worker automatically registers on app load

#### Notification Types
- **SLA Alerts**: TAT breach and approaching deadline notifications
- **Approval Requests**: New requests assigned to approver
- **Status Updates**: Request status change notifications
- **Work Note Mentions**: Notifications when mentioned in chat
- **System Alerts**: Critical system notifications

#### Browser Support
- Chrome/Edge: Full support
- Firefox: Full support
- Safari: Limited support (macOS/iOS)
- Requires HTTPS in production

## 🔧 Troubleshooting

### Common Issues

#### WebSocket Connection Issues

If real-time features (chat, presence) are not working:

1. Verify backend Socket.IO server is running
2. Check `VITE_BASE_URL` in `.env.local` (should not include `/api/v1`)
3. Ensure CORS allows WebSocket connections
4. Check browser console for Socket.IO connection errors
5. Verify Socket.IO path is `/socket.io` (default)

\`\`\`bash
# Test WebSocket connection
# Open browser console and check for Socket.IO connection logs
\`\`\`

#### Web Push Notifications Not Working

1. Ensure `VITE_PUBLIC_VAPID_KEY` is set in `.env.local`
2. Verify service worker is registered (check Application tab in DevTools)
3. Check browser notification permissions
4. Ensure HTTPS in production (required for push notifications)
5. Verify backend push notification endpoint is configured

\`\`\`bash
# Check service worker registration
# Open DevTools > Application > Service Workers
\`\`\`

#### Port Already in Use

If the default port (5173) is in use:

\`\`\`bash
# Option 1: Kill the process using the port
# Windows
netstat -ano | findstr :5173
taskkill /PID <PID> /F

# Unix/Linux/Mac
lsof -ti:5173 | xargs kill -9

# Option 2: Use a different port
npm run dev -- --port 3000
\`\`\`

#### Environment Variables Not Loading

1. Ensure variables are prefixed with `VITE_`
2. Restart the dev server after changing `.env` files
3. Check that `.env.local` exists in the project root
4. Verify no typos in variable names

#### Backend Connection Issues

1. Verify backend is running on the configured port
2. Check `VITE_API_BASE_URL` in `.env.local` matches backend URL
3. Ensure CORS is configured in backend to allow frontend origin
4. Check browser console for detailed error messages

#### Build Errors

\`\`\`bash
# Clear cache and rebuild
rm -rf node_modules/.vite
npm run build

# Check for TypeScript errors
npm run type-check
\`\`\`

### Getting Help

- Check browser console for errors
- Verify all environment variables are set correctly
- Ensure Node.js and npm versions meet requirements
- Review backend logs for API-related issues
- Check Network tab for WebSocket connection status
- Verify service worker registration in DevTools > Application

## 🔐 Role-Based Access Control

The application supports three user roles with different access levels:

### USER Role
- Create and manage own requests
- View assigned requests
- Approve/reject requests assigned to them
- Add work notes and comments
- Upload documents

### MANAGEMENT Role
- All USER permissions
- View all requests across the organization
- Access to detailed reports and analytics
- Approver Performance dashboard access
- Export capabilities

### ADMIN Role
- All MANAGEMENT permissions
- Access to Admin Control Panel (`/admin`)
- User management and role assignment
- System configuration (TAT, Notifications, Documents, etc.)
- KPI configuration and dashboard customization
- Holiday calendar management
- Full system administration capabilities

## 🧪 Testing (Future Enhancement)

Add testing framework:

\`\`\`bash
npm install -D vitest @testing-library/react @testing-library/jest-dom
\`\`\`

## 🤝 Contributing

1. Follow the existing code style
2. Run `npm run lint:fix` before committing
3. Run `npm run type-check` to ensure type safety
4. Write meaningful commit messages

## 📝 License

Private - Royal Enfield Internal Use Only

## 👥 Team

Built by the Royal Enfield Development Team

---

**For support or questions, contact the development team.**

