diff --git a/Markdown_Viewer.html b/Markdown_Viewer.html new file mode 100644 index 0000000..87f89c1 --- /dev/null +++ b/Markdown_Viewer.html @@ -0,0 +1,944 @@ + + + + + + Markdown Viewer + + + + + + + + + + +
+
+

πŸ“ Markdown Viewer

+

Upload a file or paste your Markdown to see beautiful rendered output

+
+ +
+
+

πŸ“„ Input

+ +
+ + +
+ +
+ + +
+ +
+
+
πŸ“
+

Click to upload or drag and drop

+

Supports .md, .markdown, .txt files

+
+ +
+ +
+

βš™οΈ Options

+
+ + + + +
+
+ +
+
+ +
+

πŸ‘οΈ Preview

+
+
+
πŸ“„
+

Your rendered Markdown will appear here

+
+
+ + + +
+
+
+
+
+ + + + + diff --git a/RE_Workflow_Complete_Project_Setup.md b/RE_Workflow_Complete_Project_Setup.md new file mode 100644 index 0000000..66ff0ae --- /dev/null +++ b/RE_Workflow_Complete_Project_Setup.md @@ -0,0 +1,2665 @@ +# RE Workflow Management System - Complete Project Setup Guide +## Non-Templatized Workflow System +**Version:** 1.0 +**Date:** October 16, 2025 +**Technology Stack:** Node.js 22 LTS + TypeScript 5.7 + React.js 19 (TSX) + PostgreSQL 16 + +--- + +## Table of Contents +1. [System Architecture Overview](#system-architecture-overview) +2. [Technology Matrix](#technology-matrix) +3. [Project Folder Structure](#project-folder-structure) +4. [Backend Architecture](#backend-architecture) +5. [Frontend Architecture](#frontend-architecture) +6. [Database Schema Design](#database-schema-design) +7. [API Endpoints Structure](#api-endpoints-structure) +8. [Authentication & Security](#authentication-security) +9. [Configuration Management](#configuration-management) +10. [Deployment Architecture](#deployment-architecture) +11. [Development Setup Instructions](#development-setup-instructions) + +--- + +## 1. System Architecture Overview + +### High-Level Architecture + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ CLIENT LAYER β”‚ +β”‚ React.js SPA (Single Page Application) β”‚ +β”‚ - Material-UI / Ant Design Components β”‚ +β”‚ - Redux Toolkit for State Management β”‚ +β”‚ - React Router for Navigation β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↕ HTTPS +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ API GATEWAY LAYER β”‚ +β”‚ - SSO Authentication Bridge β”‚ +β”‚ - JWT Token Validation β”‚ +β”‚ - Rate Limiting & Request Throttling β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↕ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ APPLICATION LAYER (Node.js) β”‚ +β”‚ - Express.js REST API Server β”‚ +β”‚ - Business Logic & Controllers β”‚ +β”‚ - Service Layer (Workflow, Notification, Document) β”‚ +β”‚ - AI Integration (Conclusion Generation) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↕ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ DATA LAYER (PostgreSQL) β”‚ +β”‚ - Relational Database β”‚ +β”‚ - Stored Procedures & Functions β”‚ +β”‚ - Triggers for Activity Logging β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↕ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ STORAGE LAYER β”‚ +β”‚ - Cloud Storage (GCP Cloud Storage) β”‚ +β”‚ - Document Repository β”‚ +β”‚ - Backup & Recovery System β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## 2. Technology Matrix + +| Component | Technology | Version | Purpose | +|-----------|-----------|---------|---------| +| **Backend Runtime** | Node.js | 22.x LTS | Server-side JavaScript runtime | +| **Backend Language** | TypeScript | 5.7.x | Type-safe backend development | +| **Backend Framework** | Express.js | 4.21.x | RESTful API framework | +| **Frontend Library** | React.js | 19.0.x | UI component library | +| **Frontend Language** | TypeScript (TSX) | 5.7.x | Type-safe frontend development | +| **UI Framework** | Material-UI (MUI) | 6.3.x | Component design system | +| **State Management** | Redux Toolkit | 2.5.x | Application state management | +| **Database** | PostgreSQL | 16.x | Primary relational database | +| **ORM** | Sequelize + TypeScript | 6.37.x | Database ORM with TypeScript support | +| **Authentication** | Passport.js | 0.7.x | SSO integration middleware | +| **Validation** | Zod | 3.24.x | TypeScript-first schema validation | +| **File Upload** | Multer | 1.4.x | Multipart file handling | +| **Logging** | Winston | 3.17.x | Application logging | +| **API Documentation** | Swagger/OpenAPI | 3.1 | API documentation | +| **Testing (Backend)** | Jest + Supertest + ts-jest | 29.x | Unit & integration testing | +| **Testing (Frontend)** | Jest + React Testing Library | 16.x | Component testing | +| **Process Manager** | PM2 | 5.4.x | Production process management | +| **Build Tool** | Vite + ts-loader | 6.x | Module bundler with TypeScript | +| **Code Quality** | ESLint + Prettier + TypeScript ESLint | 9.x/3.x | Code linting & formatting | + +--- + +## 3. Project Folder Structure + +### Repository Structure (Separate Repositories Approach) + +This project uses **separate repositories** for frontend and backend, enabling: +- **Independent deployment pipelines** +- **Better team ownership** (Frontend team vs Backend team) +- **Technology-specific CI/CD workflows** +- **Isolated version control and release cycles** +- **Cleaner dependency management** + +--- + +### Repository 1: Backend Repository (`re-workflow-backend`) + +``` +re-workflow-backend/ +β”‚ +β”œβ”€β”€ src/ # Source code +β”‚ β”œβ”€β”€ app.ts +β”‚ β”œβ”€β”€ server.ts +β”‚ β”œβ”€β”€ types/ +β”‚ β”œβ”€β”€ config/ +β”‚ β”œβ”€β”€ controllers/ +β”‚ β”œβ”€β”€ services/ +β”‚ β”œβ”€β”€ models/ +β”‚ β”œβ”€β”€ routes/ +β”‚ β”œβ”€β”€ middlewares/ +β”‚ β”œβ”€β”€ validators/ +β”‚ β”œβ”€β”€ utils/ +β”‚ β”œβ”€β”€ jobs/ +β”‚ └── seeders/ +β”‚ +β”œβ”€β”€ dist/ # Compiled JavaScript output +β”‚ +β”œβ”€β”€ tests/ # Test suites +β”‚ β”œβ”€β”€ unit/ +β”‚ β”œβ”€β”€ integration/ +β”‚ └── setup.ts +β”‚ +β”œβ”€β”€ database/ # Database Scripts & Migrations +β”‚ β”œβ”€β”€ migrations/ +β”‚ β”œβ”€β”€ seeders/ +β”‚ β”œβ”€β”€ schema/ +β”‚ β”‚ └── schema.sql +β”‚ └── README.md +β”‚ +β”œβ”€β”€ logs/ # Application logs +β”‚ β”œβ”€β”€ error.log +β”‚ β”œβ”€β”€ combined.log +β”‚ └── access.log +β”‚ +β”œβ”€β”€ uploads/ # Temporary upload directory +β”‚ └── .gitkeep +β”‚ +β”œβ”€β”€ docs/ # API Documentation +β”‚ β”œβ”€β”€ swagger/ +β”‚ └── postman/ +β”‚ +β”œβ”€β”€ scripts/ # Deployment & Utility Scripts +β”‚ β”œβ”€β”€ deploy.sh +β”‚ β”œβ”€β”€ backup.sh +β”‚ β”œβ”€β”€ setup.sh +β”‚ └── seed-db.sh +β”‚ +β”œβ”€β”€ .env.example # Environment variables template +β”œβ”€β”€ .env.development +β”œβ”€β”€ .env.production +β”œβ”€β”€ .eslintrc.json +β”œβ”€β”€ .prettierrc +β”œβ”€β”€ .gitignore +β”œβ”€β”€ .dockerignore +β”œβ”€β”€ Dockerfile +β”œβ”€β”€ docker-compose.yml # For local development with DB +β”œβ”€β”€ jest.config.js +β”œβ”€β”€ tsconfig.json # TypeScript configuration +β”œβ”€β”€ nodemon.json +β”œβ”€β”€ package.json +β”œβ”€β”€ package-lock.json +└── README.md +``` + +--- + +### Repository 2: Frontend Repository (`re-workflow-frontend`) + +``` +re-workflow-frontend/ +β”‚ +β”œβ”€β”€ public/ # Static assets +β”‚ β”œβ”€β”€ index.html +β”‚ β”œβ”€β”€ favicon.ico +β”‚ β”œβ”€β”€ robots.txt +β”‚ β”œβ”€β”€ manifest.json +β”‚ └── assets/ +β”‚ +β”œβ”€β”€ src/ # Source code +β”‚ β”œβ”€β”€ index.tsx +β”‚ β”œβ”€β”€ App.tsx +β”‚ β”œβ”€β”€ App.css +β”‚ β”œβ”€β”€ react-app-env.d.ts +β”‚ β”œβ”€β”€ types/ +β”‚ β”œβ”€β”€ assets/ +β”‚ β”œβ”€β”€ components/ +β”‚ β”œβ”€β”€ pages/ +β”‚ β”œβ”€β”€ redux/ +β”‚ β”œβ”€β”€ services/ +β”‚ β”œβ”€β”€ hooks/ +β”‚ β”œβ”€β”€ utils/ +β”‚ β”œβ”€β”€ routes/ +β”‚ └── config/ +β”‚ +β”œβ”€β”€ dist/ # Build output (Vite) +β”‚ +β”œβ”€β”€ tests/ # Test files +β”‚ β”œβ”€β”€ components/ +β”‚ β”œβ”€β”€ pages/ +β”‚ β”œβ”€β”€ redux/ +β”‚ β”œβ”€β”€ services/ +β”‚ └── setup.ts +β”‚ +β”œβ”€β”€ docs/ # Component documentation +β”‚ └── storybook/ +β”‚ +β”œβ”€β”€ nginx/ # Nginx configuration for production +β”‚ └── default.conf +β”‚ +β”œβ”€β”€ .env.example # Environment variables template +β”œβ”€β”€ .env.development +β”œβ”€β”€ .env.production +β”œβ”€β”€ .eslintrc.json +β”œβ”€β”€ .prettierrc +β”œβ”€β”€ .gitignore +β”œβ”€β”€ .dockerignore +β”œβ”€β”€ Dockerfile +β”œβ”€β”€ vite.config.ts # Vite configuration +β”œβ”€β”€ tsconfig.json # TypeScript configuration +β”œβ”€β”€ package.json +β”œβ”€β”€ package-lock.json +└── README.md +``` + +--- + +### Shared Types Management + +Since repositories are separate, shared TypeScript types (like `Priority`, `WorkflowStatus`, etc.) can be managed in two ways: + +#### **Option 1: Duplicate Types (Recommended for Independence)** +- Maintain separate type definitions in each repository +- Ensures complete independence and no cross-repository dependencies +- Slight duplication but maximum flexibility + +#### **Option 2: Shared NPM Package** +- Create a private NPM package `@re-workflow/types` +- Publish to private npm registry (GitHub Packages, npm private, Artifactory) +- Import in both repositories: `npm install @re-workflow/types` +- Example structure: + ``` + @re-workflow/types/ + β”œβ”€β”€ src/ + β”‚ β”œβ”€β”€ index.ts + β”‚ β”œβ”€β”€ user.types.ts + β”‚ β”œβ”€β”€ workflow.types.ts + β”‚ β”œβ”€β”€ approval.types.ts + β”‚ └── common.types.ts + β”œβ”€β”€ package.json + └── tsconfig.json + ``` + +--- + +## 4. Backend Architecture + +### Complete Backend Folder Structure + +``` +backend/ +β”‚ +β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ app.ts # Express app initialization +β”‚ β”œβ”€β”€ server.ts # Server entry point +β”‚ β”‚ +β”‚ β”œβ”€β”€ types/ # TypeScript type definitions +β”‚ β”‚ β”œβ”€β”€ index.ts # Main types export +β”‚ β”‚ β”œβ”€β”€ express.d.ts # Express type extensions +β”‚ β”‚ β”œβ”€β”€ user.types.ts # User related types +β”‚ β”‚ β”œβ”€β”€ workflow.types.ts # Workflow related types +β”‚ β”‚ β”œβ”€β”€ approval.types.ts # Approval related types +β”‚ β”‚ β”œβ”€β”€ document.types.ts # Document related types +β”‚ β”‚ β”œβ”€β”€ notification.types.ts # Notification types +β”‚ β”‚ └── common.types.ts # Common/shared types +β”‚ β”‚ +β”‚ β”œβ”€β”€ config/ # Configuration files +β”‚ β”‚ β”œβ”€β”€ database.ts # Database configuration +β”‚ β”‚ β”œβ”€β”€ jwt.ts # JWT configuration +β”‚ β”‚ β”œβ”€β”€ sso.ts # SSO Bridge configuration +β”‚ β”‚ β”œβ”€β”€ storage.ts # Cloud storage config +β”‚ β”‚ β”œβ”€β”€ email.ts # Email service config +β”‚ β”‚ └── constants.ts # Application constants +β”‚ β”‚ +β”‚ β”œβ”€β”€ controllers/ # Request handlers +β”‚ β”‚ β”œβ”€β”€ auth.controller.ts +β”‚ β”‚ β”œβ”€β”€ workflow.controller.ts +β”‚ β”‚ β”œβ”€β”€ approval.controller.ts +β”‚ β”‚ β”œβ”€β”€ document.controller.ts +β”‚ β”‚ β”œβ”€β”€ notification.controller.ts +β”‚ β”‚ β”œβ”€β”€ workNote.controller.ts +β”‚ β”‚ β”œβ”€β”€ participant.controller.ts +β”‚ β”‚ β”œβ”€β”€ dashboard.controller.ts +β”‚ β”‚ └── user.controller.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ services/ # Business logic layer +β”‚ β”‚ β”œβ”€β”€ auth.service.ts +β”‚ β”‚ β”œβ”€β”€ workflow.service.ts +β”‚ β”‚ β”œβ”€β”€ approval.service.ts +β”‚ β”‚ β”œβ”€β”€ tat.service.ts # TAT calculation & monitoring +β”‚ β”‚ β”œβ”€β”€ notification.service.ts +β”‚ β”‚ β”œβ”€β”€ document.service.ts +β”‚ β”‚ β”œβ”€β”€ workNote.service.ts +β”‚ β”‚ β”œβ”€β”€ participant.service.ts +β”‚ β”‚ β”œβ”€β”€ activity.service.ts +β”‚ β”‚ β”œβ”€β”€ ai.service.ts # AI conclusion generation +β”‚ β”‚ β”œβ”€β”€ email.service.ts +β”‚ β”‚ └── storage.service.ts # Cloud storage operations +β”‚ β”‚ +β”‚ β”œβ”€β”€ models/ # Sequelize models (ORM) +β”‚ β”‚ β”œβ”€β”€ index.ts # Model loader +β”‚ β”‚ β”œβ”€β”€ User.ts +β”‚ β”‚ β”œβ”€β”€ WorkflowRequest.ts +β”‚ β”‚ β”œβ”€β”€ ApprovalLevel.ts +β”‚ β”‚ β”œβ”€β”€ Approver.ts +β”‚ β”‚ β”œβ”€β”€ Participant.ts +β”‚ β”‚ β”œβ”€β”€ Spectator.ts +β”‚ β”‚ β”œβ”€β”€ Document.ts +β”‚ β”‚ β”œβ”€β”€ WorkNote.ts +β”‚ β”‚ β”œβ”€β”€ Activity.ts +β”‚ β”‚ β”œβ”€β”€ Notification.ts +β”‚ β”‚ β”œβ”€β”€ TATTracking.ts +β”‚ β”‚ └── ConclusionRemark.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ routes/ # API route definitions +β”‚ β”‚ β”œβ”€β”€ index.ts # Route aggregator +β”‚ β”‚ β”œβ”€β”€ auth.routes.ts +β”‚ β”‚ β”œβ”€β”€ workflow.routes.ts +β”‚ β”‚ β”œβ”€β”€ approval.routes.ts +β”‚ β”‚ β”œβ”€β”€ document.routes.ts +β”‚ β”‚ β”œβ”€β”€ notification.routes.ts +β”‚ β”‚ β”œβ”€β”€ workNote.routes.ts +β”‚ β”‚ β”œβ”€β”€ participant.routes.ts +β”‚ β”‚ β”œβ”€β”€ dashboard.routes.ts +β”‚ β”‚ └── user.routes.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ middlewares/ # Express middlewares +β”‚ β”‚ β”œβ”€β”€ auth.middleware.ts # JWT verification +β”‚ β”‚ β”œβ”€β”€ sso.middleware.ts # SSO validation +β”‚ β”‚ β”œβ”€β”€ validate.middleware.ts # Request validation +β”‚ β”‚ β”œβ”€β”€ upload.middleware.ts # File upload handling +β”‚ β”‚ β”œβ”€β”€ rateLimiter.middleware.ts # Rate limiting +β”‚ β”‚ β”œβ”€β”€ errorHandler.middleware.ts +β”‚ β”‚ β”œβ”€β”€ logger.middleware.ts +β”‚ β”‚ └── cors.middleware.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ validators/ # Request validation schemas (Zod) +β”‚ β”‚ β”œβ”€β”€ auth.validator.ts +β”‚ β”‚ β”œβ”€β”€ workflow.validator.ts +β”‚ β”‚ β”œβ”€β”€ approval.validator.ts +β”‚ β”‚ β”œβ”€β”€ document.validator.ts +β”‚ β”‚ β”œβ”€β”€ workNote.validator.ts +β”‚ β”‚ └── participant.validator.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ utils/ # Utility functions +β”‚ β”‚ β”œβ”€β”€ logger.ts # Winston logger setup +β”‚ β”‚ β”œβ”€β”€ responseHandler.ts # Standardized API responses +β”‚ β”‚ β”œβ”€β”€ errorHandler.ts # Custom error classes +β”‚ β”‚ β”œβ”€β”€ dateCalculator.ts # TAT & date calculations +β”‚ β”‚ β”œβ”€β”€ fileValidator.ts # File type & size validation +β”‚ β”‚ β”œβ”€β”€ emailTemplate.ts # Email templates +β”‚ β”‚ └── helpers.ts # General helper functions +β”‚ β”‚ +β”‚ β”œβ”€β”€ jobs/ # Background jobs & schedulers +β”‚ β”‚ β”œβ”€β”€ tatMonitor.job.ts # TAT monitoring cron job +β”‚ β”‚ β”œβ”€β”€ reminderSender.job.ts # Automated reminder system +β”‚ β”‚ β”œβ”€β”€ dataCleanup.job.ts # Old data cleanup +β”‚ β”‚ └── reportGenerator.job.ts # Periodic reports +β”‚ β”‚ +β”‚ └── seeders/ # Database seed data +β”‚ β”œβ”€β”€ admin.seeder.ts +β”‚ └── testData.seeder.ts +β”‚ +β”œβ”€β”€ dist/ # Compiled JavaScript output +β”‚ +β”œβ”€β”€ tests/ # Test suites +β”‚ β”œβ”€β”€ unit/ +β”‚ β”‚ β”œβ”€β”€ services/ +β”‚ β”‚ β”œβ”€β”€ controllers/ +β”‚ β”‚ └── utils/ +β”‚ β”œβ”€β”€ integration/ +β”‚ β”‚ β”œβ”€β”€ api/ +β”‚ β”‚ └── database/ +β”‚ └── setup.js +β”‚ +β”œβ”€β”€ logs/ # Application logs +β”‚ β”œβ”€β”€ error.log +β”‚ β”œβ”€β”€ combined.log +β”‚ └── access.log +β”‚ +β”œβ”€β”€ uploads/ # Temporary upload directory +β”‚ └── .gitkeep +β”‚ +β”œβ”€β”€ .env.example # Environment variables template +β”œβ”€β”€ .env.development +β”œβ”€β”€ .env.production +β”œβ”€β”€ .eslintrc.json +β”œβ”€β”€ .prettierrc +β”œβ”€β”€ jest.config.js +β”œβ”€β”€ tsconfig.json # TypeScript configuration +β”œβ”€β”€ nodemon.json +β”œβ”€β”€ package.json +└── README.md +``` + +### Key Backend Files Content Examples + +#### **backend/tsconfig.json** +```json +{ + "compilerOptions": { + "target": "ES2021", + "module": "commonjs", + "lib": ["ES2021"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "moduleResolution": "node", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "types": ["node", "jest"], + "typeRoots": ["./node_modules/@types", "./src/types"], + "baseUrl": "./src", + "paths": { + "@/*": ["./*"], + "@controllers/*": ["controllers/*"], + "@services/*": ["services/*"], + "@models/*": ["models/*"], + "@middlewares/*": ["middlewares/*"], + "@utils/*": ["utils/*"], + "@types/*": ["types/*"], + "@config/*": ["config/*"] + } + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "tests"] +} +``` + +#### **backend/src/app.ts** +```typescript +import express, { Application, Request, Response } from 'express'; +import helmet from 'helmet'; +import cors from 'cors'; +import morgan from 'morgan'; +import routes from './routes'; +import errorHandler from './middlewares/errorHandler.middleware'; +import logger from './utils/logger'; + +const app: Application = express(); + +// Security middleware +app.use(helmet()); +app.use(cors()); + +// Body parsing middleware +app.use(express.json({ limit: '10mb' })); +app.use(express.urlencoded({ extended: true, limit: '10mb' })); + +// Logging middleware +app.use(morgan('combined', { stream: logger.stream })); + +// API routes +app.use('/api/v1', routes); + +// Health check endpoint +app.get('/health', (req: Request, res: Response) => { + res.status(200).json({ status: 'OK', timestamp: new Date() }); +}); + +// Error handling middleware (must be last) +app.use(errorHandler); + +export default app; +``` + +#### **backend/src/server.ts** +```typescript +import app from './app'; +import { sequelize } from './models'; +import logger from './utils/logger'; + +const PORT: number = parseInt(process.env.PORT || '5000', 10); + +// Database connection and server start +const startServer = async (): Promise => { + try { + // Test database connection + await sequelize.authenticate(); + logger.info('Database connection established successfully'); + + // Sync models (in development only) + if (process.env.NODE_ENV === 'development') { + await sequelize.sync({ alter: true }); + logger.info('Database models synchronized'); + } + + // Start server + app.listen(PORT, () => { + logger.info(`Server running on port ${PORT}`); + logger.info(`Environment: ${process.env.NODE_ENV}`); + }); + } catch (error) { + logger.error('Unable to start server:', error); + process.exit(1); + } +}; + +// Graceful shutdown +process.on('SIGTERM', async () => { + logger.info('SIGTERM signal received: closing HTTP server'); + await sequelize.close(); + process.exit(0); +}); + +startServer(); +``` + +#### **backend/src/types/express.d.ts** +```typescript +import { JwtPayload } from 'jsonwebtoken'; + +declare global { + namespace Express { + interface Request { + user?: { + userId: string; + email: string; + employeeId: string; + role?: string; + }; + file?: Express.Multer.File; + files?: Express.Multer.File[]; + } + } +} +``` + +#### **backend/src/types/common.types.ts** +```typescript +export enum Priority { + STANDARD = 'STANDARD', + EXPRESS = 'EXPRESS' +} + +export enum WorkflowStatus { + DRAFT = 'DRAFT', + PENDING = 'PENDING', + IN_PROGRESS = 'IN_PROGRESS', + APPROVED = 'APPROVED', + REJECTED = 'REJECTED', + CLOSED = 'CLOSED' +} + +export enum ApprovalStatus { + PENDING = 'PENDING', + IN_PROGRESS = 'IN_PROGRESS', + APPROVED = 'APPROVED', + REJECTED = 'REJECTED', + SKIPPED = 'SKIPPED' +} + +export enum ParticipantType { + SPECTATOR = 'SPECTATOR', + INITIATOR = 'INITIATOR', + APPROVER = 'APPROVER', + CONSULTATION = 'CONSULTATION' +} + +export enum TATStatus { + ON_TRACK = 'ON_TRACK', + APPROACHING = 'APPROACHING', + BREACHED = 'BREACHED' +} + +export interface ApiResponse { + success: boolean; + message: string; + data?: T; + error?: string; + timestamp: Date; +} + +export interface PaginationParams { + page: number; + limit: number; + sortBy?: string; + sortOrder?: 'ASC' | 'DESC'; +} + +export interface PaginatedResponse { + data: T[]; + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + }; +} +``` + +--- + +## 5. Frontend Architecture + +### Complete Frontend Folder Structure + +``` +frontend/ +β”‚ +β”œβ”€β”€ public/ +β”‚ β”œβ”€β”€ index.html +β”‚ β”œβ”€β”€ favicon.ico +β”‚ β”œβ”€β”€ robots.txt +β”‚ └── manifest.json +β”‚ +β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ index.tsx # Application entry point +β”‚ β”œβ”€β”€ App.tsx # Root component +β”‚ β”œβ”€β”€ App.css +β”‚ β”œβ”€β”€ react-app-env.d.ts # React TypeScript declarations +β”‚ β”‚ +β”‚ β”œβ”€β”€ types/ # TypeScript type definitions +β”‚ β”‚ β”œβ”€β”€ index.ts # Main types export +β”‚ β”‚ β”œβ”€β”€ user.types.ts # User types +β”‚ β”‚ β”œβ”€β”€ workflow.types.ts # Workflow types +β”‚ β”‚ β”œβ”€β”€ approval.types.ts # Approval types +β”‚ β”‚ β”œβ”€β”€ document.types.ts # Document types +β”‚ β”‚ β”œβ”€β”€ notification.types.ts # Notification types +β”‚ β”‚ β”œβ”€β”€ common.types.ts # Common types +β”‚ β”‚ └── api.types.ts # API response types +β”‚ β”‚ +β”‚ β”œβ”€β”€ assets/ # Static assets +β”‚ β”‚ β”œβ”€β”€ images/ +β”‚ β”‚ β”œβ”€β”€ icons/ +β”‚ β”‚ β”œβ”€β”€ fonts/ +β”‚ β”‚ └── styles/ +β”‚ β”‚ β”œβ”€β”€ global.css +β”‚ β”‚ β”œβ”€β”€ variables.css +β”‚ β”‚ └── theme.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ components/ # Reusable components +β”‚ β”‚ β”œβ”€β”€ common/ # Generic components +β”‚ β”‚ β”‚ β”œβ”€β”€ Button/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Button.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Button.module.css +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Button.types.ts +β”‚ β”‚ β”‚ β”‚ └── Button.test.tsx +β”‚ β”‚ β”‚ β”œβ”€β”€ Input/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Dropdown/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Modal/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Card/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Table/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Tabs/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Pagination/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Loader/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Notification/ +β”‚ β”‚ β”‚ └── ErrorBoundary/ +β”‚ β”‚ β”‚ +β”‚ β”‚ β”œβ”€β”€ layout/ # Layout components +β”‚ β”‚ β”‚ β”œβ”€β”€ Header/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Header.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ Header.module.css +β”‚ β”‚ β”‚ β”‚ └── Header.types.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ Sidebar/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Footer/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Navigation/ +β”‚ β”‚ β”‚ └── PageLayout/ +β”‚ β”‚ β”‚ +β”‚ β”‚ β”œβ”€β”€ workflow/ # Workflow-specific components +β”‚ β”‚ β”‚ β”œβ”€β”€ TemplateSelector/ +β”‚ β”‚ β”‚ β”œβ”€β”€ BasicInformation/ +β”‚ β”‚ β”‚ β”œβ”€β”€ ApprovalWorkflow/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ ApprovalWorkflow.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ ApproverLevel.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ TATCalculator.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ ApprovalSummary.tsx +β”‚ β”‚ β”‚ β”‚ └── types.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ ParticipantAccess/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ ParticipantAccess.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ SpectatorList.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ UserTagging.tsx +β”‚ β”‚ β”‚ β”‚ └── types.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ DocumentUpload/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ DocumentUpload.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ FilePreview.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ GoogleDocsLink.tsx +β”‚ β”‚ β”‚ β”‚ └── types.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ ReviewSubmit/ +β”‚ β”‚ β”‚ └── WizardStepper/ +β”‚ β”‚ β”‚ +β”‚ β”‚ β”œβ”€β”€ request/ # Request management components +β”‚ β”‚ β”‚ β”œβ”€β”€ RequestCard/ +β”‚ β”‚ β”‚ β”œβ”€β”€ RequestList/ +β”‚ β”‚ β”‚ β”œβ”€β”€ RequestDetail/ +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ RequestOverview.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ WorkflowTab.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ DocumentTab.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ ActivityTab.tsx +β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ TATProgressBar.tsx +β”‚ β”‚ β”‚ β”‚ └── types.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ StatusBadge/ +β”‚ β”‚ β”‚ └── PriorityIndicator/ +β”‚ β”‚ β”‚ +β”‚ β”‚ β”œβ”€β”€ approval/ # Approval action components +β”‚ β”‚ β”‚ β”œβ”€β”€ ApprovalModal/ +β”‚ β”‚ β”‚ β”œβ”€β”€ RejectionModal/ +β”‚ β”‚ β”‚ β”œβ”€β”€ ApprovalHistory/ +β”‚ β”‚ β”‚ └── ConclusionRemark/ +β”‚ β”‚ β”‚ +β”‚ β”‚ β”œβ”€β”€ workNote/ # Work notes / chat components +β”‚ β”‚ β”‚ β”œβ”€β”€ WorkNoteChat/ +β”‚ β”‚ β”‚ β”œβ”€β”€ MessageItem/ +β”‚ β”‚ β”‚ β”œβ”€β”€ MessageComposer/ +β”‚ β”‚ β”‚ β”œβ”€β”€ FileAttachment/ +β”‚ β”‚ β”‚ └── UserMention/ +β”‚ β”‚ β”‚ +β”‚ β”‚ β”œβ”€β”€ notification/ # Notification components +β”‚ β”‚ β”‚ β”œβ”€β”€ NotificationBell/ +β”‚ β”‚ β”‚ β”œβ”€β”€ NotificationList/ +β”‚ β”‚ β”‚ β”œβ”€β”€ NotificationItem/ +β”‚ β”‚ β”‚ └── NotificationSettings/ +β”‚ β”‚ β”‚ +β”‚ β”‚ └── dashboard/ # Dashboard components +β”‚ β”‚ β”œβ”€β”€ DashboardCard/ +β”‚ β”‚ β”œβ”€β”€ StatisticsWidget/ +β”‚ β”‚ β”œβ”€β”€ RecentRequests/ +β”‚ β”‚ └── QuickActions/ +β”‚ β”‚ +β”‚ β”œβ”€β”€ pages/ # Page components (routes) +β”‚ β”‚ β”œβ”€β”€ Auth/ +β”‚ β”‚ β”‚ β”œβ”€β”€ Login.tsx +β”‚ β”‚ β”‚ └── SSOCallback.tsx +β”‚ β”‚ β”œβ”€β”€ Dashboard/ +β”‚ β”‚ β”‚ └── Dashboard.tsx +β”‚ β”‚ β”œβ”€β”€ CreateRequest/ +β”‚ β”‚ β”‚ └── CreateRequest.tsx +β”‚ β”‚ β”œβ”€β”€ MyRequests/ +β”‚ β”‚ β”‚ └── MyRequests.tsx +β”‚ β”‚ β”œβ”€β”€ OpenRequests/ +β”‚ β”‚ β”‚ └── OpenRequests.tsx +β”‚ β”‚ β”œβ”€β”€ ClosedRequests/ +β”‚ β”‚ β”‚ └── ClosedRequests.tsx +β”‚ β”‚ β”œβ”€β”€ RequestDetail/ +β”‚ β”‚ β”‚ └── RequestDetail.tsx +β”‚ β”‚ β”œβ”€β”€ NotFound/ +β”‚ β”‚ β”‚ └── NotFound.tsx +β”‚ β”‚ └── Unauthorized/ +β”‚ β”‚ └── Unauthorized.tsx +β”‚ β”‚ +β”‚ β”œβ”€β”€ redux/ # Redux state management +β”‚ β”‚ β”œβ”€β”€ store.ts # Redux store configuration +β”‚ β”‚ β”œβ”€β”€ hooks.ts # Typed Redux hooks +β”‚ β”‚ β”œβ”€β”€ slices/ +β”‚ β”‚ β”‚ β”œβ”€β”€ authSlice.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ workflowSlice.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ approvalSlice.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ notificationSlice.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ documentSlice.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ workNoteSlice.ts +β”‚ β”‚ β”‚ β”œβ”€β”€ participantSlice.ts +β”‚ β”‚ β”‚ └── uiSlice.ts +β”‚ β”‚ └── middleware/ +β”‚ β”‚ └── apiMiddleware.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ services/ # API service layer +β”‚ β”‚ β”œβ”€β”€ api.ts # Axios instance configuration +β”‚ β”‚ β”œβ”€β”€ auth.service.ts +β”‚ β”‚ β”œβ”€β”€ workflow.service.ts +β”‚ β”‚ β”œβ”€β”€ approval.service.ts +β”‚ β”‚ β”œβ”€β”€ document.service.ts +β”‚ β”‚ β”œβ”€β”€ notification.service.ts +β”‚ β”‚ β”œβ”€β”€ workNote.service.ts +β”‚ β”‚ β”œβ”€β”€ participant.service.ts +β”‚ β”‚ β”œβ”€β”€ dashboard.service.ts +β”‚ β”‚ └── user.service.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ hooks/ # Custom React hooks +β”‚ β”‚ β”œβ”€β”€ useAuth.ts +β”‚ β”‚ β”œβ”€β”€ useWorkflow.ts +β”‚ β”‚ β”œβ”€β”€ useNotification.ts +β”‚ β”‚ β”œβ”€β”€ useDebounce.ts +β”‚ β”‚ β”œβ”€β”€ useInfiniteScroll.ts +β”‚ β”‚ β”œβ”€β”€ useLocalStorage.ts +β”‚ β”‚ └── useWebSocket.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ utils/ # Utility functions +β”‚ β”‚ β”œβ”€β”€ constants.ts +β”‚ β”‚ β”œβ”€β”€ validators.ts +β”‚ β”‚ β”œβ”€β”€ formatters.ts +β”‚ β”‚ β”œβ”€β”€ dateUtils.ts +β”‚ β”‚ β”œβ”€β”€ fileUtils.ts +β”‚ β”‚ β”œβ”€β”€ errorHandler.ts +β”‚ β”‚ └── helpers.ts +β”‚ β”‚ +β”‚ β”œβ”€β”€ routes/ # React Router configuration +β”‚ β”‚ β”œβ”€β”€ AppRoutes.tsx +β”‚ β”‚ β”œβ”€β”€ PrivateRoute.tsx +β”‚ β”‚ └── PublicRoute.tsx +β”‚ β”‚ +β”‚ └── config/ # Frontend configuration +β”‚ β”œβ”€β”€ api.config.ts +β”‚ β”œβ”€β”€ theme.config.ts +β”‚ └── constants.config.ts +β”‚ +β”œβ”€β”€ tests/ # Test files +β”‚ β”œβ”€β”€ components/ +β”‚ β”œβ”€β”€ pages/ +β”‚ β”œβ”€β”€ redux/ +β”‚ β”œβ”€β”€ services/ +β”‚ └── setup.js +β”‚ +β”œβ”€β”€ .env.example +β”œβ”€β”€ .env.development +β”œβ”€β”€ .env.production +β”œβ”€β”€ .eslintrc.json +β”œβ”€β”€ .prettierrc +β”œβ”€β”€ jest.config.js +β”œβ”€β”€ tsconfig.json # TypeScript configuration +β”œβ”€β”€ package.json +└── README.md +``` + +### Key Frontend Files Content Examples + +#### **frontend/tsconfig.json** +```json +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "allowJs": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "allowSyntheticDefaultImports": true, + "isolatedModules": true, + "noEmit": true, + "baseUrl": "./src", + "paths": { + "@/*": ["./*"], + "@components/*": ["components/*"], + "@pages/*": ["pages/*"], + "@services/*": ["services/*"], + "@redux/*": ["redux/*"], + "@hooks/*": ["hooks/*"], + "@utils/*": ["utils/*"], + "@types/*": ["types/*"], + "@config/*": ["config/*"], + "@assets/*": ["assets/*"] + } + }, + "include": ["src"], + "exclude": ["node_modules", "build", "dist"] +} +``` + +#### **frontend/src/types/common.types.ts** +```typescript +export enum Priority { + STANDARD = 'STANDARD', + EXPRESS = 'EXPRESS' +} + +export enum WorkflowStatus { + DRAFT = 'DRAFT', + PENDING = 'PENDING', + IN_PROGRESS = 'IN_PROGRESS', + APPROVED = 'APPROVED', + REJECTED = 'REJECTED', + CLOSED = 'CLOSED' +} + +export interface ApiResponse { + success: boolean; + message: string; + data?: T; + error?: string; + timestamp: string; +} + +export interface PaginatedResponse { + data: T[]; + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + }; +} +``` + +#### **frontend/src/redux/hooks.ts** +```typescript +import { useDispatch, useSelector } from 'react-redux'; +import type { TypedUseSelectorHook } from 'react-redux'; +import type { RootState, AppDispatch } from './store'; + +// Use throughout your app instead of plain `useDispatch` and `useSelector` +export const useAppDispatch: () => AppDispatch = useDispatch; +export const useAppSelector: TypedUseSelectorHook = useSelector; +``` + +#### **frontend/src/redux/store.ts** +```typescript +import { configureStore } from '@reduxjs/toolkit'; +import authReducer from './slices/authSlice'; +import workflowReducer from './slices/workflowSlice'; +import approvalReducer from './slices/approvalSlice'; +import notificationReducer from './slices/notificationSlice'; +import documentReducer from './slices/documentSlice'; +import workNoteReducer from './slices/workNoteSlice'; +import participantReducer from './slices/participantSlice'; +import uiReducer from './slices/uiSlice'; + +export const store = configureStore({ + reducer: { + auth: authReducer, + workflow: workflowReducer, + approval: approvalReducer, + notification: notificationReducer, + document: documentReducer, + workNote: workNoteReducer, + participant: participantReducer, + ui: uiReducer, + }, + middleware: (getDefaultMiddleware) => + getDefaultMiddleware({ + serializableCheck: { + ignoredActions: ['persist/PERSIST'], + }, + }), +}); + +export type RootState = ReturnType; +export type AppDispatch = typeof store.dispatch; +``` + +--- + +## 6. Database Schema Design + +### Complete PostgreSQL Database Schema + +```sql +-- ============================================ +-- RE WORKFLOW MANAGEMENT SYSTEM DATABASE SCHEMA +-- PostgreSQL 16.x +-- ============================================ + +-- Extension for UUID generation +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +-- ============================================ +-- TABLE: users +-- Stores user information from SSO +-- ============================================ +CREATE TABLE users ( + user_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + employee_id VARCHAR(50) UNIQUE NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + display_name VARCHAR(255), + department VARCHAR(100), + designation VARCHAR(100), + phone VARCHAR(20), + profile_picture_url VARCHAR(500), + is_active BOOLEAN DEFAULT TRUE, + last_login TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_users_email ON users(email); +CREATE INDEX idx_users_employee_id ON users(employee_id); +CREATE INDEX idx_users_active ON users(is_active); + +-- ============================================ +-- TABLE: workflow_requests +-- Main table for workflow requests +-- ============================================ +CREATE TABLE workflow_requests ( + request_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_number VARCHAR(50) UNIQUE NOT NULL, -- REQ-2025-00001 + initiator_id UUID NOT NULL REFERENCES users(user_id), + template_type VARCHAR(50) DEFAULT 'CUSTOM', -- CUSTOM, TEMPLATE (future) + title VARCHAR(500) NOT NULL, + description TEXT NOT NULL, + priority VARCHAR(20) NOT NULL CHECK (priority IN ('STANDARD', 'EXPRESS')), + status VARCHAR(50) NOT NULL DEFAULT 'DRAFT' CHECK (status IN ('DRAFT', 'PENDING', 'IN_PROGRESS', 'APPROVED', 'REJECTED', 'CLOSED')), + current_level INTEGER DEFAULT 1, + total_levels INTEGER NOT NULL, + total_tat_hours DECIMAL(10,2) NOT NULL, -- Total TAT in hours + tat_start_date TIMESTAMP WITH TIME ZONE, + tat_end_date TIMESTAMP WITH TIME ZONE, + submission_date TIMESTAMP WITH TIME ZONE, + closure_date TIMESTAMP WITH TIME ZONE, + conclusion_remark TEXT, + is_draft BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_workflow_requests_initiator ON workflow_requests(initiator_id); +CREATE INDEX idx_workflow_requests_status ON workflow_requests(status); +CREATE INDEX idx_workflow_requests_priority ON workflow_requests(priority); +CREATE INDEX idx_workflow_requests_number ON workflow_requests(request_number); +CREATE INDEX idx_workflow_requests_submission_date ON workflow_requests(submission_date); + +-- ============================================ +-- TABLE: approval_levels +-- Defines approval hierarchy levels +-- ============================================ +CREATE TABLE approval_levels ( + level_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + level_number INTEGER NOT NULL, + level_name VARCHAR(255), + approver_id UUID NOT NULL REFERENCES users(user_id), + tat_hours DECIMAL(10,2) NOT NULL, -- TAT for this level in hours + tat_days INTEGER, -- TAT in days (calculated) + status VARCHAR(50) DEFAULT 'PENDING' CHECK (status IN ('PENDING', 'IN_PROGRESS', 'APPROVED', 'REJECTED', 'SKIPPED')), + level_start_time TIMESTAMP WITH TIME ZONE, + level_end_time TIMESTAMP WITH TIME ZONE, + action_date TIMESTAMP WITH TIME ZONE, + comments TEXT, + is_final_approver BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + UNIQUE(request_id, level_number) +); + +CREATE INDEX idx_approval_levels_request ON approval_levels(request_id); +CREATE INDEX idx_approval_levels_approver ON approval_levels(approver_id); +CREATE INDEX idx_approval_levels_status ON approval_levels(status); +CREATE INDEX idx_approval_levels_level_number ON approval_levels(request_id, level_number); + +-- ============================================ +-- TABLE: participants +-- Stores spectators and other participants +-- ============================================ +CREATE TABLE participants ( + participant_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(user_id), + participant_type VARCHAR(50) NOT NULL CHECK (participant_type IN ('SPECTATOR', 'INITIATOR', 'APPROVER', 'CONSULTATION')), + can_comment BOOLEAN DEFAULT TRUE, + can_view_documents BOOLEAN DEFAULT TRUE, + added_by UUID REFERENCES users(user_id), + added_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + UNIQUE(request_id, user_id, participant_type) +); + +CREATE INDEX idx_participants_request ON participants(request_id); +CREATE INDEX idx_participants_user ON participants(user_id); +CREATE INDEX idx_participants_type ON participants(participant_type); + +-- ============================================ +-- TABLE: documents +-- Stores document metadata +-- ============================================ +CREATE TABLE documents ( + document_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + uploaded_by UUID NOT NULL REFERENCES users(user_id), + file_name VARCHAR(500) NOT NULL, + file_type VARCHAR(100) NOT NULL, + file_size BIGINT NOT NULL, -- in bytes + file_path VARCHAR(1000) NOT NULL, -- Cloud storage path + storage_url VARCHAR(1000), -- Public accessible URL + mime_type VARCHAR(100), + is_google_doc BOOLEAN DEFAULT FALSE, + google_doc_url VARCHAR(1000), + is_deleted BOOLEAN DEFAULT FALSE, + version INTEGER DEFAULT 1, + uploaded_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_documents_request ON documents(request_id); +CREATE INDEX idx_documents_uploaded_by ON documents(uploaded_by); +CREATE INDEX idx_documents_deleted ON documents(is_deleted); + +-- ============================================ +-- TABLE: work_notes +-- Chat/communication within workflow +-- ============================================ +CREATE TABLE work_notes ( + note_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(user_id), + message TEXT NOT NULL, + is_priority BOOLEAN DEFAULT FALSE, + has_attachment BOOLEAN DEFAULT FALSE, + mentioned_users UUID[], -- Array of user IDs mentioned + reactions JSONB, -- Store reactions as JSON {emoji: [user_ids]} + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_work_notes_request ON work_notes(request_id); +CREATE INDEX idx_work_notes_user ON work_notes(user_id); +CREATE INDEX idx_work_notes_created ON work_notes(created_at DESC); + +-- ============================================ +-- TABLE: work_note_attachments +-- Attachments in work notes +-- ============================================ +CREATE TABLE work_note_attachments ( + attachment_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + note_id UUID NOT NULL REFERENCES work_notes(note_id) ON DELETE CASCADE, + file_name VARCHAR(500) NOT NULL, + file_type VARCHAR(100) NOT NULL, + file_size BIGINT NOT NULL, + file_path VARCHAR(1000) NOT NULL, + storage_url VARCHAR(1000), + uploaded_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_work_note_attachments_note ON work_note_attachments(note_id); + +-- ============================================ +-- TABLE: activities +-- Activity log for all actions +-- ============================================ +CREATE TABLE activities ( + activity_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + user_id UUID REFERENCES users(user_id), -- NULL for system events + activity_type VARCHAR(100) NOT NULL, -- CREATED, APPROVED, REJECTED, COMMENT_ADDED, etc. + activity_description TEXT NOT NULL, + metadata JSONB, -- Additional data as JSON + is_system_event BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_activities_request ON activities(request_id); +CREATE INDEX idx_activities_user ON activities(user_id); +CREATE INDEX idx_activities_type ON activities(activity_type); +CREATE INDEX idx_activities_created ON activities(created_at DESC); + +-- ============================================ +-- TABLE: notifications +-- User notifications +-- ============================================ +CREATE TABLE notifications ( + notification_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(user_id), + request_id UUID REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + notification_type VARCHAR(100) NOT NULL, -- APPROVAL_REQUEST, COMMENT_MENTION, TAT_WARNING, etc. + title VARCHAR(500) NOT NULL, + message TEXT NOT NULL, + is_read BOOLEAN DEFAULT FALSE, + priority VARCHAR(20) DEFAULT 'NORMAL' CHECK (priority IN ('LOW', 'NORMAL', 'HIGH', 'URGENT')), + action_url VARCHAR(500), + metadata JSONB, + read_at TIMESTAMP WITH TIME ZONE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_notifications_user ON notifications(user_id); +CREATE INDEX idx_notifications_request ON notifications(request_id); +CREATE INDEX idx_notifications_read ON notifications(is_read); +CREATE INDEX idx_notifications_created ON notifications(created_at DESC); + +-- ============================================ +-- TABLE: tat_tracking +-- TAT monitoring and alerts +-- ============================================ +CREATE TABLE tat_tracking ( + tracking_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + level_id UUID REFERENCES approval_levels(level_id) ON DELETE CASCADE, + tat_status VARCHAR(50) NOT NULL CHECK (tat_status IN ('ON_TRACK', 'APPROACHING', 'BREACHED')), + percentage_used DECIMAL(5,2), -- Percentage of TAT used + remaining_hours DECIMAL(10,2), + alert_sent BOOLEAN DEFAULT FALSE, + alert_sent_at TIMESTAMP WITH TIME ZONE, + checked_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_tat_tracking_request ON tat_tracking(request_id); +CREATE INDEX idx_tat_tracking_level ON tat_tracking(level_id); +CREATE INDEX idx_tat_tracking_status ON tat_tracking(tat_status); + +-- ============================================ +-- TABLE: conclusion_remarks +-- AI-generated and edited conclusions +-- ============================================ +CREATE TABLE conclusion_remarks ( + conclusion_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + request_id UUID UNIQUE NOT NULL REFERENCES workflow_requests(request_id) ON DELETE CASCADE, + ai_generated_remark TEXT, + final_remark TEXT NOT NULL, + edited_by UUID REFERENCES users(user_id), + is_edited BOOLEAN DEFAULT FALSE, + generated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + finalized_at TIMESTAMP WITH TIME ZONE +); + +CREATE INDEX idx_conclusion_remarks_request ON conclusion_remarks(request_id); + +-- ============================================ +-- TABLE: audit_logs +-- System audit trail +-- ============================================ +CREATE TABLE audit_logs ( + audit_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID REFERENCES users(user_id), + action VARCHAR(255) NOT NULL, + entity_type VARCHAR(100) NOT NULL, -- REQUEST, DOCUMENT, USER, etc. + entity_id UUID NOT NULL, + old_values JSONB, + new_values JSONB, + ip_address VARCHAR(50), + user_agent TEXT, + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_audit_logs_user ON audit_logs(user_id); +CREATE INDEX idx_audit_logs_entity ON audit_logs(entity_type, entity_id); +CREATE INDEX idx_audit_logs_created ON audit_logs(created_at DESC); + +-- ============================================ +-- TABLE: system_settings +-- Application configuration +-- ============================================ +CREATE TABLE system_settings ( + setting_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + setting_key VARCHAR(255) UNIQUE NOT NULL, + setting_value TEXT NOT NULL, + setting_type VARCHAR(50) NOT NULL, -- STRING, NUMBER, BOOLEAN, JSON + description TEXT, + is_editable BOOLEAN DEFAULT TRUE, + updated_by UUID REFERENCES users(user_id), + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================ +-- FUNCTIONS AND TRIGGERS +-- ============================================ + +-- Function to update updated_at timestamp +CREATE OR REPLACE FUNCTION update_updated_at_column() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ language 'plpgsql'; + +-- Apply trigger to relevant tables +CREATE TRIGGER update_users_updated_at BEFORE UPDATE ON users + FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); + +CREATE TRIGGER update_workflow_requests_updated_at BEFORE UPDATE ON workflow_requests + FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); + +CREATE TRIGGER update_approval_levels_updated_at BEFORE UPDATE ON approval_levels + FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); + +-- Function to auto-generate request number +CREATE OR REPLACE FUNCTION generate_request_number() +RETURNS TRIGGER AS $$ +DECLARE + year_part VARCHAR(4); + sequence_num INTEGER; + new_number VARCHAR(50); +BEGIN + year_part := TO_CHAR(CURRENT_DATE, 'YYYY'); + + SELECT COALESCE(MAX(CAST(SUBSTRING(request_number FROM 10) AS INTEGER)), 0) + 1 + INTO sequence_num + FROM workflow_requests + WHERE request_number LIKE 'REQ-' || year_part || '-%'; + + new_number := 'REQ-' || year_part || '-' || LPAD(sequence_num::TEXT, 5, '0'); + NEW.request_number := new_number; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER generate_request_number_trigger + BEFORE INSERT ON workflow_requests + FOR EACH ROW + WHEN (NEW.request_number IS NULL) + EXECUTE FUNCTION generate_request_number(); + +-- Function to log activities automatically +CREATE OR REPLACE FUNCTION log_activity() +RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + INSERT INTO activities (request_id, user_id, activity_type, activity_description, is_system_event) + VALUES (NEW.request_id, NEW.initiator_id, 'REQUEST_CREATED', 'Workflow request created', TRUE); + ELSIF TG_OP = 'UPDATE' THEN + IF OLD.status != NEW.status THEN + INSERT INTO activities (request_id, activity_type, activity_description, is_system_event, metadata) + VALUES (NEW.request_id, 'STATUS_CHANGED', 'Request status changed from ' || OLD.status || ' to ' || NEW.status, TRUE, + jsonb_build_object('old_status', OLD.status, 'new_status', NEW.status)); + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER log_workflow_activity + AFTER INSERT OR UPDATE ON workflow_requests + FOR EACH ROW + EXECUTE FUNCTION log_activity(); + +-- ============================================ +-- VIEWS FOR REPORTING +-- ============================================ + +-- View: Active requests with current approver +CREATE VIEW vw_active_requests AS +SELECT + wr.request_id, + wr.request_number, + wr.title, + wr.priority, + wr.status, + wr.current_level, + wr.total_levels, + u_initiator.display_name as initiator_name, + u_initiator.department, + al.approver_id as current_approver_id, + u_approver.display_name as current_approver_name, + wr.submission_date, + wr.total_tat_hours, + EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - al.level_start_time))/3600 as elapsed_hours, + al.tat_hours - EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - al.level_start_time))/3600 as remaining_hours +FROM workflow_requests wr +LEFT JOIN users u_initiator ON wr.initiator_id = u_initiator.user_id +LEFT JOIN approval_levels al ON wr.request_id = al.request_id AND al.level_number = wr.current_level +LEFT JOIN users u_approver ON al.approver_id = u_approver.user_id +WHERE wr.status IN ('PENDING', 'IN_PROGRESS'); + +-- View: User notification summary +CREATE VIEW vw_user_notifications AS +SELECT + n.user_id, + COUNT(*) as total_notifications, + COUNT(*) FILTER (WHERE NOT n.is_read) as unread_count, + COUNT(*) FILTER (WHERE n.priority = 'HIGH' OR n.priority = 'URGENT') as high_priority_count +FROM notifications n +GROUP BY n.user_id; + +-- ============================================ +-- INITIAL DATA SEEDING +-- ============================================ + +-- Insert default system settings +INSERT INTO system_settings (setting_key, setting_value, setting_type, description) VALUES +('TAT_REMINDER_THRESHOLD_1', '50', 'NUMBER', 'First TAT reminder at 50% usage'), +('TAT_REMINDER_THRESHOLD_2', '80', 'NUMBER', 'Second TAT reminder at 80% usage'), +('TAT_BREACH_THRESHOLD', '100', 'NUMBER', 'TAT breach alert at 100% usage'), +('MAX_FILE_SIZE_MB', '10', 'NUMBER', 'Maximum file upload size in MB'), +('MAX_APPROVAL_LEVELS', '10', 'NUMBER', 'Maximum number of approval levels'), +('NOTIFICATION_CLEANUP_DAYS', '90', 'NUMBER', 'Clean up read notifications after N days'), +('ENABLE_EMAIL_NOTIFICATIONS', 'true', 'BOOLEAN', 'Enable email notifications'); + +-- ============================================ +-- INDEXES FOR PERFORMANCE OPTIMIZATION +-- ============================================ + +-- Additional composite indexes +CREATE INDEX idx_workflow_requests_status_priority ON workflow_requests(status, priority); +CREATE INDEX idx_approval_levels_request_level ON approval_levels(request_id, level_number); +CREATE INDEX idx_notifications_user_read ON notifications(user_id, is_read); +CREATE INDEX idx_activities_request_created ON activities(request_id, created_at DESC); + +-- Full-text search indexes +CREATE INDEX idx_workflow_requests_title_search ON workflow_requests USING gin(to_tsvector('english', title)); +CREATE INDEX idx_workflow_requests_description_search ON workflow_requests USING gin(to_tsvector('english', description)); + +-- ============================================ +-- DATABASE COMMENTS +-- ============================================ + +COMMENT ON TABLE workflow_requests IS 'Main table storing all workflow requests'; +COMMENT ON TABLE approval_levels IS 'Hierarchical approval levels for each request'; +COMMENT ON TABLE participants IS 'Spectators and other non-approver participants'; +COMMENT ON TABLE documents IS 'Document metadata and storage references'; +COMMENT ON TABLE work_notes IS 'Internal communication and notes'; +COMMENT ON TABLE activities IS 'Audit trail of all request activities'; +COMMENT ON TABLE notifications IS 'User notifications and alerts'; +COMMENT ON TABLE tat_tracking IS 'TAT monitoring and threshold alerts'; +``` + +--- + +## 7. API Endpoints Structure + +### Complete REST API Specification + +#### **Base URL:** `http://api.re-workflow.com/api/v1` + +### 7.1 Authentication APIs + +``` +POST /auth/login # SSO login initiation +POST /auth/callback # SSO callback handler +POST /auth/logout # User logout +GET /auth/me # Get current user details +POST /auth/refresh # Refresh JWT token +``` + +### 7.2 Workflow Management APIs + +``` +GET /workflows # Get all workflows (with filters) +POST /workflows # Create new workflow request +GET /workflows/:id # Get workflow details +PUT /workflows/:id # Update workflow (draft only) +DELETE /workflows/:id # Delete workflow (draft only) +PATCH /workflows/:id/submit # Submit workflow for approval +PATCH /workflows/:id/close # Close workflow with conclusion + +# Filtered lists +GET /workflows/my-requests # Initiator's requests +GET /workflows/open # Open/pending requests +GET /workflows/closed # Closed requests +GET /workflows/assigned-to-me # Requests assigned to current user +``` + +### 7.3 Approval APIs + +``` +GET /workflows/:id/approvals # Get approval hierarchy +POST /workflows/:id/approvals # Add new approver to workflow +PATCH /workflows/:id/approvals/:levelId/approve # Approve request +PATCH /workflows/:id/approvals/:levelId/reject # Reject request +GET /workflows/:id/approvals/current # Get current level info +``` + +### 7.4 Participant APIs + +``` +GET /workflows/:id/participants # Get all participants +POST /workflows/:id/participants # Add participant (spectator) +DELETE /workflows/:id/participants/:participantId # Remove participant +GET /workflows/:id/spectators # Get spectators only +``` + +### 7.5 Document APIs + +``` +GET /workflows/:id/documents # Get all documents +POST /workflows/:id/documents # Upload document +GET /documents/:documentId # Get document details +GET /documents/:documentId/download # Download document +DELETE /documents/:documentId # Delete document +GET /documents/:documentId/preview # Preview document (PDF/images) +``` + +### 7.6 Work Notes APIs + +``` +GET /workflows/:id/work-notes # Get all work notes +POST /workflows/:id/work-notes # Add work note +PUT /work-notes/:noteId # Update work note +DELETE /work-notes/:noteId # Delete work note +POST /work-notes/:noteId/reactions # Add reaction to note +POST /work-notes/:noteId/attachments # Add attachment to note +``` + +### 7.7 Activity Log APIs + +``` +GET /workflows/:id/activities # Get activity timeline +GET /workflows/:id/activities/:type # Filter by activity type +``` + +### 7.8 Notification APIs + +``` +GET /notifications # Get user notifications +GET /notifications/unread # Get unread notifications +PATCH /notifications/:id/read # Mark as read +PATCH /notifications/mark-all-read # Mark all as read +DELETE /notifications/:id # Delete notification +``` + +### 7.9 TAT Tracking APIs + +``` +GET /workflows/:id/tat # Get TAT status +GET /tat/breached # Get breached TAT requests +GET /tat/approaching # Get approaching deadline requests +``` + +### 7.10 Dashboard APIs + +``` +GET /dashboard/stats # Get dashboard statistics +GET /dashboard/recent # Get recent activities +GET /dashboard/pending-actions # Get pending actions count +``` + +### 7.11 User Management APIs + +``` +GET /users # Get all active users (for tagging) +GET /users/search # Search users by name/email +GET /users/:id # Get user details +GET /users/:id/requests # Get user's requests +``` + +### 7.12 Conclusion APIs + +``` +POST /workflows/:id/conclusion/generate # Generate AI conclusion +PUT /workflows/:id/conclusion # Update conclusion +GET /workflows/:id/conclusion # Get conclusion +``` + +--- + +## 8. Authentication & Security + +### 8.1 SSO Integration Architecture + +```typescript +// backend/src/config/sso.ts +export interface SSOConfig { + ssoProvider: string; + authorizationURL: string; + tokenURL: string; + userInfoURL: string; + clientID: string; + clientSecret: string; + callbackURL: string; + scope: string[]; + sessionSecret: string; + jwtSecret: string; + jwtExpiry: string; + refreshTokenExpiry: string; +} + +const ssoConfig: SSOConfig = { + ssoProvider: 'RE_SSO_BRIDGE', + authorizationURL: process.env.SSO_AUTHORIZATION_URL || '', + tokenURL: process.env.SSO_TOKEN_URL || '', + userInfoURL: process.env.SSO_USERINFO_URL || '', + clientID: process.env.SSO_CLIENT_ID || '', + clientSecret: process.env.SSO_CLIENT_SECRET || '', + callbackURL: process.env.SSO_CALLBACK_URL || '', + scope: ['openid', 'profile', 'email'], + sessionSecret: process.env.SESSION_SECRET || '', + jwtSecret: process.env.JWT_SECRET || '', + jwtExpiry: '24h', + refreshTokenExpiry: '7d' +}; + +export default ssoConfig; +``` + +### 8.2 Security Measures + +| Security Layer | Implementation | +|----------------|----------------| +| **Transport Security** | HTTPS/TLS 1.3 | +| **Authentication** | SSO + JWT tokens | +| **Authorization** | Role-based access control (RBAC) | +| **Password Encryption** | bcrypt (cost factor 12) | +| **Token Storage** | HTTP-only cookies + Local storage | +| **CSRF Protection** | CSRF tokens on state-changing operations | +| **XSS Protection** | Input sanitization + Content Security Policy | +| **SQL Injection** | Parameterized queries (Sequelize ORM) | +| **Rate Limiting** | Express rate limiter (100 req/15min) | +| **File Upload Security** | Type validation, size limits, virus scanning | +| **Audit Logging** | All actions logged with user context | +| **Data Encryption** | At-rest (database) and in-transit (TLS) | + +--- + +## 9. Configuration Management + +### 9.1 Backend Environment Variables + +```bash +# backend/.env.example + +# Application +NODE_ENV=development +PORT=5000 +API_VERSION=v1 +BASE_URL=http://localhost:5000 + +# Database +DB_HOST=localhost +DB_PORT=5432 +DB_NAME=re_workflow_db +DB_USER=workflow_user +DB_PASSWORD=secure_password +DB_SSL=false +DB_POOL_MIN=2 +DB_POOL_MAX=10 + +# SSO Configuration +SSO_AUTHORIZATION_URL=https://sso.royalenfield.com/oauth/authorize +SSO_TOKEN_URL=https://sso.royalenfield.com/oauth/token +SSO_USERINFO_URL=https://sso.royalenfield.com/oauth/userinfo +SSO_CLIENT_ID=re_workflow_client +SSO_CLIENT_SECRET=your_sso_client_secret +SSO_CALLBACK_URL=http://localhost:5000/api/v1/auth/callback + +# JWT Configuration +JWT_SECRET=your_jwt_secret_key_here_min_32_chars +JWT_EXPIRY=24h +REFRESH_TOKEN_SECRET=your_refresh_token_secret_here +REFRESH_TOKEN_EXPIRY=7d + +# Session +SESSION_SECRET=your_session_secret_here_min_32_chars + +# Cloud Storage (GCP) +GCP_PROJECT_ID=re-workflow-project +GCP_BUCKET_NAME=re-workflow-documents +GCP_KEY_FILE=./config/gcp-key.json + +# Email Service (Optional) +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_SECURE=false +SMTP_USER=notifications@royalenfield.com +SMTP_PASSWORD=your_smtp_password +EMAIL_FROM=RE Workflow System + +# AI Service (for conclusion generation) +AI_API_KEY=your_ai_api_key +AI_MODEL=gpt-4 +AI_MAX_TOKENS=500 + +# Logging +LOG_LEVEL=info +LOG_FILE_PATH=./logs + +# CORS +CORS_ORIGIN=http://localhost:3000 + +# Rate Limiting +RATE_LIMIT_WINDOW_MS=900000 +RATE_LIMIT_MAX_REQUESTS=100 + +# File Upload +MAX_FILE_SIZE_MB=10 +ALLOWED_FILE_TYPES=pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif + +# TAT Monitoring +TAT_CHECK_INTERVAL_MINUTES=30 +TAT_REMINDER_THRESHOLD_1=50 +TAT_REMINDER_THRESHOLD_2=80 +``` + +### 9.2 Frontend Environment Variables + +```bash +# frontend/.env.example + +# Application +REACT_APP_ENV=development +REACT_APP_NAME=RE Workflow Management +REACT_APP_VERSION=1.0.0 + +# API Configuration +REACT_APP_API_BASE_URL=http://localhost:5000/api/v1 +REACT_APP_API_TIMEOUT=30000 + +# SSO Configuration +REACT_APP_SSO_LOGIN_URL=http://localhost:5000/api/v1/auth/login +REACT_APP_SSO_LOGOUT_URL=http://localhost:5000/api/v1/auth/logout + +# Feature Flags +REACT_APP_ENABLE_NOTIFICATIONS=true +REACT_APP_ENABLE_EMAIL_NOTIFICATIONS=false +REACT_APP_ENABLE_ANALYTICS=true + +# File Upload +REACT_APP_MAX_FILE_SIZE_MB=10 +REACT_APP_ALLOWED_FILE_TYPES=pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif + +# Google Integration +REACT_APP_GOOGLE_API_KEY=your_google_api_key + +# UI Configuration +REACT_APP_THEME_PRIMARY_COLOR=#1976d2 +REACT_APP_ITEMS_PER_PAGE=20 +``` + +--- + +## 10. Deployment Architecture + +### 10.1 Infrastructure on GCP + +Since we have **separate repositories**, each repo has its own Docker configuration. For local development, you can use docker-compose in the backend repository to run the full stack. + +--- + +### 10.1.1 Backend Repository - Docker Compose (`re-workflow-backend/docker-compose.yml`) + +This file runs the full stack for local development: + +```yaml +# re-workflow-backend/docker-compose.yml +# For local development - runs backend + database + +version: '3.8' + +services: + # PostgreSQL Database + postgres: + image: postgres:16-alpine + container_name: re_workflow_db + environment: + POSTGRES_USER: ${DB_USER:-workflow_user} + POSTGRES_PASSWORD: ${DB_PASSWORD:-secure_password} + POSTGRES_DB: ${DB_NAME:-re_workflow_db} + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./database/schema:/docker-entrypoint-initdb.d + networks: + - re_workflow_network + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-workflow_user}"] + interval: 10s + timeout: 5s + retries: 5 + + # Backend API + backend: + build: + context: . + dockerfile: Dockerfile + container_name: re_workflow_backend + environment: + NODE_ENV: development + DB_HOST: postgres + DB_PORT: 5432 + DB_USER: ${DB_USER:-workflow_user} + DB_PASSWORD: ${DB_PASSWORD:-secure_password} + DB_NAME: ${DB_NAME:-re_workflow_db} + PORT: 5000 + ports: + - "5000:5000" + depends_on: + postgres: + condition: service_healthy + volumes: + - ./logs:/app/logs + - ./uploads:/app/uploads + networks: + - re_workflow_network + restart: unless-stopped + +volumes: + postgres_data: + +networks: + re_workflow_network: + driver: bridge +``` + +--- + +### 10.1.2 Production Docker Compose (Optional - For coordinated deployment) + +If you need to deploy both services together using docker-compose, create this in a separate deployment repository or infrastructure folder: + +```yaml +# infrastructure/docker-compose.prod.yml +# For production deployment with separate repositories + +version: '3.8' + +services: + # PostgreSQL Database + postgres: + image: postgres:16-alpine + container_name: re_workflow_db + environment: + POSTGRES_USER: ${DB_USER} + POSTGRES_PASSWORD: ${DB_PASSWORD} + POSTGRES_DB: ${DB_NAME} + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + networks: + - re_workflow_network + restart: unless-stopped + + # Backend API (from separate repo/registry) + backend: + image: gcr.io/re-project/re-workflow-backend:latest + container_name: re_workflow_backend + environment: + NODE_ENV: production + DB_HOST: postgres + ports: + - "5000:5000" + depends_on: + - postgres + volumes: + - backend_logs:/app/logs + - backend_uploads:/app/uploads + networks: + - re_workflow_network + restart: unless-stopped + + # Frontend (from separate repo/registry) + frontend: + image: gcr.io/re-project/re-workflow-frontend:latest + container_name: re_workflow_frontend + environment: + REACT_APP_API_BASE_URL: http://backend:5000/api/v1 + ports: + - "3000:80" + depends_on: + - backend + networks: + - re_workflow_network + restart: unless-stopped + + # Nginx Reverse Proxy + nginx: + image: nginx:alpine + container_name: re_workflow_nginx + ports: + - "80:80" + - "443:443" + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf + - ./nginx/ssl:/etc/nginx/ssl + depends_on: + - backend + - frontend + networks: + - re_workflow_network + restart: unless-stopped + +volumes: + postgres_data: + backend_logs: + backend_uploads: + +networks: + re_workflow_network: + driver: bridge +``` + +--- + +### 10.2 Backend Repository Dockerfile (`re-workflow-backend/Dockerfile`) + +```dockerfile +# re-workflow-backend/Dockerfile + +FROM node:22-alpine AS builder + +WORKDIR /app + +# Copy package files +COPY package*.json ./ +COPY tsconfig.json ./ + +# Install all dependencies (including devDependencies for build) +RUN npm ci + +# Copy source code +COPY src ./src + +# Build TypeScript to JavaScript +RUN npm run build + +# ===================================== +# Production Image +# ===================================== +FROM node:22-alpine + +WORKDIR /app + +# Install PM2 globally +RUN npm install -g pm2 + +# Copy package files +COPY package*.json ./ + +# Install only production dependencies +RUN npm ci --only=production + +# Copy compiled JavaScript from builder +COPY --from=builder /app/dist ./dist + +# Create logs and uploads directories +RUN mkdir -p logs uploads + +# Expose port +EXPOSE 5000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ + CMD node -e "require('http').get('http://localhost:5000/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" + +# Start with PM2 +CMD ["pm2-runtime", "start", "dist/server.js", "--name", "re-workflow-api"] +``` + +--- + +### 10.3 Frontend Repository Dockerfile (`re-workflow-frontend/Dockerfile`) + +```dockerfile +# re-workflow-frontend/Dockerfile + +FROM node:22-alpine AS builder + +WORKDIR /app + +# Copy package files +COPY package*.json ./ + +# Install dependencies +RUN npm ci + +# Copy source code +COPY . . + +# Build application with Vite +RUN npm run build + +# ===================================== +# Production Image with Nginx +# ===================================== +FROM nginx:alpine + +# Copy custom nginx config +COPY nginx/default.conf /etc/nginx/conf.d/default.conf + +# Copy built files from builder (Vite outputs to 'dist' by default) +COPY --from=builder /app/dist /usr/share/nginx/html + +# Expose port +EXPOSE 80 + +# Health check +HEALTHCHECK --interval=30s --timeout=3s \ + CMD wget --quiet --tries=1 --spider http://localhost/ || exit 1 + +CMD ["nginx", "-g", "daemon off;"] +``` + +--- + +### 10.4 CI/CD Pipeline Strategy (Separate Repositories) + +#### **Backend CI/CD (GitHub Actions / GitLab CI)** +```yaml +# .github/workflows/backend-deploy.yml + +name: Backend CI/CD + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +jobs: + test-and-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Install dependencies + run: npm ci + + - name: Run linter + run: npm run lint + + - name: Run tests + run: npm test + + - name: Build TypeScript + run: npm run build + + - name: Build Docker image + run: docker build -t gcr.io/re-project/re-workflow-backend:${{ github.sha }} . + + - name: Push to GCR + run: docker push gcr.io/re-project/re-workflow-backend:${{ github.sha }} +``` + +#### **Frontend CI/CD (GitHub Actions / GitLab CI)** +```yaml +# .github/workflows/frontend-deploy.yml + +name: Frontend CI/CD + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +jobs: + test-and-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Install dependencies + run: npm ci + + - name: Run linter + run: npm run lint + + - name: Run tests + run: npm test + + - name: Build application + run: npm run build + + - name: Build Docker image + run: docker build -t gcr.io/re-project/re-workflow-frontend:${{ github.sha }} . + + - name: Push to GCR + run: docker push gcr.io/re-project/re-workflow-frontend:${{ github.sha }} +``` + +--- + +## 11. Development Setup Instructions + +### 11.1 Prerequisites + +- **Node.js:** v22.x LTS +- **PostgreSQL:** v16.x +- **npm:** v10.x or higher +- **TypeScript:** v5.7.x (installed globally or as dev dependency) +- **Git:** Latest version +- **Docker & Docker Compose** (Optional, for containerized setup) +- **GCP Account** (for cloud storage in production) + +--- + +### 11.2 Local Development Setup (Separate Repositories) + +Since we have **two separate repositories**, you'll need to clone and set up both: + +--- + +#### **BACKEND SETUP** + +#### Step 1: Clone Backend Repository + +```bash +git clone https://github.com/royalenfield/re-workflow-backend.git +cd re-workflow-backend +``` + +#### Step 2: Setup Database + +```bash +# Install PostgreSQL (if not installed) +# For Ubuntu/Debian: +# sudo apt-get install postgresql-16 + +# For macOS: +# brew install postgresql@16 + +# Create database +createdb re_workflow_db + +# Or using psql: +psql -U postgres +CREATE DATABASE re_workflow_db; +\q + +# Run schema +psql -U postgres -d re_workflow_db -f database/schema/schema.sql +``` + +#### Step 3: Configure Backend Environment + +```bash +# Copy environment file +cp .env.example .env + +# Edit .env with your configurations +nano .env # or use your preferred editor + +# Required variables: +# - Database credentials +# - JWT secrets +# - SSO configuration +# - GCP storage keys +``` + +#### Step 4: Install Dependencies & Run Backend + +```bash +# Install dependencies +npm install + +# Run TypeScript type checking +npm run type-check + +# Run migrations (if using Sequelize CLI) +npx sequelize-cli db:migrate + +# Seed data (optional) +npx sequelize-cli db:seed:all + +# Start development server (with hot reload) +npm run dev + +# Backend will run on: http://localhost:5000 +# API Documentation: http://localhost:5000/api-docs +``` + +--- + +#### **FRONTEND SETUP** + +#### Step 1: Clone Frontend Repository + +```bash +# In a new terminal window/tab +git clone https://github.com/royalenfield/re-workflow-frontend.git +cd re-workflow-frontend +``` + +#### Step 2: Configure Frontend Environment + +```bash +# Copy environment file +cp .env.example .env + +# Edit .env with backend API URL +nano .env + +# Set REACT_APP_API_BASE_URL=http://localhost:5000/api/v1 +``` + +#### Step 3: Install Dependencies & Run Frontend + +```bash +# Install dependencies +npm install + +# Run TypeScript type checking +npm run type-check + +# Start development server (Vite with hot reload) +npm run dev + +# Frontend will run on: http://localhost:3000 +``` + +#### Step 4: Access Application + +- **Frontend:** http://localhost:3000 +- **Backend API:** http://localhost:5000 +- **API Documentation:** http://localhost:5000/api-docs +- **Health Check:** http://localhost:5000/health + +--- + +### 11.3 Docker Setup (Alternative - Backend Repository) + +The backend repository includes a docker-compose.yml that runs both database and backend: + +```bash +# From backend repository root +cd re-workflow-backend + +# Copy environment file +cp .env.example .env + +# Edit .env if needed +nano .env + +# Build and start services (backend + PostgreSQL) +docker-compose up --build -d + +# Check logs +docker-compose logs -f + +# Access backend: http://localhost:5000 + +# Stop services +docker-compose down + +# Stop and remove volumes (clean state) +docker-compose down -v +``` + +For frontend Docker setup: + +```bash +# From frontend repository root +cd re-workflow-frontend + +# Copy environment file +cp .env.example .env + +# Build Docker image +docker build -t re-workflow-frontend . + +# Run frontend container +docker run -d -p 3000:80 --name frontend re-workflow-frontend + +# Access frontend: http://localhost:3000 + +# Stop container +docker stop frontend +docker rm frontend +``` + +--- + +### 11.4 Running Tests (Separate Repositories) + +#### Backend Tests +```bash +# From backend repository +cd re-workflow-backend + +npm test # Run all tests (Jest + ts-jest) +npm run test:unit # Unit tests only +npm run test:integration # Integration tests only +npm run test:watch # Watch mode for development +npm run test:coverage # With coverage report + +# Coverage report will be in: coverage/ +# View HTML report: open coverage/lcov-report/index.html +``` + +#### Frontend Tests +```bash +# From frontend repository +cd re-workflow-frontend + +npm test # Run all tests (Vitest) +npm run test:ui # Interactive UI mode (Vitest) +npm run test:coverage # With coverage report + +# Coverage report will be in: coverage/ +``` + +--- + +### 11.5 Code Quality Checks (Separate Repositories) + +#### Backend Code Quality +```bash +# From backend repository +cd re-workflow-backend + +npm run lint # ESLint check (TypeScript rules) +npm run lint:fix # Auto-fix issues +npm run format # Prettier formatting +npm run type-check # TypeScript type checking only (no compilation) + +# Run all quality checks together +npm run lint && npm run type-check && npm test +``` + +#### Frontend Code Quality +```bash +# From frontend repository +cd re-workflow-frontend + +npm run lint # ESLint check (React + TypeScript rules) +npm run lint:fix # Auto-fix issues +npm run format # Prettier formatting +npm run type-check # TypeScript type checking only (no build) + +# Run all quality checks together +npm run lint && npm run type-check && npm test +``` + +--- + +### 11.6 Git Workflow (Separate Repositories) + +Each repository should follow standard Git workflow: + +```bash +# Feature branch workflow +git checkout -b feature/your-feature-name +git add . +git commit -m "feat: add your feature description" +git push origin feature/your-feature-name + +# Create Pull Request on GitHub/GitLab +# After approval and merge: +git checkout main +git pull origin main +``` + +**Branch Strategy:** +- `main` - Production-ready code +- `develop` - Integration branch for features +- `feature/*` - New features +- `bugfix/*` - Bug fixes +- `hotfix/*` - Production hotfixes +- `release/*` - Release preparation + +**Commit Message Convention (Conventional Commits):** +- `feat:` - New feature +- `fix:` - Bug fix +- `docs:` - Documentation changes +- `style:` - Code style changes (formatting) +- `refactor:` - Code refactoring +- `test:` - Test additions or changes +- `chore:` - Build process or tool changes + +--- + +## 12. Additional Documentation Files + +### Package.json Files + +#### **backend/package.json** + +```json +{ + "name": "re-workflow-backend", + "version": "1.0.0", + "description": "Royal Enfield Workflow Management System - Backend API (TypeScript)", + "main": "dist/server.js", + "scripts": { + "start": "node dist/server.js", + "dev": "nodemon --exec ts-node src/server.ts", + "build": "tsc", + "build:watch": "tsc --watch", + "start:prod": "NODE_ENV=production node dist/server.js", + "test": "jest --coverage", + "test:unit": "jest --testPathPattern=tests/unit", + "test:integration": "jest --testPathPattern=tests/integration", + "test:watch": "jest --watch", + "lint": "eslint src/**/*.ts", + "lint:fix": "eslint src/**/*.ts --fix", + "format": "prettier --write \"src/**/*.ts\"", + "type-check": "tsc --noEmit", + "db:migrate": "sequelize-cli db:migrate", + "db:migrate:undo": "sequelize-cli db:migrate:undo", + "db:seed": "sequelize-cli db:seed:all", + "clean": "rm -rf dist" + }, + "dependencies": { + "express": "^4.21.2", + "pg": "^8.13.1", + "pg-hstore": "^2.3.4", + "sequelize": "^6.37.5", + "bcryptjs": "^2.4.3", + "jsonwebtoken": "^9.0.2", + "passport": "^0.7.0", + "passport-jwt": "^4.0.1", + "zod": "^3.24.1", + "multer": "^1.4.5-lts.1", + "winston": "^3.17.0", + "cors": "^2.8.5", + "helmet": "^8.0.0", + "dotenv": "^16.4.7", + "express-rate-limit": "^7.5.0", + "morgan": "^1.10.0", + "@google-cloud/storage": "^7.14.0", + "axios": "^1.7.9", + "node-cron": "^3.0.3" + }, + "devDependencies": { + "@types/express": "^5.0.0", + "@types/node": "^22.10.5", + "@types/bcryptjs": "^2.4.6", + "@types/jsonwebtoken": "^9.0.7", + "@types/passport": "^1.0.16", + "@types/passport-jwt": "^4.0.1", + "@types/multer": "^1.4.12", + "@types/cors": "^2.8.17", + "@types/morgan": "^1.9.9", + "@types/jest": "^29.5.14", + "@types/supertest": "^6.0.2", + "typescript": "^5.7.2", + "ts-node": "^10.9.2", + "ts-node-dev": "^2.0.0", + "nodemon": "^3.1.9", + "jest": "^29.7.0", + "ts-jest": "^29.2.5", + "supertest": "^7.0.0", + "eslint": "^9.17.0", + "@typescript-eslint/eslint-plugin": "^8.19.1", + "@typescript-eslint/parser": "^8.19.1", + "prettier": "^3.4.2", + "sequelize-cli": "^6.6.2", + "sequelize-typescript": "^2.1.7" + }, + "engines": { + "node": ">=22.0.0", + "npm": ">=10.0.0" + } +} +``` + +#### **frontend/package.json** + +```json +{ + "name": "re-workflow-frontend", + "version": "1.0.0", + "description": "Royal Enfield Workflow Management System - Frontend (TypeScript)", + "private": true, + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0", + "react-router-dom": "^7.1.1", + "@reduxjs/toolkit": "^2.5.0", + "react-redux": "^9.2.0", + "@mui/material": "^6.3.0", + "@mui/icons-material": "^6.3.0", + "@emotion/react": "^11.14.0", + "@emotion/styled": "^11.14.0", + "axios": "^1.7.9", + "formik": "^2.4.6", + "yup": "^1.6.3", + "zod": "^3.24.1", + "react-dropzone": "^14.3.5", + "date-fns": "^4.1.0", + "recharts": "^2.15.0", + "react-toastify": "^11.0.2" + }, + "devDependencies": { + "@types/react": "^19.0.6", + "@types/react-dom": "^19.0.2", + "@types/node": "^22.10.5", + "typescript": "^5.7.2", + "vite": "^6.0.7", + "@vitejs/plugin-react": "^4.3.4", + "@testing-library/react": "^16.1.0", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/user-event": "^14.5.2", + "eslint": "^9.17.0", + "@typescript-eslint/eslint-plugin": "^8.19.1", + "@typescript-eslint/parser": "^8.19.1", + "prettier": "^3.4.2", + "vitest": "^2.1.8" + }, + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview", + "test": "vitest", + "test:ui": "vitest --ui", + "test:coverage": "vitest --coverage", + "lint": "eslint src/**/*.{ts,tsx}", + "lint:fix": "eslint src/**/*.{ts,tsx} --fix", + "format": "prettier --write \"src/**/*.{ts,tsx,css}\"", + "type-check": "tsc --noEmit" + }, + "eslintConfig": { + "extends": ["react-app", "react-app/jest"] + }, + "browserslist": { + "production": [">0.2%", "not dead", "not op_mini all"], + "development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"] + }, + "engines": { + "node": ">=22.0.0", + "npm": ">=10.0.0" + } +} +``` + +--- + +## Summary + +This comprehensive project setup guide provides: + +βœ… **Complete Architecture** - System layers, components, and interactions +βœ… **Separate Repository Structure** - Independent backend and frontend repositories for better scalability +βœ… **TypeScript Integration** - Full TypeScript support for backend (Node.js + TS) and frontend (React + TSX) +βœ… **Independent Deployment** - Separate CI/CD pipelines for frontend and backend +βœ… **Folder Structure** - Detailed backend and frontend organization with TypeScript conventions +βœ… **Type Safety** - Comprehensive type definitions, interfaces, and enums for all entities +βœ… **Database Schema** - Full PostgreSQL schema with tables, indexes, triggers, views +βœ… **API Specification** - RESTful endpoints for all features with TypeScript types +βœ… **Security Implementation** - SSO, JWT, encryption, audit trails +βœ… **Configuration Management** - Environment variables and settings with type safety +βœ… **Deployment Architecture** - Docker, docker-compose, GCP deployment with TS compilation +βœ… **Development Setup** - Step-by-step installation and configuration for separate repositories +βœ… **Testing Strategy** - Unit, integration, and E2E testing with ts-jest (backend) and Vitest (frontend) +βœ… **Code Quality** - ESLint with TypeScript parser, Prettier, and best practices +βœ… **Git Workflow** - Branch strategy and commit conventions for both repositories + +### **TypeScript Benefits:** + +🎯 **Type Safety** - Catch errors at compile time, not runtime +🎯 **Better IDE Support** - Enhanced autocomplete, refactoring, and navigation +🎯 **Self-Documenting Code** - Types serve as inline documentation +🎯 **Reduced Bugs** - Strong typing prevents common JavaScript errors +🎯 **Improved Maintainability** - Easier refactoring and code understanding +🎯 **Enterprise-Ready** - Industry standard for large-scale applications + +### **TypeScript Configuration Highlights:** + +- **Backend:** Strict mode enabled with comprehensive type checking (TypeScript 5.7) +- **Frontend:** React 19 + TypeScript with path aliases for clean imports +- **Validation:** Zod 3.24 for runtime type validation (TypeScript-first) +- **ORM:** Sequelize 6.37 with TypeScript support for type-safe database operations +- **Redux:** Fully typed Redux Toolkit 2.5 slices and hooks +- **Build Process:** Vite 6.0 for lightning-fast frontend builds and hot-reload +- **Testing:** Vitest 2.1 for frontend, ts-jest 29.2 for backend + +### **Latest Package Updates (December 2024):** + +πŸ”₯ **React 19.0** - Latest stable version with improved performance and new features +⚑ **Vite 6.0** - Ultra-fast build tool replacing webpack/CRA for better DX +🎯 **TypeScript 5.7** - Latest TypeScript with improved type inference +πŸš€ **Node.js 22 LTS** - Latest LTS release with enhanced performance +πŸ—„οΈ **PostgreSQL 16** - Latest stable database with improved query performance +πŸ“¦ **Redux Toolkit 2.5** - Simplified state management with RTK Query +🎨 **Material-UI 6.3** - Latest MUI with improved theming and components +πŸ”’ **Helmet 8.0** - Latest security middleware +βœ… **ESLint 9** - Latest linting with flat config support + +### **Separate Repository Benefits:** + +πŸš€ **Independent Deployment** - Deploy frontend and backend separately without affecting each other +πŸ‘₯ **Team Ownership** - Clear boundaries between frontend and backend teams +πŸ”„ **CI/CD Flexibility** - Technology-specific pipelines and build processes +πŸ“¦ **Version Control** - Independent versioning and release cycles +πŸ› οΈ **Technology Freedom** - Easier to upgrade or change technologies independently +πŸ”’ **Security** - Better access control and permissions management +⚑ **Scalability** - Scale frontend and backend independently based on load + +**Next Steps:** + +1. **Repository Setup:** + - Create `re-workflow-backend` repository on GitHub/GitLab + - Create `re-workflow-frontend` repository on GitHub/GitLab + - Set up branch protection rules for both repositories + +2. **Development Environment:** + - Install Node.js 22 LTS + TypeScript 5.7 + - Install PostgreSQL 16 + - Configure development tools (VS Code, ESLint, Prettier) + +3. **Backend Repository Initialization:** + - Clone backend repository + - Initialize package.json with latest dependencies + - Set up folder structure as per document + - Configure TypeScript (tsconfig.json) + - Set up database schema and migrations + - Configure SSO integration + +4. **Frontend Repository Initialization:** + - Clone frontend repository + - Initialize package.json with React 19 + Vite 6 + - Set up folder structure as per document + - Configure TypeScript (tsconfig.json) + - Set up Redux Toolkit and Material-UI + +5. **CI/CD Pipeline Setup:** + - Configure GitHub Actions or GitLab CI for backend + - Configure GitHub Actions or GitLab CI for frontend + - Set up Docker build and push to GCR + - Configure automated testing in pipelines + +6. **Development Phase:** + - Backend API development with TypeScript 5.7 + - Frontend components with React 19 + TSX + - Integration testing between frontend and backend + - Implement security measures (SSO, JWT, RBAC) + +7. **Cloud Infrastructure:** + - Set up GCP project + - Configure Cloud SQL (PostgreSQL 16) + - Set up Cloud Storage for documents + - Configure Cloud Run or Kubernetes for deployment + +8. **Testing & QA:** + - Unit tests (backend: Jest, frontend: Vitest) + - Integration tests + - End-to-end tests + - Security testing + - Load testing + +9. **Deployment:** + - Deploy backend to QA environment + - Deploy frontend to QA environment + - User acceptance testing + - Production deployment with monitoring + +10. **Monitoring & Maintenance:** + - Set up application monitoring (Cloud Monitoring) + - Configure log aggregation + - Set up alerts and notifications + - Regular security updates + +--- + +**Document Version:** 1.2 (Separate Repositories - Latest Packages - December 2024) +**Last Updated:** October 16, 2025 +**Prepared By:** .NET Expert Team +**Architecture:** Separate Repositories (Microservices Ready) +**Technology Stack:** Node.js 22 LTS + TypeScript 5.7 + React 19 (TSX) + PostgreSQL 16 +**Repository Structure:** `re-workflow-backend` + `re-workflow-frontend` (Independent) +**Status:** βœ… Ready for Implementation - All Packages Updated to Latest Stable Versions + diff --git a/streamlined_approvals.md b/streamlined_approvals.md new file mode 100644 index 0000000..e27dcfc --- /dev/null +++ b/streamlined_approvals.md @@ -0,0 +1,776 @@ +RE Workflow Management – Not Templatized +System Requirements Specifications +13 - Oct- 2025 +Version 1. 0 +Contents +1 System Overview & Problem Statement +2 Use case examples +3 Intended Audience +4 HiFi Wireframe,Goals and Expected Outcomes +5 Definitions and Acronyms +6 Flow of Application +6.1 High-Level Flow +7 System Features & Requirements +7.1 SSO Login +7.2 Dashboard +7.3 Side Navigation Menu +7.4 Create New Request – Template Selection +7.5 Create New Request – Basic Information +7.6 Create New Request – Approval Workflow +7.7 Create New Request – Participants & Access +7.8 Create New Request – Documents & Attachments +7.9 Create New Request – Review & Submit +7.10 Notifications +7.11 My Requests............................................................................................................. +7.12 Request Detail View +7.13 Request Detail view - Workflow +7.14 Request Detail view - Document +7.15 Request Detail view – Activity +7.16 Add Work Note +7.17 Add Approver & Spectator +7.18 Approve / Reject Request (Popup Window) +7.19 Closure Remark +8 Client Feedback Log (Post-Review Updates) +9 Non-Functional Requirements +10 Technology Matrix +11 Infra requirements & System Hygiene +12 Not in scope +1 System Overview & Problem Statement +The Workflow Management System – Non-Templatized is a strategic digital initiative aimed at +bringing structure, traceability, and efficiency to approval-based processes within Royal Enfield +(RE). + +Currently, most approvals and related communications are handled through emails , which often +results in: + +Unstructured and fragmented approval chains +Loss of critical information due to scattered email threads +Lack of visibility on approval status and ownership +No defined Turnaround Time (TAT) , leading to delays and open-ended tasks +These challenges collectively reduce process transparency , accountability , and decision +efficiency across teams. + +The proposed Workflow Management System – Non-Templatized will address these issues by +providing a centralized, intuitive platform where: + +Users can create requests , +Define custom approval hierarchies , +Set and monitor TATs , and +Track real-time progress and final outcomes. +All workflows will be captured, organized, and closed within a single system of record β€” +ensuring clarity, control, and compliance throughout the process. + +A thoughtfully designed User Interface (UI) will further enhance usability, adoption, and +productivity , ensuring smooth navigation and a clean experience across departments. + +2 Use case examples +The following are some illustrative use cases for the Workflow Management System – Non- +Templatized. These examples represent common approval scenarios within the organization, +though additional use cases may be added over time as business needs evolve: + +Approval for a new office location – involving multiple stakeholders such as facilities, +finance, and leadership teams. +Approval of unbudgeted incentives – requiring justification and review from HR and +finance departments. +Sponsorship or participation in an event – covering approvals from marketing, branding, +and finance. +Purchase of material from a new vendor – requiring validation, procurement, and +financial approvals. +These examples demonstrate the system’s flexibility to handle a wide range of approval +workflows across departments. + +3 Intended Audience +The Workflow Management System – Non-Templatized will be accessible to all Royal Enfield +(RE) employees who have valid SSO (Single Sign-On) credentials. + +Initially, the system will be introduced in a pilot environment for selected users and +departments. Based on feedback and performance, it will later be rolled out organization-wide. + +The system will involve the following user roles : + +Initiator – The user who creates and submits a workflow request. +Participants – Individuals involved in the workflow at different stages or approval levels. +Final Approver – The ultimate authority responsible for approving or rejecting the +workflow request. +Consultation – A user or subject matter expert whom the Final Approver may consult +before making a final decision. +Spectators – Users who are invited to view the workflow for information or transparency +purposes, similar to how individuals are copied (CC’d) on email communications. +This defined role structure ensures clarity, accountability, and collaboration throughout the +workflow lifecycle. + +4 HiFi Wireframe,Goals and Expected Outcomes +Hi-Fi Wireframe: https://sway-dense-03017508.figma.site + +The Workflow Management System – Non-Templatized is designed with a user-centric +approach, supported by a high-fidelity (Hi-Fi) wireframe that visually represents the layout, +navigation flow, and user interactions. + +Through the implementation of this system, Royal Enfield (RE) aims to achieve the +following measurable goals : + +Centralization: Consolidate all approval workflows and related communications within a +single unified platform. +Transparency: Provide real-time visibility into each workflow’s stage, status, and assigned +approvers. +Accountability: Define clear ownership at every stage and maintain a complete audit trail +of all user actions. +Efficiency: Reduce approval cycle times by implementing TAT-based +tracking , automated reminders , and smart notifications. +Traceability: Maintain structured and retrievable records of all approvals to support easy +reference, audit, and reporting. +Scalability: Enable flexible configuration of non-templatized workflows that can adapt to +various departmental and business needs. +User Experience: Deliver a clean, intuitive, and responsive interface that enhances +usability and encourages regular adoption. +5 Definitions and Acronyms +Term Definition +Workflow A sequence of tasks, approvals, or activities linked to a business process. +Non- +Templatized +A flexible structure where each workflow can be created dynamically without a fixed +format. +Admin System user with full privileges. +6 Flow of Application +This section describes the end-to-end flow of the Workflow Management – Non-Templatized +application. It outlines how users interact with the system, how approvals move through +different stages, and how data transitions between modules until final closure. + +6.1 High-Level Flow +Login (SSO Integration) +o Users access the system via the RE SSO Bridge using their organizational +credentials. +o Upon successful authentication, users are redirected to the Dashboard. +Dashboard & Navigation +o The Dashboard provides a summary of pending, approved, and rejected requests. +o The left Side Menu gives access to My Requests , Open Requests , Closed Requests , +and Raise New Request. +Creating a New Request +o User clicks β€œRaise New Request” and chooses between: +β–ͺ Custom Request – Create a flexible, non-templatized workflow. +β–ͺ Existing Template – (Future scope) Use a predefined structure. +o The user proceeds through a 6 - step wizard : +β–ͺ Template Selection +β–ͺ Basic Information +β–ͺ Approval Workflow +β–ͺ Participants & Access +β–ͺ Documents & Attachments +β–ͺ Review & Submit +Defining Approval Workflow +o The user configures approval levels dynamically , assigning approvers via @ +tagging. +o Each approver level has a defined TAT (in hours or days). +o System calculates the total TAT by summing all levels. +o TAT starts only when a request reaches that approver’s level. +Adding Participants +o User can add Spectators (view-only participants) who can comment but not +approve. +o Spectators receive notifications and see the request in read-only mode. +Uploading Documents +o User attaches supporting files (PDF, Word, Excel, PPT, or images) or links Google +Docs/Sheets. +o PDFs and images are previewable , while other formats can be downloaded. +Submitting the Request +o The user reviews all information in the Review & Submit step. +o Once submitted, the request enters the Approval Workflow and notifies the first +approver. +Approval Process +o Approvers receive a notification and can: +β–ͺ Approve Request – Moves to the next level or closes if final approver. +β–ͺ Reject Request – Sends remarks to the initiator and marks as closed. +o Each action requires comments and remarks (mandatory). +o TAT tracking is visible with color-coded status (Green = Within TAT, Yellow = +Approaching Deadline, Red = Breached). +o Auto-reminders are sent at configured thresholds (e.g., 80% TAT usage). +Work Notes & Collaboration +o Participants communicate via the Work Notes (Chat View). +o Supports @mentions, file sharing, and reactions. +o All discussions are stored chronologically and linked to the request. +Activity Tracking +o Every event β€” creation, comment, document upload, approval, rejection, or TAT +alert β€” is captured in the Activity Tab with timestamps. +Request Closure & Conclusion +o After final approval, the request returns to the Initiator with AI-generated +conclusion remarks. +o The initiator reviews, optionally edits, and marks the request as closed. +o The Conclusion Remark summarizing the workflow becomes part of the final +record and appears under: +β–ͺ My Requests (Approved) +β–ͺ Open Requests +β–ͺ Closed Requests +Post-Closure Access & Sharing +o Closed requests remain accessible to all participants and spectators. +o Requests can be shared internally via Add Spectator ; +download permissions apply only to Work Note attachments. +o All actions and comments remain viewable for audit purposes. +7 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?” + +7.1 SSO Login +The system will integrate with the existing RE SSO Bridge to enable secure, seamless login for all +authorized Royal Enfield employees. This ensures unified authentication, eliminating the need +for separate credentials and maintaining compliance with RE’s security standards. + +Width: + +Integrates with the existing RE SSO Bridge for secure authentication. +Allows access only to authorized Royal Enfield employees. +Automatically retrieves user details ( name, employee ID, department ). +Depth: + +Uses token-based authentication and HTTPS for secure sessions. +Handles session timeout and re-authentication per RE’s IT security policy. +Dependency + +SSO implementation guide and sample users are required. +7.2 Dashboard +The Dashboard is an open element that is currently under discussion and will be finalized in later +phases. It is expected to serve as a central view for users to monitor workflow status, pending +approvals, and key metrics once its structure and content are defined. + +7.3 Side Navigation Menu +The Side Menu provides users with quick and consistent navigation across the application. It +includes the following primary sections: + +Dashboard: Overview of workflow activities, key metrics, and pending actions. +My Requests: Displays all workflow requests created by the logged-in user. +Open Requests: Lists all active or in-progress workflows requiring action. These may +include requests initiated by or assigned to the logged-in user. +Closed Requests: Shows all completed or approved workflows for reference. These may +include requests created by or processed by the logged-in user. +Raise New Request: Allows users to initiate and submit a new workflow request. +Width: + +Offers persistent navigation to Dashboard , My Requests , Open Requests , Closed +Requests , and Raise New Request. +Ensures consistent access throughout the system. +Depth: + +Implements active route highlighting and role-based visibility. +Includes search, sort, and filter capabilities. +Supports pagination and stable ID-based navigation to detail screens. +7.4 Create New Request – Template Selection +This screen appears when the user clicks β€œRaise New Request.” It introduces a wizard-style +navigation that guides users through the request creation process in sequential steps. + +Custom Request (Non Templatized): Allows users to create a fully flexible workflow tailored to +unique business needs. + +To initiate the request flow, users must select β€œCustom Request.” The system then progresses +step by step to capture all required details, ensuring clarity and completeness before submission. + +Width: + +Enables users to choose Custom Request (non-templatized) +Displays wizard navigation with progress indicator. +Depth: + +In the current version, only Custom Request is enabled. +Enforces mandatory selection before proceeding. +Saves the chosen configuration as part of the workflow metadata. +Activates after completion of wizard +7.5 Create New Request – Basic Information +In this step, users outline the what, why, and how soon of their request, creating clarity for all +participants involved in the approval process. + +Users are required to enter: + +Request Title: A short and descriptive title that summarizes the purpose of the request +(e.g., Approval for new office location ). +Detailed Description: A comprehensive explanation outlining the need, background, and +expected outcome of the request. +Priority Level: Selection between two options β€” +o Express (Urgent): Includes calendar days in the TAT for faster processing. +o Standard (Default): Includes working days in the TAT for regular processing. +This step ensures that each request is well-defined, prioritized appropriately, and easily +understood by all participants in the approval flow. + +Width: + +Captures core request details : +o Request Title +o Detailed Description +o Priority Level – Express or Standard +Depth: + +Express: Uses calendar days in TAT calculation. +Standard: Uses working days (default). +Supports rich text formatting and pasted tables for better clarity. +Support comprehensive email like formatting features , including table insertion, links, +and text formatting such as bold and italics +β€’ +7.6 Create New Request – Approval Workflow +In this step, users define the approval hierarchy and assign approvers for each level. The number +of approvers is dynamically configurable based on the workflow’s complexity, with a maximum +of ten levels supported. + +Each approver’s Turnaround Time (TAT) must be defined individually in hours or days , +depending on the urgency and scope of the request. The system automatically calculates +the overall TAT by summing the TAT values of all approval levels. + +An important behavior to note: the TAT timer for each participant starts only when the request +reaches that level. Any delay at a previous level impacts only that approver’s TAT and does not +affect subsequent ones. + +Approvers can be tagged using the β€œ@” symbol for easy identification, and each level’s +configuration is summarized in real time under the Approval Flow Summary and TAT +Summary sections for complete visibility. All the taggable users must be available in Active +Directory (AD). + +Width: + +Allows defining a multi-level approval hierarchy with dynamic levels (up to 10). +Each level includes a TAT (in hours or days). +Approvers can be added using @ tagging. +Depth: + +System computes overall TAT by summing all levels. +TAT timer starts only when a level becomes active β€” delays are isolated per level. +Displays real-time Approval Flow Summary and TAT Summary for transparency. +7.7 Create New Request – Participants & Access +The system allows adding Spectators β€” users who can view the workflow, add comments, and +stay informed , but cannot approve or modify the request. Spectators can be added using +the β€œ@” tag , ensuring relevant stakeholders remain in the loop throughout the approval process. + +Width: + +Allows adding Spectators who can view and comment but cannot approve. +Ensures visibility is restricted to participants and spectators only. +Depth: + +@ tagging used to add spectators easily. +Spectators can add comments but have no edit or approval privileges. +All changes are logged in the audit trail. +7.8 Create New Request – Documents & Attachments +In this step, users can upload supporting documents and reference materials required for the +workflow request. The system supports file formats such as PDF, Word, Excel, PowerPoint, and +images , with a maximum upload size of 10 MB per file. + +Users can drag and drop files directly into the upload area or use the Browse Files option to +attach them. + +PDF and image files can be previewed directly within the system. +Other formats such as Word, Excel, or PowerPoint must be downloaded to view. +Additionally, users can associate Google Docs and Google Sheets links as part of the +request for collaborative reference. +This feature ensures that all relevant documents are easily accessible and centralized for +smoother review and approval. + +Width: + +Supports uploads of PDF, Word, Excel, PowerPoint, and image files (up to 10 MB each ). +Allows linking of Google Docs and Google Sheets. +Depth: + +Provides inline preview for PDFs and images. +Other formats must be downloaded to view. +Stores file metadata (name, size, uploader, timestamp) for traceability. +7.9 Create New Request – Review & Submit +This is the final step before the request enters the approval cycle. Users can review all captured +details and ensure the accuracy of every input. The screen provides a structured summary of: + +Request Overview: Displays key attributes such as Request Type, Priority, Workflow +Type, and Request Title. +Basic Information: Shows the request description and priority level entered earlier. +Approval Workflow: Summarizes approval hierarchy, approvers, and defined TAT for +each level. +Participants & Access Control: Lists spectators, permissions, and comment settings. +After verification, the user can either save the request as draft or click β€œSubmit Request.” Once +submitted, the workflow is activated, and notifications are automatically triggered to all +assigned approvers and spectators. + +This final step ensures each request is validated, structured, and complete before moving into +execution. + +Width: + +Displays a complete summary of all entered details before submission: +o Request Overview +o Basic Information +o Approval Workflow +o Participants & Access +Provides options to Save as Draft or Submit Request. +Depth: + +Performs final validation of all required fields. +Computes total TAT and confirms approver hierarchy. +Upon submission, sends notifications to approvers and spectators. +7.10 Notifications +The system provides real-time notifications to keep users informed about workflow activities +and pending actions. Notifications appear through a bell icon in the application header with a +visible count of unread alerts. + +Users receive updates such as: + +Approval Reminders: Alerts when a request requires action or when its SLA/TAT is about +to expire. +Comments and Mentions: Notifications when someone adds a comment or tags the user +in a workflow discussion. +Each notification includes the request ID, message, and timestamp , allowing users to respond +quickly and maintain timely workflow progress. + +Width: + +Centralized bell icon for all system alerts with unread count. +Covers events like: +o Approval assignments +o SLA/TAT warnings +o Comments or mentions +o Status updates and closures +Depth: + +Delivers real-time in-app alerts (optional email integration). +Each alert includes request ID, event type, user, and timestamp. +Supports click navigation , read/unread states , and auto-cleanup of old alerts. +Highlights high-priority or SLA-related notifications distinctly. +7.11 My Requests............................................................................................................. +This screen allows users to view, track, and manage all workflow requests they have created +within the system. It provides a consolidated view of request status, type, and progress for easy +monitoring. + +Width: + +Displays all workflow requests submitted by the logged-in user , categorized as Total, In +Progress, Approved, Rejected, and Draft. +Each record shows critical details like Request Title, Priority (Express/Standard), +Template Type, ID, Submission Date, and Current Level. +Includes search and filter options for status and priority to quickly locate specific +requests. +Depth: + +Each request card provides real-time tracking of the current approver , workflow level , +and estimated completion date. +Supports click navigation to open the detailed workflow view. +Uses color-coded indicators for status identification (e.g., green for Approved, red for +Rejected, yellow for Pending). +Data refreshes upon page load when new requests are created or status updates occur, +ensuring users always see the latest information. +7.12 Request Detail View +This screen allows users to view, review, and act on individual workflow requests. It +consolidates all key information β€” request details, approver actions, documents, and activity +logs β€” into a single, interactive view for efficient decision-making. + +Width: + +Displays comprehensive request details , including title, description, initiator info, +department, and contact details. +Shows priority , TAT progress bar , and remaining time until the TAT expires. +Provides a tab-based layout for: +o Overview (request details and status) +o Workflow (approval hierarchy and progress) +o Documents (uploaded files) +o Activity (comments and action log) +Includes Quick Actions for approvers: Add Work Note, Add Approver, Add Spectator, +Approve Request, and Reject Request. +Lists Spectators with view-only access. +Depth: + +TAT progress bar dynamically updates based on elapsed and remaining time, color-coded +for urgency (e.g., red for nearing expiry). +Each action (approval, rejection, addition of approver/spectator) is logged in +chronology within the activity tab for full traceability. +Approvers can add comments or attachments before taking a decision. +When the request reaches its final approver , the system allows closure and triggers an AI- +generated conclusion remark summarizing the discussion (as per feedback notes). +Page refresh updates data to reflect new comments, document uploads, or action +changes. +7.13 Request Detail view - Workflow +This screen provides a stage-by-stage view of the approval hierarchy within a specific workflow. +It helps users and approvers track progress, review comments, and monitor TAT (Turnaround +Time) performance at each approval level. + +Width: + +Displays each approver level , showing their name, designation, and TAT allocation. +Shows real-time progress of approvals β€” Completed, Pending, Waiting, or Approaching +Deadline. +Includes TAT tracking with both elapsed and remaining time indicators. +Highlights whether each step was completed within or beyond TAT. +Lists approver comments for visibility and decision traceability. +Auto-sends system-generated reminders when TAT thresholds are reached (e.g., 50% or +100% usage). +Depth: + +The system tracks individual TAT usage per approver level , ensuring delays are isolated +to that stage only. +TAT bars dynamically update color (e.g., green for Within TAT , yellow for Approaching +Deadline , red for Breached ). +Automatically sends TAT reminders based on configured thresholds β€” manual reminders +are disabled as per design notes. +Supports chronological logging of every action and comment, visible in the activity trail. +Approvers can add notes, attach files, or escalate to higher levels if TAT expires without +action. +The final approver’s action closes the workflow , triggering summary notifications and AI- +generated closure remarks. +7.14 Request Detail view - Document +This tab provides a centralized space to view, manage, and access all documents attached to the +workflow request. It ensures that approvers and spectators have visibility into all supporting +materials necessary for informed decision-making. + +Width: + +Displays a list of uploaded documents associated with the request, showing: +o File name , size , type/category , uploader , and timestamp. +Supports standard file types such as PDF, Word, Excel, PowerPoint, and images. +Allows users to preview or download files directly from the list. +PDF and image files can be previewed inline ; other file types must be downloaded. +Shows Quick Actions (e.g., Add Work Note, Add Approver, Add Spectator ) on the side +panel for easy context switching. +Depth: + +Ensures document version integrity β€” if the same file name is uploaded again, the latest +version is timestamped and saved separately. +Records audit entries whenever a file is uploaded, deleted, or viewed. +Provides metadata-based filtering (by file type, uploader, or date). +Allows association of Google Docs and Google Sheets links for live collaboration. +Refreshes file list upon page load or when a new document is uploaded , ensuring users +always view the most updated set of attachments. +7.15 Request Detail view – Activity +The Activity Tab serves as a chronological timeline that records every action, event, and update +associated with a workflow request. It provides complete transparency for users to trace +approvals, comments, document uploads, and system-generated notifications. + +Width: + +Displays a real-time activity timeline , including events such as: +o Request creation +o Approvals and rejections +o Comments and notes added +o Document uploads or deletions +o System-generated TAT warnings or reminders +Each activity entry shows: +o Event type , description , timestamp , and initiator name. +Differentiates between user actions (e.g., β€œDocument Added”) and system events (e.g., +β€œTAT Warning Sent”). +Depth: + +Activities are displayed in reverse chronological order , with the latest updates at the top. +Color-coded event icons visually represent action types (e.g., green for approval, red for +warnings). +Automatically logs system-generated events such as TAT breach alerts or reminder +dispatches. +Records file uploads with metadata (file name, uploader, timestamp) for audit +traceability. +Ensures immutable logging β€” entries cannot be modified or deleted once created. +Data refreshes upon page load , ensuring users always view the most updated timeline. +7.16 Add Work Note +The Work Notes section enables participants to communicate and collaborate directly within a +workflow request , ensuring that all discussions, clarifications, and shared files remain tied to the +request record. This eliminates dependency on external email threads and improves traceability. + +Width: + +Displays a chronological chat-style conversation between workflow participants. +Supports @mentions to tag users for feedback or updates. +Allows file sharing within messages β€” uploaded files appear as inline attachments with +download options. +Each message displays the sender’s name, role, timestamp, and message content. +Offers reaction options +Includes a message composer at the bottom with: +o Text box for entering messages (max 2000 characters). +Automatically differentiates roles using colored badges (e.g., Initiator, Approver, +Spectator ). +Depth: + +Messages are displayed in reverse chronological order , preserving a clear dialogue +history. +@mentions trigger system notifications to the tagged users. +Each message is time-stamped, immutable, and stored as part of the request’s +permanent record. +Inline attachments are linked to the Documents Tab for centralized access. +Priority tags (e.g., P – Priority ) appear inline when approvers mark messages as urgent. +The chat interface automatically refreshes upon page load to reflect the latest messages +and reactions. +Chat data remains available throughout the workflow lifecycle and is archived upon +closure. +If there is a query at any level, user will mention it here and ask additional details. +7.17 Add Approver & Spectator +This feature allows users to add new participants β€”either as Approvers or Spectators β€”to an +ongoing workflow request. It provides flexibility for dynamically updating the workflow hierarchy +or visibility list during the approval process. + +Width: + +Displays a modal popup titled β€œAdd Approver” or β€œAdd Spectator,” depending on the +selected action. +Provides a single input field for email address entry using the @ mention convention. +Allows users to search and add participants by email or username. +Includes two action buttons: Confirm (Add) and Cancel. +Approvers: Gain the ability to review, approve, or reject the request. +Spectators: Gain view-only access with the ability to comment and receive notifications. +Both participant types receive automated notifications upon being added. +Depth: + +The Approver is inserted into the approval hierarchy in the defined sequence; +the Spectator is added to the visibility list. +All additions are recorded in the activity timeline for audit and transparency. +Notifications are sent automatically to the newly added users via the system’s alert +service. +Approver TAT begins only when their stage becomes active in the workflow. +The popup closes automatically upon successful addition, refreshing the request view to +reflect the change. +7.18 Approve / Reject Request (Popup Window) +This feature enables approvers to write their decision on a workflow request by either +approving or rejecting it. It ensures that each decision is properly documented with remarks, +creating a transparent and traceable approval trail. + +Width: + +Displays a modal window titled β€œApprove Request” or β€œReject Request.” +Shows key request information: +o Request ID +o Request Title +o Action Type ( Approve or Reject ). +Includes a mandatory Comments & Remarks field (up to 500 characters) for justifying the +decision. +Contains two buttons: +o Approve Request / Reject Request β€” confirms and submits the decision. +o Cancel β€” closes the modal without any action. +Shows a contextual message: +o Approval Confirmation for approval flow. +o Rejection Guidelines encouraging constructive feedback. +Depth: + +Comments are mandatory for both approval and rejection to ensure context for future +reference. +Upon approval: +o The system forwards the request to the next approver in the hierarchy or closes +it if this is the final level. +o If the final approver needs to consult with someone, he can use work note to +specify that user, conclude and put the final closing remarks +o Status updates automatically across all linked screens. +Upon rejection: +o The system sends a notification to the initiator along with rejection remarks. +o The request is marked as β€œRejected” and closed for further approval. +All actions are logged in the Activity Tab with timestamps and user details. +The popup automatically closes upon successful submission , refreshing the view to +display the updated status. +7.19 Closure Remark +This stage marks the final closure of a workflow request after all approvals are completed. +Once the final approver submits their decision, the request automatically returns to the +Initiator with an AI-generated Conclusion Remark summarizing the entire workflow journey. + +The Initiator reviews, optionally edits, and marks the request as closed , completing the +lifecycle. + +Width: + +Becomes available after the final approver’s action is recorded. +Displays an AI-generated Conclusion Remark summarizing: +o Discussion highlights and decision points +o Key approval or rejection reasons +o Notable attachments or supporting references +Allows the Initiator to review and, if required, edit or enhance the remark before final +closure. +Once confirmed, the request status changes to β€œClosed” , and the final remark becomes +part of the permanent workflow record. +The Conclusion Remark is visible under: +o My Requests (Approved) +o Open Requests +o Closed Requests +If no remark exists, a placeholder message is displayed: +β€œNo conclusion remarks added yet. This section will highlight the main points or core +conclusions of the request.” +Depth: + +The AI engine compiles the initial remark using inputs from Work Notes, Approver +Comments, and Activity Logs. +The remark generation occurs immediately after the final approval action is completed. +The Initiator can make final edits or confirmations before closing the request. +Once marked as closed, the remark becomes read-only for all other participants and +spectators. +The finalized conclusion is stored with workflow metadata for audit, compliance, and +reporting. +Closed requests retain full visibility of their conclusion remarks for traceability and +knowledge retention. +8 Client Feedback Log (Post-Review Updates) +This section tracks all client-driven changes, clarifications, or design validations received after +initial wireframe or SRS review. Each point is linked to the relevant feature section for traceability. + +# Client Request / Feedback Response / Action Taken (Rohit) Linked +Feature +Section +1 Remove the TAT +modification option for +approvers, allowing only during +initiation. +Accepted – TAT edit will be available +only at request initiation, not at +approval stages. +Approval +Workflow +2 Display Conclusion +Remarks in My Requests for +approved requests, consistent +with Open and Closed Requests. +Agreed – Will be implemented during +development. To align with design +limitation noted in section 6.20. +My Requests, +Conclusion +Remark +3 Need to see how conclusion +workflow works ; final approver +should have ability to enter +conclusion. +Confirmed – After final approval, +request returns to initiator with AI- +generated comments for review/edit +before closure. +Conclusion +Remark +4 Add restrictive view for sharing +approved requests with non- +participants. +Accepted – To be managed via Work +Notes option with permission control. +Work Notes +5 Clarify sharing and +download permissions for +requests. +Approved – Requests can be shared +internally using Add +Spectator. Download option will be +enabled for Work Notes attachments +only. +Add +Participant, +Work Notes +9 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. +10 Technology Matrix +Component Specification +Database PGSQL (Managed or local instance) +Application Stack Node.js (Backend) + React.js (Frontend) +Authentication RE SSO Bridge +11 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. +12 Not in scope +Anything which comes beyond the scope defined above in terms of Width and depth \ No newline at end of file diff --git a/workflow_complete_flow.mermaid b/workflow_complete_flow.mermaid new file mode 100644 index 0000000..0a2342a --- /dev/null +++ b/workflow_complete_flow.mermaid @@ -0,0 +1,174 @@ +flowchart TD + Start([User Access System]) --> SSO[SSO Login via RE Bridge] + SSO --> Auth{Authentication Successful?} + Auth -->|No| SSO + Auth -->|Yes| Dashboard[Dashboard] + + Dashboard --> NavMenu[Side Navigation Menu] + NavMenu --> MenuChoice{User Selection} + + MenuChoice -->|My Requests| MyReq[View My Requests] + MenuChoice -->|Open Requests| OpenReq[View Open Requests] + MenuChoice -->|Closed Requests| ClosedReq[View Closed Requests] + MenuChoice -->|Raise New Request| RaiseReq[Create New Request] + + %% My Requests Flow + MyReq --> ViewReqDetail[View Request Details] + OpenReq --> ViewReqDetail + ClosedReq --> ViewReqDetail + + %% Create New Request Flow + RaiseReq --> Step1[Step 1: Template Selection] + Step1 --> SelectCustom[Select Custom Request] + SelectCustom --> Step2[Step 2: Basic Information] + + Step2 --> EnterBasic[Enter Request Details: Title, Description, Priority Express/Standard] + EnterBasic --> Step3[Step 3: Approval Workflow] + + Step3 --> DefineApproval[Define Approval Hierarchy: Add Approvers @mention, Set TAT per level, Max 10 levels] + DefineApproval --> CalcTAT[System Calculates Total TAT] + CalcTAT --> Step4[Step 4: Participants & Access] + + Step4 --> AddSpectators[Add Spectators @mention - View-only access] + AddSpectators --> Step5[Step 5: Documents & Attachments] + + Step5 --> UploadDocs[Upload Documents: PDF, Word, Excel, PPT, Images - Max 10MB per file - Link Google Docs/Sheets] + UploadDocs --> Step6[Step 6: Review & Submit] + + Step6 --> ReviewAll[Review All Details: Request Overview, Basic Info, Approval Workflow, Participants, Documents] + ReviewAll --> SubmitChoice{User Action} + + SubmitChoice -->|Save as Draft| Dashboard + SubmitChoice -->|Submit Request| ValidateReq[Validate All Fields] + ValidateReq --> SendNotif[Send Notifications to Approvers & Spectators] + + %% Approval Process Flow + SendNotif --> ApprovalLevel[Request at Approval Level N] + ApprovalLevel --> StartTAT[Start TAT Timer for Level N] + StartTAT --> NotifyApprover[Notify Approver] + + NotifyApprover --> ApproverAction{Approver Action} + ApproverAction -->|View Request| ViewReqDetail + + ViewReqDetail --> DetailTabs{View Tabs} + DetailTabs -->|Overview| ShowOverview[Display Request Details & TAT Progress Bar] + DetailTabs -->|Workflow| ShowWorkflow[Display Approval Hierarchy & TAT Status per Level] + DetailTabs -->|Documents| ShowDocs[Display Uploaded Files & Preview PDF/Images] + DetailTabs -->|Activity| ShowActivity[Display Timeline: All Actions & Events] + + ShowOverview --> QuickActions + ShowWorkflow --> QuickActions + ShowDocs --> QuickActions + ShowActivity --> QuickActions + + QuickActions[Quick Actions Available] --> ActionChoice{Select Action} + + ActionChoice -->|Add Work Note| WorkNote[Add Comment/Message, @mention users, Attach files] + ActionChoice -->|Add Approver| AddApprover[Add New Approver to Hierarchy] + ActionChoice -->|Add Spectator| AddSpectatorAction[Add New Spectator - View-only] + ActionChoice -->|Approve| ApproveModal[Approve Request Modal] + ActionChoice -->|Reject| RejectModal[Reject Request Modal] + + WorkNote --> LogActivity1[Log to Activity Tab] + AddApprover --> LogActivity1 + AddSpectatorAction --> LogActivity1 + LogActivity1 --> SendNotif2[Send Notifications] + SendNotif2 --> ViewReqDetail + + %% Approval Decision Flow + ApproveModal --> EnterApproveComment[Enter Comments & Remarks - Mandatory - 500 chars max] + EnterApproveComment --> ConfirmApprove{Confirm Approval?} + ConfirmApprove -->|Cancel| ViewReqDetail + ConfirmApprove -->|Approve| CheckLevel{Is Final Approver?} + + CheckLevel -->|No| NextLevel[Move to Next Level] + NextLevel --> LogApproval[Log Approval in Activity] + LogApproval --> UpdateStatus1[Update Request Status] + UpdateStatus1 --> ApprovalLevel + + CheckLevel -->|Yes| FinalApproval[Final Approval Recorded] + FinalApproval --> ConsultCheck{Need Consultation?} + ConsultCheck -->|Yes| UseWorkNote[Use Work Note to Consult with Expert] + UseWorkNote --> FinalApproval + ConsultCheck -->|No| GenerateConclusion + + %% Rejection Flow + RejectModal --> EnterRejectComment[Enter Rejection Remarks - Mandatory - 500 chars max] + EnterRejectComment --> ConfirmReject{Confirm Rejection?} + ConfirmReject -->|Cancel| ViewReqDetail + ConfirmReject -->|Reject| LogRejection[Log Rejection in Activity] + LogRejection --> NotifyInitiator[Notify Initiator with Rejection Remarks] + NotifyInitiator --> MarkRejected[Mark Request as Rejected] + MarkRejected --> CloseRejected[Close Request] + CloseRejected --> ArchivedReq[Move to Closed Requests] + + %% TAT Monitoring + StartTAT --> MonitorTAT[Monitor TAT Progress] + MonitorTAT --> TATCheck{TAT Status} + TATCheck -->|Within TAT| GreenStatus[Green Indicator] + TATCheck -->|80% Used| YellowStatus[Yellow Indicator - Send Reminder] + TATCheck -->|Breached| RedStatus[Red Indicator - Send Alert] + + YellowStatus --> ContinueMonitor[Continue Monitoring] + RedStatus --> ContinueMonitor + GreenStatus --> ContinueMonitor + ContinueMonitor --> ApproverAction + + %% Closure Flow + GenerateConclusion[AI Generates Conclusion Remark from Work Notes, Comments, Activity Logs] + GenerateConclusion --> ReturnToInitiator[Return to Initiator] + ReturnToInitiator --> InitiatorReview[Initiator Reviews AI-Generated Conclusion] + InitiatorReview --> EditConclusion{Edit Conclusion?} + + EditConclusion -->|Yes| ModifyConclusion[Edit Conclusion Remark] + EditConclusion -->|No| ConfirmClosure + ModifyConclusion --> ConfirmClosure[Confirm & Close Request] + + ConfirmClosure --> MarkClosed[Mark Request as Closed] + MarkClosed --> FinalRecord[Conclusion Becomes Permanent Record] + FinalRecord --> VisibleIn[Visible in: My Requests, Open Requests, Closed Requests] + VisibleIn --> PostClosure + + %% Post-Closure Access + PostClosure[Post-Closure Access] --> AccessibleTo[Accessible to All Participants & Spectators] + AccessibleTo --> ShareOptions{Sharing Options} + ShareOptions -->|Add Spectator| ShareInternal[Share Internally via Add Spectator] + ShareOptions -->|Download| DownloadWorkNotes[Download Work Note Attachments Only] + + ShareInternal --> AuditTrail[All Actions Viewable for Audit] + DownloadWorkNotes --> AuditTrail + + %% Notification System + SendNotif -.->|In-App Alert| BellIcon[Bell Icon Notification with Count] + SendNotif2 -.->|In-App Alert| BellIcon + YellowStatus -.->|Auto Reminder| BellIcon + RedStatus -.->|Auto Alert| BellIcon + NotifyInitiator -.->|In-App Alert| BellIcon + ReturnToInitiator -.->|In-App Alert| BellIcon + + BellIcon --> NotifDetails[Show Request ID, Message & Timestamp] + NotifDetails --> ClickToView[Click to View Request] + ClickToView --> ViewReqDetail + + AuditTrail --> End([Workflow Complete]) + ArchivedReq --> End + + style Start fill:#e1f5ff + style SSO fill:#fff3cd + style Dashboard fill:#d4edda + style Step1 fill:#cfe2ff + style Step2 fill:#cfe2ff + style Step3 fill:#cfe2ff + style Step4 fill:#cfe2ff + style Step5 fill:#cfe2ff + style Step6 fill:#cfe2ff + style ApproveModal fill:#d1e7dd + style RejectModal fill:#f8d7da + style GenerateConclusion fill:#d1ecf1 + style MarkClosed fill:#d4edda + style End fill:#e1f5ff + style GreenStatus fill:#d1e7dd + style YellowStatus fill:#fff3cd + style RedStatus fill:#f8d7da + style BellIcon fill:#ffeaa7 + diff --git a/~$yal Enfield Documentation.docx b/~$yal Enfield Documentation.docx deleted file mode 100644 index 55a8afe..0000000 Binary files a/~$yal Enfield Documentation.docx and /dev/null differ