# 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<void> => {
  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<T = any> {
  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<T> {
  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<T = any> {
  success: boolean;
  message: string;
  data?: T;
  error?: string;
  timestamp: string;
}

export interface PaginatedResponse<T> {
  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<RootState> = 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<typeof store.getState>;
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 <notifications@royalenfield.com>

# 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

