# RE Workflow Management System - Task Breakdown
## Sprint Planning & Task Distribution (Frontend & Backend)

**Version:** 1.1  
**Date:** October 23, 2025  
**Project:** RE Workflow Management System (Non-Templatized)  
**Authentication:** Standard Login Flow (SSO deferred)  
**Current Status:** Frontend UI from Figma implemented, functionality integration in progress

---

## Table of Contents
1. [Project Overview](#project-overview)
2. [SSO Authentication Approach](#sso-authentication-approach) 🔐
3. [Frontend Work Reality Check](#frontend-work-reality-check) ⚠️ **READ THIS FIRST**
4. [Sprint Structure](#sprint-structure)
5. [Backend Tasks](#backend-tasks)
6. [Frontend Tasks](#frontend-tasks)
7. [Task Dependencies](#task-dependencies)
8. [Timeline & Milestones](#timeline--milestones)

📖 **For Detailed Sprint Explanations:** See separate file `RE_Workflow_Detailed_Sprint_Guide.md`

---

## Project Overview

### Technology Stack
- **Backend:** Node.js 22 LTS + TypeScript 5.7 + Express.js + PostgreSQL 16
- **Frontend:** React 19 + TypeScript (TSX) + Material-UI 6.3 + Redux Toolkit 2.5
- **Authentication:** Standard Email/Password Login (JWT-based)

### Authentication Approach
- 🔄 **SSO Login (RE SSO Bridge):** Primary authentication method (awaiting final confirmation)
  - **No Login/Signup Screens:** SSO handles authentication externally
  - **Figma Note:** No login/signup screens in Figma (not needed for SSO)
  - **User Flow:** 
    1. User clicks "Login" → Redirects to RE SSO Bridge
    2. User authenticates with RE credentials (handled by SSO)
    3. SSO redirects back to app with token
    4. App validates token and creates session
  - **Frontend Work:** Minimal (just SSO callback handler)
  - **No Registration Flow:** Users are provisioned in Active Directory, auto-synced to app
  
- ⚠️ **Fallback Plan (if SSO delayed):** Standard email/password login (temporary)
  - Only if SSO integration is delayed or unavailable
  - Can be built in 3-4 days as temporary solution
  - Will be replaced by SSO once available

### Current Project Status (As of October 23, 2025)

#### Frontend Status 🔄
- **Figma UI Extraction:** 80% complete (includes mobile responsive)
  - ⚠️ **Important:** This is just UI with dummy data, NO API integration yet
  - When 100% extraction done: Still just static UI components
  - All UI is mobile responsive (320px - 1920px)
- **Dependency Packages:** ✅ All resolved and installed
- **Work Note Feature:** UI complete + partial functionality (document selection, emoji support working)
- **Current Status:** 
  - ✅ UI Components: 80% extracted
  - ❌ API Integration: 0% (not started)
  - ❌ Redux Integration: 0% (not started)
  - ❌ Form Validations: 0% (not started)
  - ❌ Business Logic: 0% (not started)

**Reality Check:** 
- Figma extraction ≠ Feature complete
- UI extraction = Just visual components with dummy data
- Still need: API integration, state management, validations, error handling, loading states

**Actual Frontend Completion:** ~20% (UI only, no functionality)

#### Backend Status 🔄
- **Repository Setup:** 70% in progress
- **Database Schema:** Ready to implement (0% done)
- **API Development:** Not started (0% done)
- **Estimated Completion:** Following planned timeline

**Overall Project Completion:** ~10% (mostly UI extraction)

---

## 🔐 SSO Authentication Approach

### How SSO Login Works (No Login/Signup Screens Needed)

#### User Authentication Flow:

```
┌─────────────────────────────────────────────────────────────┐
│  User visits app → https://workflow.royalenfield.com        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  App detects no session → Redirects to RE SSO Bridge        │
│  https://sso.royalenfield.com/oauth/authorize?client_id=... │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  User enters RE credentials (email + password)               │
│  SSO validates against Active Directory                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  SSO redirects back to app with authorization code           │
│  https://workflow.royalenfield.com/auth/callback?code=XXX   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  App backend exchanges code for access token                 │
│  Gets user info from SSO (name, email, employee ID, dept)   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  App creates/updates user in local database                  │
│  Generates JWT token for app session                         │
│  Returns JWT to frontend                                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  Frontend stores JWT and redirects to Dashboard              │
│  User is now logged in!                                      │
└─────────────────────────────────────────────────────────────┘
```

#### What This Means for Development:

**Frontend (Minimal Work):**
- ❌ No login page (SSO handles it)
- ❌ No signup page (users come from Active Directory)
- ❌ No password reset page (SSO handles it)
- ✅ Just need SSO callback page (`/auth/callback`)
- ✅ Protected route guards (redirect to SSO if not authenticated)
- ✅ Logout functionality (clear session + redirect to SSO logout)

**Backend:**
- ✅ SSO integration (Passport.js with OAuth2 strategy)
- ✅ User sync from Active Directory
- ✅ JWT token generation for app sessions
- ✅ Session management
- ✅ User profile sync and updates

**Sprint 1 Focus:**
- Configure SSO OAuth2 integration
- Handle SSO callback
- Sync users from AD to local database
- Generate JWT for app sessions
- Implement protected routes

**Time Saved:**
- No need to build login/signup/password reset screens
- No password hashing/validation
- No email verification
- **Estimated time saved:** 3-4 days frontend, 2-3 days backend

---

## ⚠️ Frontend Work Reality Check

### 🎨 Understanding "Figma UI Extraction" vs "Feature Complete"

This section is **CRITICAL** to understand before reviewing tasks and timelines.

#### What Figma Extraction Gives You:

**✅ Visual Components (80% Complete):**
```
login-page/
├── login-form.tsx          ← Has HTML structure
│   ├── <input email>       ← Looks like email input
│   ├── <input password>    ← Looks like password input
│   └── <button>Login</button>  ← Looks like button
└── login-page.css          ← Has all styling

PROBLEM: Form doesn't actually do anything!
- Email input accepts any text (even "abc123")
- Password input has no strength check
- Login button has no onClick handler
- No API call on submit
- No error handling
- No loading state
- No validation messages
- Just pretty, non-functional HTML
```

**Example: My Requests Page from Figma**
```tsx
// What Figma gives you (80% done):
const MyRequests = () => {
  const dummyData = [
    { id: 1, title: "Approval for office", status: "Pending" },
    { id: 2, title: "Budget approval", status: "Approved" }
  ];
  
  return (
    <div className="requests-page">
      {dummyData.map(req => (
        <RequestCard data={req} />  {/* Pretty card with dummy data */}
      ))}
    </div>
  );
};

// What you ACTUALLY need (the other 84%):
const MyRequests = () => {
  const dispatch = useAppDispatch();  // ← Need Redux
  const { workflows, loading, error } = useAppSelector(state => state.workflow);  // ← Need Redux
  const [filters, setFilters] = useState({});  // ← Need state management
  
  useEffect(() => {
    // ← Need API integration
    dispatch(fetchMyWorkflows(filters));
  }, [filters]);
  
  if (loading) return <LoadingSkeleton />;  // ← Need loading state
  if (error) return <ErrorState message={error} />;  // ← Need error handling
  if (!workflows.length) return <EmptyState />;  // ← Need empty state
  
  return (
    <div className="requests-page">
      <SearchBar onSearch={handleSearch} />  {/* ← Need search logic */}
      <FilterPanel filters={filters} onChange={setFilters} />  {/* ← Need filter logic */}
      {workflows.map(req => (
        <RequestCard 
          data={req} 
          onClick={() => navigate(`/workflows/${req.id}`)}  {/* ← Need navigation */}
        />
      ))}
      <Pagination 
        page={page} 
        total={totalPages} 
        onChange={handlePageChange}  {/* ← Need pagination */}
      />
    </div>
  );
};
```

---

#### What You Still Need to Build (84% of Frontend Work):

**1. Redux State Management (20% of total work = 7 days)**
- Create Redux store configuration
- Create 8 Redux slices (auth, workflow, approval, notification, etc.)
- Define initial states
- Create reducers for each action
- Create async thunks for API calls
- Setup Redux persist
- Configure Redux DevTools
- **Without this:** Components can't share data, no global state

**2. API Integration (30% of total work = 12 days)**
- Configure Axios instance
- Create API service files (9 files)
- Setup request/response interceptors
- Handle JWT token injection
- Handle token refresh
- Connect every page to its API:
  - Login → POST /api/v1/auth/login
  - Register → POST /api/v1/auth/register
  - Create Workflow → POST /api/v1/workflows
  - Approve → PATCH /api/v1/workflows/:id/approve
  - (And 50+ more API calls)
- Handle API errors
- Handle network failures
- **Without this:** App is just a pretty shell with fake data

**3. Form Validations (15% of total work = 5 days)**
- Email format validation
- Password strength validation
- Required field validation
- Max/min length validation
- Number validation (TAT hours)
- File type validation (documents)
- File size validation (10MB max)
- Custom validators (employee ID format, etc.)
- Error message display
- Real-time validation as user types
- **Without this:** Users can submit invalid data, app crashes

**4. Business Logic (15% of total work = 5 days)**
- TAT calculation (working days vs calendar days)
- Request number generation (display)
- Date formatting and calculations
- File size formatting (bytes to MB)
- User search and @mention logic
- Approval level sequencing
- Status badge color logic
- Priority level handling
- **Without this:** App has no "brain"

**5. Error Handling (10% of total work = 3 days)**
- API error handling (400, 401, 403, 404, 500)
- Network error handling (offline, timeout)
- Form validation errors
- Display error messages (toast notifications)
- Error boundaries (catch React crashes)
- Retry logic for failed requests
- User-friendly error messages
- **Without this:** App crashes and users are confused

**6. Loading States (10% of total work = 3 days)**
- Loading spinners for API calls
- Skeleton loaders for data fetching
- Progress bars for file uploads
- Disable buttons during loading
- Overlay loaders for modals
- Page transition loaders
- **Without this:** Users don't know app is working

**7. Testing (10% of total work = 5 days)**
- Component unit tests
- Redux slice tests
- Integration tests
- E2E tests
- **Without this:** Bugs in production

---

### 📊 Frontend Effort Distribution Chart

```
Total Frontend Work = 100%
├─ Visual UI (Figma Extraction): 20% ── [████████████████████] 80% DONE
├─ Redux State Management:      20% ── [░░░░░░░░░░░░░░░░░░░░]  0% DONE
├─ API Integration:              30% ── [░░░░░░░░░░░░░░░░░░░░]  0% DONE
├─ Validations & Logic:          20% ── [░░░░░░░░░░░░░░░░░░░░]  0% DONE
└─ Testing & Polish:             10% ── [░░░░░░░░░░░░░░░░░░░░]  0% DONE

Current Completion: 16% (0.80 × 0.20 = 0.16)
Remaining Work: 84%
```

---

### 🎯 Typical Frontend Task Breakdown (Example: Login Page)

**What Figma Gives You (20% - Already Done):**
- Login page layout ✅
- Email input field (looks pretty) ✅
- Password input field (looks pretty) ✅
- Login button (styled) ✅
- Dummy text and placeholder ✅
- **Time saved:** ~2 hours

**What You Still Need to Build (80% - Todo):**

**1. Redux Integration (2 hours):**
- Create authSlice actions
- Create login async thunk
- Handle loading/success/error states
- Update Redux store on login

**2. API Integration (1 hour):**
- Create auth.service.ts
- Implement login API call
- Handle API response
- Extract JWT token

**3. Form Validation (1.5 hours):**
- Validate email format
- Check required fields
- Show validation errors
- Disable submit if invalid

**4. Business Logic (1 hour):**
- Handle form submit
- Store JWT in localStorage
- Redirect to dashboard on success
- Clear form on error

**5. Error Handling (1 hour):**
- Handle wrong credentials (401)
- Handle network errors
- Show error toast
- Display field-level errors

**6. Loading State (0.5 hours):**
- Show spinner on button
- Disable form during login
- Show loading overlay

**7. Testing (1 hour):**
- Test valid login
- Test invalid credentials
- Test validation

**Total Time for Login Page:**
- Figma UI: 2 hours ✅ (Done)
- Functionality: 8 hours ❌ (Todo)
- **Login page is only 20% done!**

**This pattern applies to EVERY page in the app!**

---

### 💡 Key Takeaway for Frontend Team

**"Having the UI" is like having a car body without:**
- Engine (Redux)
- Transmission (API integration)
- Steering (Navigation & routing)
- Brakes (Error handling)
- Fuel (Data from backend)
- Dashboard instruments (Loading states)

**It looks like a car, but you can't drive it!**

Similarly:
- Your app looks complete
- But nothing actually works yet
- You need to build all the "internal machinery"

**Plan for 7-8 weeks of integration work, not 2-3 weeks!**

---

### 📋 Realistic Frontend Task List (With Current Status)

| Category | Total Tasks | Figma Done | Still Todo | Time Needed |
|----------|-------------|------------|------------|-------------|
| **UI Components** | 40 components | 32 (80%) | 8 (20%) | 1-2 days |
| **Redux Slices** | 8 slices | 0 (0%) | 8 (100%) | 2-3 days |
| **API Services** | 9 service files | 0 (0%) | 9 (100%) | 1 day |
| **Page Integration** | 15 pages | 0 (0%) | 15 (100%) | 12 days |
| **Form Validations** | 20 forms | 0 (0%) | 20 (100%) | 4 days |
| **Route Guards** | 12 routes | 0 (0%) | 12 (100%) | 1 day |
| **Error Handling** | All pages | 0 (0%) | All (100%) | 3 days |
| **Loading States** | All pages | 0 (0%) | All (100%) | 3 days |
| **Testing** | 40 tests | 0 (0%) | 40 (100%) | 5 days |
| **TOTAL** | | **16%** | **84%** | **~35 days** |

---

## Revised Sprint Structure (Week-Based Timeline)

### 🔄 Sprint 0: Project Setup & Infrastructure (PARTIALLY COMPLETE)
**Week:** 1  
**Backend Status:** 🔄 70% In Progress  
**Frontend Status:** 🔄 80% In Progress (UI extracted, NO functionality)  
**Goal:** Development environment ready with basic architecture

**Frontend Reality:**
- ✅ UI Components extracted from Figma: 80%
- ✅ Mobile responsive: Done
- ✅ Packages installed: Done
- ❌ API integration: Not started
- ❌ Redux connected: Not started
- ❌ Forms functional: Not started

---

### 🔄 Sprint 1: SSO Authentication & User Management (CURRENT WEEK)
**Week:** 2-3  
**Backend:** SSO integration, user sync, session management  
**Frontend:** SSO callback handler, protected routes, user profile  
**Goal:** Working SSO authentication system

**Note:** No login/signup screens needed (SSO handles authentication externally)

---

### Sprint 2: Core Workflow Creation 
**Weeks:** 3-4 (2 weeks)  
**Backend:** Workflow APIs, approval hierarchy  
**Frontend:** Connecting wizard UI to backend  
**Goal:** Complete workflow creation flow

---

### Sprint 3: Approval & Workflow Actions
**Weeks:** 5-6 (2 weeks)  
**Backend:** Approval logic, TAT tracking, notifications  
**Frontend:** Request management, approval/reject modals  
**Goal:** Full approval workflow operational

---

### Sprint 4: Documents & Work Notes
**Week:** 7  
**Backend:** Document storage, work notes APIs  
**Frontend:** ✅ Work notes UI complete, connect to backend  
**Goal:** Collaboration features working

---

### Sprint 5: Dashboard & Reporting
**Week:** 8  
**Backend:** Dashboard APIs, AI integration  
**Frontend:** Charts, statistics, filters  
**Goal:** Analytics and dashboards complete

---

### Sprint 6: Testing & Deployment
**Weeks:** 9-10 (2 weeks)  
**Backend:** Testing, optimization, deployment  
**Frontend:** Testing, performance optimization, deployment  
**Goal:** Production-ready application

---

## 📖 Sprint Summaries

**⚠️ For Detailed Code Examples, Step-by-Step Guides, and Implementation Details:**  
**See separate document:** `RE_Workflow_Detailed_Sprint_Guide.md`

This section provides brief summaries only. The detailed guide contains:
- Complete code examples for each feature
- Step-by-step implementation instructions
- Validation logic and error handling
- API integration patterns
- Redux state management examples
- 100+ code snippets

---

### 🚀 Sprint 0: Project Setup & Infrastructure (Week 1)
**Status:** Frontend 🔄 80% Complete (UI Only) | Backend 🔄 70% Complete

#### What This Sprint Delivers:
This sprint establishes the foundation for the entire project. It's about setting up the development environment, tools, and basic architecture.

#### ⚠️ IMPORTANT: Figma UI Extraction Reality
**What "80% UI Extracted" Actually Means:**
- ✅ Visual components created (buttons, inputs, cards, modals)
- ✅ Layout structure in place (header, sidebar, content areas)
- ✅ Mobile responsive design (320px to 1920px)
- ✅ Styling complete (colors, fonts, spacing)
- ✅ Dummy data displayed (hardcoded text, placeholder images)

**What is NOT Included in "UI Extraction":**
- ❌ API integration (no backend calls)
- ❌ Redux state management (no global state)
- ❌ Form validations (fields don't validate input)
- ❌ Error handling (no error messages)
- ❌ Loading states (no spinners/skeletons)
- ❌ Business logic (no calculations, no workflows)
- ❌ Data persistence (nothing saves to database)
- ❌ Authentication (login form visible but doesn't work)
- ❌ Navigation guards (routes not protected)
- ❌ Dynamic data (everything is static/hardcoded)

**Real Effort Distribution:**
- Figma UI Extraction: 20% of total frontend work
- API Integration: 30% of total frontend work
- State Management: 20% of total frontend work
- Validations & Logic: 20% of total frontend work
- Testing & Polish: 10% of total frontend work

**Translation:**
- 80% UI extracted = 16% of total frontend work done (0.80 × 0.20)
- Still need: 84% of actual functionality to be built

#### Backend Deliverables:

**1. Repository & Environment Setup (BE-001)**
- Create GitHub/GitLab repository with proper structure
- Initialize Node.js 22 LTS project with TypeScript 5.7
- Setup complete folder structure:
  - `src/` for source code
  - `src/controllers/`, `src/services/`, `src/models/`
  - `src/middlewares/`, `src/routes/`, `src/utils/`
  - `tests/` for unit and integration tests
  - `database/` for schema and migrations
- Configure `tsconfig.json` with strict TypeScript settings
- Setup `.env.example` with all required environment variables
- Configure `.gitignore`, `.eslintrc`, `.prettierrc`
- Install all dependencies (Express, Sequelize, JWT, bcrypt, etc.)

**2. Database Setup & Schema (BE-002) - CRITICAL**
- Install and configure PostgreSQL 16
- Create database `re_workflow_db`
- Implement complete database schema with 15+ tables:
  - `users` - User accounts and profiles
  - `workflow_requests` - Main workflow data
  - `approval_levels` - Approval hierarchy
  - `participants` - Spectators and other participants
  - `documents` - Document metadata
  - `work_notes` - Chat/collaboration messages
  - `activities` - Audit trail and activity log
  - `notifications` - User notifications
  - `tat_tracking` - TAT monitoring
  - `conclusion_remarks` - AI-generated conclusions
  - And more...
- Create database triggers for auto-generation of request numbers
- Create database views for reporting (active requests, notifications)
- Add indexes for performance optimization
- Insert initial system settings

**3. Core Backend Configuration (BE-003)**
- Setup Express.js application with TypeScript
- Configure essential middleware:
  - `helmet` - Security headers
  - `cors` - Cross-origin resource sharing
  - `express.json()` - JSON body parsing
  - `morgan` - HTTP request logging
- Setup Winston logger with file rotation (error.log, combined.log)
- Create centralized error handling middleware
- Setup health check endpoint (`/health`)
- Configure graceful shutdown handlers

**4. Sequelize ORM Setup (BE-004)**
- Configure Sequelize connection to PostgreSQL
- Create TypeScript models for all database tables:
  - User model with associations
  - WorkflowRequest model with relationships
  - ApprovalLevel, Participant, Document models
  - Work notes, activities, notifications models
- Define all model associations (one-to-many, many-to-many)
- Test database connectivity
- Setup model synchronization for development

#### Frontend Deliverables:

**1. Current Status of Frontend Tasks (FE-001 to FE-007)**

**What's Actually Done (80%):**
- ✅ Repository with React 19 + Vite 6 setup
- ✅ TypeScript 5.7 configuration
- ✅ Material-UI 6.3 theme configuration
- ✅ All dependencies installed and resolved
- ✅ UI components extracted from Figma (80%):
  - Buttons, inputs, dropdowns, modals, cards, tables
  - Header, sidebar, footer layouts
  - All pages visually complete
  - Mobile responsive (320px - 1920px)
  - Dummy data displayed everywhere

**What's NOT Done Yet (0%):**
- ❌ **Redux Toolkit 2.5 store:** Need to create all slices
  - authSlice (user, token, login state)
  - workflowSlice (requests, current workflow)
  - approvalSlice (approval levels, status)
  - notificationSlice (notifications, unread count)
  - documentSlice, workNoteSlice, participantSlice, uiSlice
  
- ❌ **Axios API service layer:** Need to configure
  - Create Axios instance with base URL
  - Setup request interceptors (add JWT token)
  - Setup response interceptors (error handling)
  - Handle token refresh logic
  - Handle 401 unauthorized redirects
  
- ❌ **React Router DOM 7.1:** Need to implement
  - Route protection (PrivateRoute/PublicRoute)
  - Auth guards (redirect if not logged in)
  - Route-based code splitting
  
- ❌ **Form Validations:** None implemented
  - No field validation (email format, required fields)
  - No error messages shown
  - Forms accept any input
  
- ❌ **API Integration:** Zero integration
  - Forms don't submit data
  - Lists show dummy data
  - No backend calls made
  - No loading states
  - No error handling

**Remaining Work for Sprint 0:**
1. Complete last 20% of UI extraction (1-2 days)
2. Setup Redux store with all slices (2-3 days)
3. Configure Axios service layer (1 day)
4. Implement route guards (1 day)
5. Basic form validations (2 days)

**Estimated Time to Complete Sprint 0:** 1 week more

#### What You Can Use After Sprint 0 (Actually Completes):
- ✅ Running backend server with database connection
- ✅ Frontend UI with all visual components
- ✅ Redux store configured and working
- ✅ API service layer ready to make calls
- ✅ Protected routes working
- ✅ Forms with basic validation
- ❌ Still no API integration (that's Sprint 1 onwards)

---

### 🔐 Sprint 1: SSO Authentication & User Management (Week 2-3)
**Status:** ⏳ Awaiting SSO Details | **Focus:** SSO integration (no login/signup screens)

#### What This Sprint Delivers:
SSO-based authentication with Royal Enfield SSO Bridge. Users authenticate via company SSO (no login/signup screens needed).

#### Key Implementation Points:

**Backend (BE-101, BE-102: 2 days):**
- Configure SSO Bridge OAuth2 integration
- Handle SSO callback and token exchange
- Auto-sync users from Active Directory to local database
- Generate JWT tokens for app sessions
- User search API (for @tagging in workflows)
- User profile update API (phone/picture only - other fields from AD)

**Frontend (FE-101, FE-102, FE-103: 2.5 days):**
- SSO callback handler page (receives token from SSO)
- Protected route guards (redirect to SSO if not authenticated)
- "Login with SSO" button (redirects to SSO Bridge)
- Logout functionality (clears session + SSO logout)
- User profile display in header (from Active Directory data)
- Limited profile editing (phone number and profile picture only)

**What You Can Do After Sprint 1:**
- ✅ Users can login via SSO
- ✅ Users auto-synced from Active Directory
- ✅ Protected routes working (redirect to SSO if not logged in)
- ✅ User profile displayed in header
- ✅ Logout functionality
- ✅ JWT session management

**⚠️ Important:** No login/signup/password reset screens needed! SSO handles all authentication.

**📖 For Detailed Implementation:** See `RE_Workflow_Detailed_Sprint_Guide.md`

---

### 📝 Sprint 2: Core Workflow Creation (Weeks 3-4)
**Status:** ⏳ Upcoming | **Focus:** 6-step workflow creation wizard

#### What This Sprint Delivers:
Complete workflow creation wizard: Basic Info → Approval Hierarchy → Participants → Documents → Review → Submit

#### Key Features:
- **Step 1:** Template selection (Custom Request)
- **Step 2:** Request title, rich text description, priority (Standard/Express)
- **Step 3:** Dynamic approval levels (up to 10), @mention user search, TAT calculation
- **Step 4:** Add spectators with @mention
- **Step 5:** Document upload (drag-drop, 10MB max), Google Docs/Sheets links
- **Step 6:** Review summary, save draft or submit

**Backend APIs (BE-201 to BE-204: 1 week):**
- Create/update/delete workflow
- Add approval levels
- Add participants
- Upload documents
- Submit workflow
- List and filter workflows

**Frontend Integration (FE-201 to FE-208: 1.5 weeks):**
- Connect wizard steps to Redux
- Real-time TAT calculation
- User search for approvers/spectators
- File upload with progress
- Multi-step API submission flow
- Form validations

**Most Complex:** Approval workflow builder (dynamic levels, TAT calculation, user search)

**📖 For Detailed Code Examples:** See `RE_Workflow_Detailed_Sprint_Guide.md` - Sprint 2 section

---

### ✅ Sprint 3: Approval & Workflow Actions (Weeks 5-6)
**Status:** ⏳ Upcoming | **Focus:** Approve/reject requests, TAT tracking, notifications

#### What This Sprint Delivers:
- Request management pages (My Requests, Open Requests, Closed Requests)
- Request detail page with tabs (Overview, Workflow, Documents, Activity)
- Approve/reject modals with mandatory comments
- TAT monitoring cron job (runs every 30 minutes)
- Real-time notifications (bell icon with unread count)
- Work notes integration with @mentions

**Backend APIs (BE-301 to BE-303: 1.5 weeks):**
- Approve/reject workflow endpoints
- TAT calculation service (working days vs calendar days)
- TAT monitoring cron job
- Notification system (8 notification types)
- Activity logging for all actions

**Frontend Integration (FE-301 to FE-309: 2 weeks):**
- Request listing pages with search/filter/pagination
- Request detail page with 4 tabs
- TAT progress bars (color-coded: green/yellow/red)
- Approval timeline visualization
- Notification bell with dropdown
- Approve/reject modals with validation

**Most Complex:** TAT calculation logic (working days exclude weekends)

**📖 For Detailed Code Examples:** See `RE_Workflow_Detailed_Sprint_Guide.md` - Sprint 3 section

**2. Approval Hierarchy Management (BE-202, FE-204)**

**Backend APIs:**
- **POST /api/v1/workflows/:id/approvals** - Add approval level
  - Accept level number, approver user ID, TAT
  - Validate max 10 levels
  - Ensure level numbers are sequential (1, 2, 3...)
  - Calculate TAT dates based on priority
  
- **GET /api/v1/workflows/:id/approvals** - Get approval hierarchy
  - Return all levels with approver details
  - Show current level status
  
- **GET /api/v1/workflows/:id/approvals/current** - Get active level
  - Return currently active approval level
  - Show who needs to approve now

**Frontend Approval Workflow Builder (FE-204):**

This is the most complex screen in the wizard!

**Dynamic Level Creation:**
- Start with Level 1 (minimum 1 level required)
- Add Level button to create additional levels
- Maximum 10 approval levels allowed
- Each level can be removed (except if only 1 level)

**For Each Approval Level:**
- **Level Number:** Auto-generated (Level 1, Level 2, etc.)
  
- **Level Name/Title:** (Optional)
  - Text input for descriptive name
  - Example: "Department Head Approval", "Finance Review", "CEO Final Approval"
  
- **Approver Selection:**
  - **@mention search input** (like Slack/Teams)
  - Type "@" or start typing name
  - Dropdown appears showing matching users
  - Shows user details:
    - Full name
    - Email address
    - Department
    - Profile picture
  - Select user from dropdown
  - Selected user appears as tag/chip
  - Can clear and select different user
  - Required field (must select an approver)
  
- **TAT (Turnaround Time):**
  - Number input for TAT value
  - Dropdown to select unit (Hours or Days)
  - Options: 1-720 hours OR 1-30 days
  - Required field
  - Example: "48 hours" or "2 days"
  
- **Add/Remove Level Actions:**
  - "Add Level" button (if less than 10 levels)
  - "Remove Level" button (if more than 1 level)
  - Confirm before removing level

**Real-Time TAT Calculation:**
- As user adds levels and TAT values:
  - Automatically sum all TAT values
  - Show total TAT prominently at top
  - Example: "Total TAT: 96 hours (4 days)"
  - Update in real-time as user modifies levels

**Approval Flow Summary Panel:**
- Read-only visualization showing:
  - Complete approval hierarchy
  - All levels in order (1 → 2 → 3...)
  - Approver name for each level
  - TAT for each level
  - Total TAT at bottom
- Updates automatically as user adds/modifies levels

**TAT Summary Widget:**
- Visual breakdown:
  - Total hours and days
  - Expected completion date (estimated)
  - Working days vs calendar days indicator
- Color-coded based on urgency

**Validation:**
- At least 1 approval level required
- Each level must have an approver selected
- Each level must have valid TAT (> 0)
- No duplicate approvers allowed (same person can't be at multiple levels)

**WEEK 4: Participants, Documents & Submission**

**3. Participant Management (BE-203, FE-205)**

**Backend APIs:**
- **POST /api/v1/workflows/:id/participants** - Add spectator
  - Accept user ID and participant type
  - Validate user exists
  - Set permissions (can view, can comment)
  
- **GET /api/v1/workflows/:id/participants** - Get all participants
  - Return initiator, approvers, spectators
  
- **DELETE /api/v1/workflows/:id/participants/:id** - Remove spectator
  - Only spectators can be removed (not approvers)

**Frontend Participants & Access (FE-205):**

**Add Spectators Section:**
- **What are Spectators?**
  - View-only participants (like CC in email)
  - Can see workflow progress
  - Can add comments in work notes
  - Cannot approve or reject
  - Receive notifications about workflow
  
- **@mention Search (same as approver selection):**
  - Type "@" or start typing name
  - Search users by name/email
  - Select multiple spectators
  - Show selected spectators as chips/tags
  
- **Spectator List:**
  - Display all added spectators
  - Show user name, email, department
  - Remove button for each spectator
  
- **Permissions Display:**
  - Clear message: "Spectators can view and comment but cannot approve"
  - Visual icon showing permissions

**4. Document Upload (BE-201, FE-206)**

**Backend APIs:**
- **POST /api/v1/workflows/:id/documents** - Upload document
  - Accept multipart/form-data
  - Validate file type (PDF, Word, Excel, PPT, images)
  - Validate file size (max 10MB per file)
  - Upload to cloud storage (GCP or local for dev)
  - Store metadata in database
  - Return document ID and URL
  
- **GET /api/v1/workflows/:id/documents** - Get all documents
  - Return list of documents with metadata

**Frontend Documents & Attachments (FE-206):**

**File Upload Component:**
- **Drag-and-Drop Zone:**
  - Large drop area with icon
  - "Drag files here or click to browse"
  - Highlight area when files dragged over
  
- **Browse Files Button:**
  - Opens file picker dialog
  - Can select multiple files at once
  
- **Supported File Types:**
  - PDF documents
  - Word (DOC, DOCX)
  - Excel (XLS, XLSX)
  - PowerPoint (PPT, PPTX)
  - Images (JPG, PNG, GIF)
  - Show supported formats below upload area
  
- **File Size Limit:**
  - Maximum 10MB per file
  - Show error if file too large
  - Suggest compressing large files

**Uploaded Files List:**
- Display each file as a card/row showing:
  - File icon (based on file type)
  - File name
  - File size (KB/MB)
  - Upload progress bar (while uploading)
  - Remove button (X icon)
  
- **File Actions:**
  - Preview icon (for PDF and images)
  - Download icon
  - Delete icon

**Google Docs/Sheets Integration:**
- **Google Docs Link:**
  - Text input for Google Docs URL
  - Validate URL format
  - Show link icon when valid URL entered
  
- **Google Sheets Link:**
  - Text input for Google Sheets URL
  - Validate URL format
  - Show link icon when valid URL entered
  
- Display added links with:
  - Document/Sheet icon
  - Link title (extracted from URL or user-provided)
  - Open link button
  - Remove button

**5. Review & Submit (BE-201, FE-207, FE-208)**

**Frontend Review & Submit (FE-207):**

**Comprehensive Summary Display:**

**Section 1: Request Overview**
- Request Type: Custom Request
- Priority: Standard / Express (with badge)
- Request Title: (user-entered title)

**Section 2: Basic Information**
- Detailed Description (formatted with HTML)
- Priority Level with explanation
- Edit button → goes back to Step 2

**Section 3: Approval Workflow**
- Visual hierarchy showing:
  - All approval levels in order
  - Approver name and email for each level
  - TAT for each level
  - Total TAT calculation
- Edit button → goes back to Step 3

**Section 4: Participants & Access**
- List of all spectators with names
- Participant count
- Edit button → goes back to Step 4

**Section 5: Documents & Attachments**
- List of uploaded files (name, size, type)
- List of Google Docs/Sheets links
- Document count
- Edit button → goes back to Step 5

**Action Buttons:**

**Save as Draft:**
- Saves workflow without submitting
- User can edit later
- Stays in "Draft" status
- Redirects to "My Requests"

**Submit Request:**
- Final submission (cannot be edited after)
- Triggers approval workflow
- Changes status from "Draft" to "Pending"
- Sends notification to first approver
- Starts TAT tracking
- Redirects to request detail page

**Backend Submission Logic (BE-201, FE-208):**

**API Integration Flow:**
1. **POST /api/v1/workflows** - Create draft workflow
2. **POST /api/v1/workflows/:id/documents** (multiple) - Upload documents
3. **POST /api/v1/workflows/:id/approvals** (multiple) - Create approval levels
4. **POST /api/v1/workflows/:id/participants** (multiple) - Add spectators
5. **PATCH /api/v1/workflows/:id/submit** - Submit workflow

**Submission Actions:**
- Update workflow status: DRAFT → PENDING
- Set submission_date to current timestamp
- Calculate and set tat_start_date and tat_end_date
- Update first approval level status to IN_PROGRESS
- Create activity log entry: "Request submitted"
- Send notifications:
  - To first approver: "New workflow pending your approval"
  - To all spectators: "You've been added to a workflow request"
- Return complete workflow data

**6. Workflow Listing & Filtering (BE-204)**

**Backend APIs:**
- **GET /api/v1/workflows** - Get all workflows with filters
  - Query parameters: status, priority, page, limit, sortBy, sortOrder
  
- **GET /api/v1/workflows/my-requests** - User's created workflows
  - Return workflows where user is initiator
  
- **GET /api/v1/workflows/open** - Open/pending workflows
  - Return workflows in PENDING or IN_PROGRESS status
  - Where user is approver or spectator
  
- **GET /api/v1/workflows/closed** - Completed workflows
  - Return workflows in APPROVED, REJECTED, or CLOSED status
  
- **GET /api/v1/workflows/assigned-to-me** - Workflows pending user's action
  - Return workflows where user is current level approver

**Filtering & Search Features:**
- Filter by status (Draft, Pending, Approved, Rejected, Closed)
- Filter by priority (Standard, Express)
- Filter by date range (submission date)
- Search by title or description (full-text search)
- Sort by date, priority, status
- Pagination (20 requests per page)

#### What You Can Do After Sprint 2:
- ✅ Create custom workflow requests
- ✅ Define multi-level approval hierarchy (up to 10 levels)
- ✅ Set TAT for each approval level
- ✅ Add spectators for transparency
- ✅ Upload supporting documents
- ✅ Link Google Docs/Sheets
- ✅ Save workflows as draft
- ✅ Submit workflows for approval
- ✅ View all created workflows (My Requests)
- ✅ Search and filter workflows

#### Technical Complexity:
- **Frontend:** Dynamic form with 6 steps, wizard navigation, real-time validation
- **Backend:** Complex data relationships, file upload, TAT calculation logic
- **Integration:** Multi-step API calls, error handling at each step

---

### ✅ Sprint 3: Approval & Workflow Actions (Weeks 5-6)
**Status:** ⏳ Upcoming | **Focus:** Enable approvers to act on workflows, track TAT, send notifications

#### What This Sprint Delivers:
Complete approval workflow with ability to approve/reject requests, TAT monitoring with alerts, real-time notifications, and comprehensive request management pages.

#### Detailed Functionality Breakdown:

**WEEK 5: Approval Actions & TAT Tracking**

**1. Workflow Approval Process (BE-301)**

**Backend Approval Logic:**

**PATCH /api/v1/workflows/:id/approvals/:levelId/approve** - Approve Request

**Pre-Approval Validations:**
- Verify user is the assigned approver for this level
- Verify workflow is in PENDING or IN_PROGRESS status
- Verify current level matches the level being approved
- Verify level is not already approved
- Verify comments field is provided (mandatory)

**Approval Actions:**
1. Update approval level:
   - Set status to APPROVED
   - Set action_date to current timestamp
   - Set level_end_time to current timestamp
   - Store approver comments
   
2. Stop TAT for current level:
   - Calculate elapsed time for this level
   - Update tat_tracking table
   - Mark level as completed within/beyond TAT
   
3. Move to next level OR close if final:
   - **If NOT final approver:**
     - Increment workflow current_level (e.g., 1 → 2)
     - Update workflow status to IN_PROGRESS
     - Update next level status to IN_PROGRESS
     - Set level_start_time for next level
     - Start TAT tracking for next level
     - Send notification to next approver
   - **If final approver:**
     - Update workflow status to APPROVED
     - Set closure_date to current timestamp
     - Trigger AI conclusion generation
     - Send notification to initiator: "Your request has been approved"
     - Send notification to all spectators
     
4. Create activity log:
   - Activity type: APPROVAL_ACTION
   - Description: "Level X approved by [Approver Name]"
   - Store comments in metadata
   - Timestamp the action

**PATCH /api/v1/workflows/:id/approvals/:levelId/reject** - Reject Request

**Pre-Rejection Validations:**
- Same as approval validations
- Comments/rejection reason is mandatory

**Rejection Actions:**
1. Update approval level:
   - Set status to REJECTED
   - Set action_date to current timestamp
   - Store rejection comments (mandatory)
   
2. Stop all TAT tracking:
   - Mark current level as breached/stopped
   - Cancel pending levels
   
3. Close workflow:
   - Update workflow status to REJECTED
   - Set closure_date to current timestamp
   - Mark as closed
   
4. Send notifications:
   - To initiator: "Your request has been rejected by [Approver Name]"
   - Include rejection reason in notification
   - To all spectators: notification of rejection
   
5. Create activity log:
   - Activity type: REJECTION_ACTION
   - Description: "Request rejected by [Approver Name] at Level X"
   - Store rejection reason in metadata

**Frontend Approval Actions (FE-307):**

**Approve Request Modal:**
- **Trigger:** Click "Approve Request" button in request detail
- **Modal Content:**
  - Request ID and Title display
  - Current approval level info
  - "Approval Confirmation" heading
  - **Comments & Remarks field:**
    - Multi-line text area
    - Placeholder: "Add your approval comments..."
    - Mandatory field (cannot submit without comments)
    - Character limit: 500 characters
    - Character counter showing remaining chars
    - Validation: "Comments are required"
  - **Contextual message:**
    - "Your approval will move this request to the next level" OR
    - "As final approver, your approval will close this request"
- **Action Buttons:**
  - "Approve Request" button (primary/green)
    - Disabled until comments entered
    - Shows loading spinner during API call
  - "Cancel" button (secondary)
    - Closes modal without action

**Reject Request Modal:**
- **Trigger:** Click "Reject Request" button in request detail
- **Modal Content:**
  - Request ID and Title display
  - Current approval level info
  - "Rejection Confirmation" heading (red/warning color)
  - **Rejection Reason field:**
    - Multi-line text area
    - Placeholder: "Please provide detailed reason for rejection..."
    - Mandatory field (cannot submit without reason)
    - Character limit: 500 characters
    - Character counter
    - Validation: "Rejection reason is required"
  - **Warning message:**
    - "Rejecting will close this request immediately"
    - "This action cannot be undone"
  - **Rejection Guidelines:**
    - "Please provide constructive feedback"
    - "Be specific about what needs to be changed"
- **Action Buttons:**
  - "Reject Request" button (danger/red)
    - Disabled until reason entered
    - Shows loading spinner
    - Confirmation prompt: "Are you sure?"
  - "Cancel" button
    - Closes modal without action

**After Action Taken:**
- Close modal automatically
- Show success notification:
  - "Request approved successfully" OR
  - "Request rejected"
- Refresh request detail page to show updated status
- Scroll to activity timeline to show new activity
- Update TAT progress bar
- Update approval timeline visual

**2. TAT Tracking & Monitoring (BE-302)**

**Backend TAT Service:**

**TAT Calculation Logic:**

**For Standard Priority (Working Days):**
- Calculate elapsed time excluding weekends
- Exclude holidays (if holiday list configured)
- Example: 48 hours TAT starting Friday 3 PM
  - Friday 3 PM - 5 PM = 2 hours
  - Monday 9 AM - 5 PM = 8 hours  
  - Tuesday 9 AM - 5 PM = 8 hours
  - Wednesday 9 AM - 5 PM = 8 hours
  - Thursday 9 AM - 5 PM = 8 hours
  - Friday 9 AM - 3 PM = 6 hours
  - Total = 40 hours (exclude weekend)

**For Express Priority (Calendar Days):**
- Calculate elapsed time including weekends
- Include all days (7 days/week, 24 hours/day)
- Example: 48 hours TAT starting Friday 3 PM
  - Deadline: Sunday 3 PM (48 hours later)

**TAT Status Determination:**
- **ON_TRACK (Green):**
  - TAT usage < 50%
  - Example: 10 hours used out of 48 hours (20%)
  
- **APPROACHING (Yellow/Warning):**
  - TAT usage between 50% and 80%
  - Example: 36 hours used out of 48 hours (75%)
  - Trigger reminder notification
  
- **BREACHED (Red/Critical):**
  - TAT usage >= 100%
  - Example: 50 hours used out of 48 hours (104%)
  - Trigger breach alert notification

**TAT Monitoring Cron Job:**
- **Schedule:** Runs every 30 minutes
- **Process:**
  1. Get all active workflows (PENDING, IN_PROGRESS)
  2. For each active workflow:
     - Get current approval level
     - Calculate elapsed time since level_start_time
     - Calculate percentage TAT used
     - Determine TAT status
     - Update tat_tracking table
  3. Check for threshold crossings:
     - If TAT usage crosses 50%: Create alert (optional)
     - If TAT usage crosses 80%: Send reminder notification
     - If TAT usage crosses 100%: Send breach notification
  4. Send notifications to approvers and initiators
  5. Log TAT status changes in activity timeline

**TAT APIs:**
- **GET /api/v1/workflows/:id/tat** - Get TAT status
  - Return current level TAT info
  - Elapsed time, remaining time, percentage used
  - TAT status (ON_TRACK, APPROACHING, BREACHED)
  - Expected completion date
  
- **GET /api/v1/tat/breached** - Get breached requests
  - Return all workflows with breached TAT
  - For admin dashboard and monitoring
  
- **GET /api/v1/tat/approaching** - Get approaching deadlines
  - Return workflows with TAT usage > 80%
  - For proactive monitoring

**Frontend TAT Display (FE-303, FE-304):**

**TAT Progress Bar Component:**
- **Visual Progress Bar:**
  - Horizontal bar showing TAT progress
  - Fill color based on status:
    - Green: 0-50% (ON_TRACK)
    - Yellow: 50-80% (APPROACHING)
    - Orange: 80-99% (HIGH RISK)
    - Red: 100%+ (BREACHED)
  - Animated fill effect
  - Percentage label inside or above bar
  
- **TAT Status Text:**
  - Display current status with icon
  - "On Track" (green checkmark icon)
  - "Approaching Deadline" (yellow warning icon)
  - "TAT Breached!" (red exclamation icon)
  
- **Time Information:**
  - Elapsed time: "24 hours elapsed"
  - Remaining time: "24 hours remaining" OR "8 hours overdue"
  - Total TAT: "48 hours total"
  - Expected completion: "Expected by Nov 15, 3:00 PM"
  
- **Per-Level TAT Display (Workflow Tab):**
  - For each approval level, show:
    - Level TAT allocation (e.g., "48 hours")
    - Actual time taken
    - Status indicator (completed within/beyond TAT)
    - Progress bar for active level
    - Checkmark for completed levels

**WEEK 6: Notifications & Request Management**

**3. Notification System (BE-303)**

**Backend Notification Service:**

**Notification Types & Triggers:**

**1. Workflow Assignment Notifications:**
- **When:** Workflow submitted, moves to new level
- **To:** Assigned approver
- **Title:** "New Approval Request Assigned"
- **Message:** "You have a new workflow request (REQ-2025-00001) pending your approval from [Initiator Name]"
- **Action URL:** Link to request detail page
- **Priority:** NORMAL

**2. Approval/Rejection Notifications:**
- **When:** Request approved or rejected
- **To:** Workflow initiator
- **Title:** "Workflow Request [Approved/Rejected]"
- **Message:** "Your request (REQ-2025-00001) has been [approved/rejected] by [Approver Name]"
- **Action URL:** Link to request detail page
- **Priority:** HIGH

**3. TAT Warning Notifications (80% threshold):**
- **When:** TAT usage reaches 80%
- **To:** Current approver + initiator
- **Title:** "TAT Warning: Action Required"
- **Message:** "Request (REQ-2025-00001) has used 80% of TAT. Please review urgently."
- **Action URL:** Link to request detail page
- **Priority:** HIGH

**4. TAT Breach Notifications (100%+):**
- **When:** TAT exceeded
- **To:** Current approver + initiator + spectators
- **Title:** "TAT BREACHED!"
- **Message:** "Request (REQ-2025-00001) has exceeded TAT deadline"
- **Action URL:** Link to request detail page
- **Priority:** URGENT

**5. Work Note Mention Notifications:**
- **When:** User @mentioned in work note
- **To:** Mentioned user
- **Title:** "[User Name] mentioned you"
- **Message:** "[User Name] mentioned you in a work note: '[Message preview...]'"
- **Action URL:** Link to work notes section
- **Priority:** NORMAL

**6. Document Upload Notifications:**
- **When:** New document uploaded
- **To:** All participants (initiator, approvers, spectators)
- **Title:** "New Document Added"
- **Message:** "[User Name] uploaded a document: [filename]"
- **Action URL:** Link to documents tab
- **Priority:** LOW

**7. Spectator Added Notifications:**
- **When:** User added as spectator
- **To:** Added spectator
- **Title:** "You've been added to a workflow"
- **Message:** "[Initiator Name] added you as spectator to request (REQ-2025-00001)"
- **Action URL:** Link to request detail page
- **Priority:** NORMAL

**8. Request Closure Notifications:**
- **When:** Workflow closed (approved or rejected)
- **To:** All participants (initiator, approvers, spectators)
- **Title:** "Workflow Request Closed"
- **Message:** "Request (REQ-2025-00001) has been closed"
- **Action URL:** Link to request detail page
- **Priority:** NORMAL

**Notification APIs:**
- **GET /api/v1/notifications** - Get user notifications
  - Query params: page, limit, is_read filter
  - Return paginated notifications
  - Sort by created_at DESC (newest first)
  
- **GET /api/v1/notifications/unread** - Get unread notifications
  - Return only unread notifications
  - Include unread count
  
- **PATCH /api/v1/notifications/:id/read** - Mark as read
  - Update is_read to true
  - Set read_at timestamp
  
- **PATCH /api/v1/notifications/mark-all-read** - Mark all as read
  - Update all user's unread notifications
  
- **DELETE /api/v1/notifications/:id** - Delete notification
  - Soft delete or hard delete

**Frontend Notification System (FE-401):**

**Notification Bell Icon (Header):**
- **Bell icon in top-right corner**
- **Unread count badge:**
  - Red circle with number
  - Shows count of unread notifications
  - Updates in real-time
  - Pulsing animation for new notifications
  
- **Click Behavior:**
  - Opens dropdown panel below icon
  - Shows recent notifications
  - Marks clicked notifications as read

**Notification Dropdown Panel:**
- **Header:**
  - "Notifications" title
  - "Mark All as Read" button
  - Close button (X)
  
- **Notification List (Recent 10):**
  - Each notification shows:
    - Type icon (color-coded)
    - Title (bold)
    - Message text (truncated)
    - Timestamp (relative: "2 hours ago")
    - Unread indicator (blue dot)
    - Read notifications are grayed out
  
- **Click Notification:**
  - Mark as read automatically
  - Navigate to action URL (request detail page)
  - Close dropdown
  
- **Footer:**
  - "View All Notifications" link
  - Opens full notifications page
  
- **Empty State:**
  - Shows when no notifications
  - Icon + "No notifications"

**Notification Polling:**
- **Auto-refresh every 30 seconds**
- Fetch new notifications from API
- Update unread count in header
- Show toast notification for high-priority alerts
- Play sound (optional) for urgent notifications

**Toast Notifications (High Priority):**
- **For urgent notifications:**
  - Small popup in top-right corner
  - Auto-dismiss after 5 seconds
  - Click to go to related request
  - Multiple toasts stack vertically

**4. Request Management Pages (FE-301, FE-302, FE-303)**

**My Requests Page (FE-301):**

**Page Layout:**
- **Tab Navigation at Top:**
  - Total (show all requests)
  - In Progress (pending + in_progress status)
  - Approved (approved status)
  - Rejected (rejected status)
  - Draft (draft status)
  - Each tab shows count badge
  
- **Search & Filter Bar:**
  - Search input (search by title or request number)
  - Priority filter dropdown (All, Standard, Express)
  - Date range filter (submission date)
  - Sort dropdown (Date: Newest, Date: Oldest, Priority)
  - "Clear Filters" button
  
- **Request Cards Grid:**
  - Display requests as cards (3 per row on desktop)
  - Each card shows:
    - **Request Number** (REQ-2025-00001) - top-left
    - **Title** (bold, large) - truncate if too long
    - **Priority Badge** - Express (red) / Standard (blue)
    - **Status Badge** - Color-coded:
      - Draft: Gray
      - Pending: Yellow
      - In Progress: Blue
      - Approved: Green
      - Rejected: Red
      - Closed: Dark Gray
    - **Current Approval Level** - "Level 2 of 5"
    - **Current Approver** - Name and designation
    - **Submission Date** - "Submitted on Nov 10, 2025"
    - **Estimated Completion** - "Expected by Nov 15"
    - **TAT Progress Bar** (for active requests)
    - **Quick Actions:**
      - View Details button
      - Edit button (only for drafts)
      - Delete button (only for drafts)
  
- **Pagination:**
  - Show 20 requests per page
  - Page numbers at bottom
  - Previous/Next buttons
  - "Go to page" input

**Click on Card:**
- Navigate to Request Detail page
- Pass request ID in URL

**Open Requests Page (FE-302):**
- **Similar to My Requests but shows:**
  - Requests where user is approver (pending action)
  - Requests where user is spectator
  - Requests in PENDING or IN_PROGRESS status
- **Highlight requests needing user's action**
- **Same layout as My Requests**

**Closed Requests Page (FE-302):**
- **Shows requests with status:**
  - APPROVED
  - REJECTED
  - CLOSED
- **Additional Info:**
  - Closure date
  - Final approver name
  - Conclusion remark preview (first 100 chars)
- **Same layout as My Requests**

**5. Request Detail Page (FE-303 to FE-306)**

**Request Detail Overview Tab (FE-303):**

**Page Layout:**

**Top Section:**
- **Request Header:**
  - Request Number (large, bold)
  - Status Badge (prominent)
  - Priority Badge
  - Created Date | Submitted Date
  
- **TAT Progress Section:**
  - Large TAT progress bar (full width)
  - Status indicator (On Track / Approaching / Breached)
  - Time information (elapsed, remaining, total)
  - Expected completion date
  
- **Tab Navigation:**
  - Overview (active by default)
  - Workflow
  - Documents
  - Activity
  - Each tab shows relevant counts

**Left Content Area (Main):**

**Request Information Card:**
- **Title:** Request title (editable if draft)
- **Description:** 
  - Full description with HTML formatting
  - Expand/collapse if very long
  - Tables, lists, links preserved
- **Initiator Information:**
  - Profile picture
  - Name and designation
  - Department
  - Email address
  - Phone number
  - "Contact" button
- **Basic Details:**
  - Request Type: Custom Request
  - Priority Level with explanation
  - Template Type (if applicable)
  - Submission Date
  - Last Updated Date

**Right Sidebar:**

**Spectators Panel:**
- **Title:** "Spectators" with count
- **List of spectators:**
  - Profile picture (small)
  - Name
  - Department
  - Can scroll if many spectators
- **Add Spectator button** (if user has permission)

**Quick Actions Panel** (shown only to approvers of current level):
- **Action Buttons:**
  - "Add Work Note" (primary)
  - "Add Approver" (secondary)
  - "Add Spectator" (secondary)
  - "Approve Request" (success/green, large)
  - "Reject Request" (danger/red, large)
- **Buttons enabled/disabled based on:**
  - User role (approver, initiator, spectator)
  - Current workflow status
  - User's turn to approve

**Workflow Tab (FE-304):**

**Approval Timeline Visualization:**

**Vertical Timeline (Top to Bottom):**
- **For Each Approval Level:**
  
  **Level Card:**
  - **Level Number & Name** - "Level 1: Department Head Approval"
  
  - **Approver Info:**
    - Profile picture
    - Name and designation
    - Department
    - Email address
  
  - **TAT Allocation:**
    - Allocated TAT: "48 hours"
    - TAT days: "2 days" (if applicable)
  
  - **Status Indicator:**
    - **PENDING:** Gray circle with clock icon
    - **IN_PROGRESS:** Blue circle with spinner icon
    - **APPROVED:** Green circle with checkmark icon
    - **REJECTED:** Red circle with X icon
    - **SKIPPED:** Yellow circle with forward icon
  
  - **Time Tracking:**
    - Level start time: "Started on Nov 12, 10:00 AM"
    - Level end time: "Completed on Nov 13, 2:00 PM"
    - Actual time taken: "28 hours"
    - TAT status for level:
      - "Completed within TAT" (green badge)
      - "Exceeded TAT by 5 hours" (red badge)
  
  - **TAT Progress Bar** (for active level):
    - Visual bar showing % used
    - Color-coded (green/yellow/red)
    - Remaining time displayed
  
  - **Approver Comments:**
    - Display comments if level is approved/rejected
    - Formatted text with proper line breaks
    - Timestamp: "Commented on Nov 13, 2:00 PM"
  
  - **Action Date:**
    - Display date/time when approved/rejected
    - Relative time: "2 days ago"

**Visual Connectors:**
- Vertical line connecting levels
- Shows flow from Level 1 → 2 → 3...
- Current active level highlighted

**Level Status Summary (Top of Page):**
- **Progress Indicator:**
  - "Level 2 of 5 in progress"
  - Progress bar showing overall approval progress
  - Example: "40% complete (2 of 5 levels)"

**Approval Flow Insights:**
- **Average time per level**
- **Fastest level completion**
- **Slowest level completion**
- **Total approval time taken**

**Documents Tab (FE-305):**

**Document List View:**

**Filter/View Options:**
- Filter by file type (All, PDF, Word, Excel, Images, etc.)
- Sort by: Name, Date, Size, Uploader
- Grid view / List view toggle

**Document Cards/List Items:**
- **For Each Document:**
  
  **Document Card:**
  - **File Type Icon** (large, color-coded)
    - PDF: Red icon
    - Word: Blue icon
    - Excel: Green icon
    - PowerPoint: Orange icon
    - Images: Purple icon
  
  - **File Name** (bold)
  - **File Size** (e.g., "2.5 MB")
  - **File Type** (e.g., "PDF Document")
  - **Upload Info:**
    - Uploaded by: Name
    - Upload date/time
    - Relative time: "3 days ago"
  
  - **Action Buttons:**
    - **Preview button** (eye icon)
      - Enabled for PDF and images only
      - Opens preview modal
    - **Download button** (download icon)
      - Downloads file to user's device
    - **Delete button** (trash icon)
      - Only shown to initiator or admin
      - Confirmation before delete
  
  - **Version Info** (if applicable):
    - Version number: "v2"
    - "View history" link

**Preview Modal (for PDF/Images):**
- **PDF Preview:**
  - Embedded PDF viewer
  - Page navigation (Previous/Next)
  - Zoom in/out buttons
  - Full-screen option
  - Download button
  - Close button
  
- **Image Preview:**
  - Lightbox viewer
  - Full-size image display
  - Zoom controls
  - Previous/Next for multiple images
  - Download button
  - Close button

**Google Docs/Sheets Section:**
- **Separate section below uploaded files**
- **Title:** "Linked Documents"
- **For Each Link:**
  - Google Docs/Sheets icon
  - Document title
  - Link URL
  - "Open in new tab" button
  - Added by: User name
  - Added on: Date/time

**Empty State:**
- Shows when no documents uploaded
- Icon + message: "No documents uploaded yet"
- "Upload Document" button

**Activity Tab (FE-306):**

**Activity Timeline View:**

**Timeline Display (Reverse Chronological):**
- **Latest activities at top**
- **Scroll to see older activities**

**For Each Activity:**

**Activity Item:**
- **Event Icon (left side):**
  - Color-coded by activity type
  - Icons:
    - 📝 Request created (green)
    - ✅ Approved (green checkmark)
    - ❌ Rejected (red X)
    - 📎 Document uploaded (blue paperclip)
    - 🗑️ Document deleted (gray trash)
    - 💬 Work note added (blue chat bubble)
    - 👤 Approver added (green person+)
    - 👥 Spectator added (blue person+)
    - ⚠️ TAT warning (yellow warning)
    - 🚨 TAT breached (red alert)
    - 📊 Status changed (blue)
    - 🔒 Request closed (gray lock)

- **Activity Description:**
  - Primary text (bold): Main action
    - Example: "Request submitted for approval"
    - Example: "Approved by John Doe at Level 2"
    - Example: "Document uploaded: filename.pdf"
  - Secondary text: Additional details
    - Example: "Status changed from PENDING to IN_PROGRESS"
  
- **User Information:**
  - Profile picture (small, if user action)
  - User name and designation
  - "System" for automated activities
  
- **Timestamp:**
  - Relative time: "2 hours ago", "3 days ago"
  - Hover to see exact date/time
  
- **Metadata (if applicable):**
  - For status changes: Show old → new status
  - For documents: Show file name and size
  - For approvals: Show comments preview
  - Expandable section for full details

**Activity Type Grouping:**
- Group activities by date
- Date headers: "Today", "Yesterday", "Nov 12, 2025"

**Activity Filter (Optional):**
- Filter by activity type
- Dropdown: All, Approvals, Documents, Work Notes, Status Changes

**Real-Time Updates:**
- Auto-refresh when new activity occurs
- Smooth animation for new activities
- Highlight new activities with background color

**6. Work Notes / Chat Component (FE-308)**

**✅ ALREADY COMPLETE!** (As mentioned by user)

The work notes feature is already functional with:
- Document selection capability
- Emoji support
- @mentions
- File attachments
- Real-time chat interface

**What's Needed:**
- Connect to backend APIs (BE-402)
- Ensure notifications trigger on @mentions

**7. Add Approver/Spectator Modals (FE-309)**

**Add Approver Modal:**
- **Trigger:** Click "Add Approver" button
- **Modal Content:**
  - Title: "Add Approver to Workflow"
  - Explanation: "Add an additional approver at the current level"
  - **User Search Input:**
    - @mention autocomplete
    - Search by name or email
    - Dropdown showing matching users
  - **Selected User Display:**
    - Show user card with name, email, department
    - Confirm selection
  - **Action Buttons:**
    - "Add" button (primary)
    - "Cancel" button
- **After Adding:**
  - Close modal
  - Show success notification
  - Refresh request detail
  - User appears in workflow tab

**Add Spectator Modal:**
- **Trigger:** Click "Add Spectator" button
- **Modal Content:**
  - Title: "Add Spectator to Workflow"
  - Explanation: "Spectators can view and comment but cannot approve"
  - **User Search Input:**
    - Same as Add Approver
  - **Multiple Selection:**
    - Can add multiple spectators at once
    - Show selected users as chips
  - **Action Buttons:**
    - "Add" button (primary)
    - "Cancel" button
- **After Adding:**
  - Close modal
  - Show success notification
  - User(s) appear in spectators panel
  - Notifications sent to added users

#### What You Can Do After Sprint 3:
- ✅ Approve workflow requests
- ✅ Reject workflow requests with reasons
- ✅ Track TAT for each approval level
- ✅ Receive automated TAT warnings and breach alerts
- ✅ View comprehensive approval timeline
- ✅ See real-time notifications
- ✅ Receive @mention notifications
- ✅ View all request details in tabs (overview, workflow, documents, activity)
- ✅ Add additional approvers dynamically
- ✅ Add spectators during workflow
- ✅ Monitor TAT with color-coded progress bars
- ✅ View complete activity history
- ✅ Full request management dashboard

#### Technical Complexity:
- **Backend:** Complex approval state machine, TAT calculations, cron jobs
- **Frontend:** Real-time updates, polling for notifications, complex UI states
- **Integration:** Multi-user scenarios, concurrent approvals, race conditions

---

### 📁 Sprint 4: Documents & Work Notes (Week 7)
**Status:** ⏳ Upcoming | **Focus:** Document management and collaboration

#### What This Sprint Delivers:
Complete document upload/download system, work notes API integration, and activity logging.

#### Frontend Advantage:
- ✅ **Work Notes UI:** Already complete with all functionality!
- ✅ **Document Upload UI:** Already complete from Figma!
- ⏱️ **Only need:** Backend API integration (2 days instead of 1 week!)

#### Detailed Functionality Breakdown:

**1. Document Management System (BE-401)**

**Backend Document Storage:**

**File Upload Handling:**
- Use Multer middleware for multipart/form-data
- Accept multiple file uploads simultaneously
- Maximum 10MB per file
- Supported types: PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, JPG, PNG, GIF

**Cloud Storage Integration:**
- **For Development:** Local file system storage
- **For Production:** GCP Cloud Storage
  - Upload files to GCP bucket
  - Generate signed URLs for secure access
  - Set expiration on URLs (24 hours)
  - Store file metadata in database

**Document APIs:**
- **POST /api/v1/workflows/:id/documents**
  - Upload document
  - Validate file type and size
  - Generate unique filename
  - Upload to storage
  - Create document record in database
  - Return document metadata
  
- **GET /api/v1/workflows/:id/documents**
  - Get all documents for workflow
  - Return metadata (name, size, type, uploader, date)
  - Include download/preview URLs
  
- **GET /api/v1/documents/:documentId**
  - Get specific document details
  - Return metadata
  
- **GET /api/v1/documents/:documentId/download**
  - Generate download URL
  - Return signed URL for direct download
  
- **GET /api/v1/documents/:documentId/preview**
  - Generate preview URL (for PDF/images)
  - Return signed URL for preview
  
- **DELETE /api/v1/documents/:documentId**
  - Soft delete document
  - Mark as deleted in database
  - Keep file in storage (for audit)
  - Only initiator or admin can delete

**Frontend Integration:**
- Connect upload component to POST API
- Show upload progress (0-100%)
- Handle upload errors (file too large, invalid type)
- Display uploaded files from GET API
- Implement preview for PDF/images
- Implement download for all files

**2. Work Notes & Chat System (BE-402)**

**Backend Work Notes APIs:**

**Work Note Structure:**
```json
{
  "note_id": "uuid",
  "request_id": "uuid",
  "user_id": "uuid",
  "message": "This is a work note with @mentions",
  "mentioned_users": ["user_id1", "user_id2"],
  "has_attachment": true,
  "is_priority": false,
  "reactions": {
    "👍": ["user_id1", "user_id3"],
    "❤️": ["user_id2"]
  },
  "created_at": "2025-11-12T10:00:00Z",
  "updated_at": "2025-11-12T10:05:00Z"
}
```

**Work Note APIs:**
- **GET /api/v1/workflows/:id/work-notes**
  - Get all work notes for workflow
  - Return in chronological order
  - Include user details (name, picture)
  - Include attachments
  - Include reactions
  
- **POST /api/v1/workflows/:id/work-notes**
  - Create new work note
  - Parse @mentions from message
  - Extract mentioned user IDs
  - Store message and mentions
  - Create notifications for mentioned users
  - Return created work note
  
- **PUT /api/v1/work-notes/:noteId**
  - Update work note (only by creator)
  - Allow editing within 10 minutes of creation
  - Update message content
  
- **DELETE /api/v1/work-notes/:noteId**
  - Delete work note (only by creator)
  - Soft delete
  
- **POST /api/v1/work-notes/:noteId/reactions**
  - Add emoji reaction to note
  - Support multiple emojis per note
  - Store user who reacted
  - Return updated reactions
  
- **POST /api/v1/work-notes/:noteId/attachments**
  - Upload attachment with work note
  - Handle file upload
  - Link to work note
  - Return attachment metadata

**@Mention Detection:**
- Parse message text for @mentions
- Match pattern: `@username` or `@"User Name"`
- Look up users in database
- Extract user IDs
- Store in mentioned_users array

**Mention Notifications:**
- When work note created with @mentions:
  - Create notification for each mentioned user
  - Notification type: WORK_NOTE_MENTION
  - Include message preview
  - Link to work notes section

**Frontend Integration (Already Complete!):**
- Connect chat component to GET API for loading messages
- Connect to POST API for sending messages
- Connect to reactions API for emoji reactions
- Connect to attachments API for file uploads
- Implement @mention autocomplete with user search
- Auto-refresh messages every 10 seconds
- Show typing indicators (optional)

**3. Activity Log System (BE-403)**

**Backend Activity Tracking:**

**Automated Activity Logging:**
- Log activities automatically through database triggers
- Log activities from service layer
- Capture all important events

**Activity Types:**
- REQUEST_CREATED - Workflow created as draft
- REQUEST_SUBMITTED - Workflow submitted for approval
- APPROVAL_ACTION - Request approved at a level
- REJECTION_ACTION - Request rejected
- APPROVER_ADDED - New approver added
- SPECTATOR_ADDED - New spectator added
- DOCUMENT_UPLOADED - Document uploaded
- DOCUMENT_DELETED - Document deleted
- WORK_NOTE_ADDED - Work note/comment added
- TAT_WARNING - TAT approaching deadline
- TAT_BREACH - TAT exceeded
- STATUS_CHANGED - Workflow status changed
- REQUEST_CLOSED - Workflow closed

**Activity APIs:**
- **GET /api/v1/workflows/:id/activities**
  - Get activity timeline
  - Return in reverse chronological order
  - Include user info for user actions
  - Include metadata (old/new values for changes)
  
- **GET /api/v1/workflows/:id/activities/:type**
  - Filter activities by type
  - Example: Get only approval actions

**Activity Display:**
- Generate human-readable descriptions
- Examples:
  - "Request created by John Doe"
  - "Approved by Jane Smith at Level 2"
  - "Document uploaded: proposal.pdf"
  - "TAT warning: Request approaching deadline"
  - "Status changed from PENDING to IN_PROGRESS"

#### What You Can Do After Sprint 4:
- ✅ Upload documents (multiple files at once)
- ✅ Preview PDF and image files
- ✅ Download any file
- ✅ Delete documents (with permission)
- ✅ Add work notes with @mentions
- ✅ React to messages with emojis
- ✅ Attach files to work notes
- ✅ Receive notifications for @mentions
- ✅ View complete activity timeline
- ✅ Filter activities by type
- ✅ Real-time collaboration through chat

---

### 📊 Sprint 5: Dashboard & Reporting (Week 8)
**Status:** ⏳ Upcoming | **Focus:** Analytics, AI conclusions, workflow closure

#### What This Sprint Delivers:
Dashboard with statistics and charts, AI-powered conclusion generation, workflow closure functionality, search/filter components, and final polish.

#### Detailed Functionality Breakdown:

**1. Dashboard Statistics (BE-501, FE-402)**

**Backend Dashboard APIs:**

**GET /api/v1/dashboard/stats:**
Returns comprehensive statistics for current user:
```json
{
  "total_requests": 45,
  "pending_approvals": 8,
  "approved_requests": 32,
  "rejected_requests": 5,
  "draft_requests": 3,
  "tat_breached": 2,
  "avg_approval_time_hours": 36.5,
  "requests_by_priority": {
    "STANDARD": 40,
    "EXPRESS": 5
  },
  "requests_by_status": {
    "DRAFT": 3,
    "PENDING": 5,
    "IN_PROGRESS": 3,
    "APPROVED": 32,
    "REJECTED": 5,
    "CLOSED": 37
  },
  "approval_trend_last_30_days": [
    {"date": "2025-10-15", "count": 2},
    {"date": "2025-10-16", "count": 3},
    ...
  ]
}
```

**GET /api/v1/dashboard/recent:**
Returns recent activities (last 10):
```json
{
  "recent_activities": [
    {
      "activity_type": "APPROVAL_ACTION",
      "request_id": "uuid",
      "request_number": "REQ-2025-00045",
      "description": "Approved by John Doe",
      "timestamp": "2025-11-12T10:00:00Z"
    },
    ...
  ]
}
```

**GET /api/v1/dashboard/pending-actions:**
Returns requests needing user's action:
```json
{
  "pending_actions": [
    {
      "request_id": "uuid",
      "request_number": "REQ-2025-00046",
      "title": "Approval for new office",
      "priority": "EXPRESS",
      "level": 2,
      "tat_status": "APPROACHING",
      "days_pending": 2
    },
    ...
  ]
}
```

**Frontend Dashboard Page:**

**Layout:**

**Top Row - Key Metrics Cards (4 columns):**
1. **Total Requests Card:**
   - Large number: "45"
   - Label: "Total Requests"
   - Icon: 📊
   - Subtitle: "All time"
   
2. **Pending Approvals Card:**
   - Large number: "8"
   - Label: "Pending Approvals"
   - Icon: ⏳
   - Subtitle: "Awaiting action"
   - Click to filter
   
3. **Approved Requests Card:**
   - Large number: "32"
   - Label: "Approved"
   - Icon: ✅
   - Subtitle: "Successfully completed"
   
4. **TAT Breached Card:**
   - Large number: "2"
   - Label: "TAT Breached"
   - Icon: 🚨
   - Subtitle: "Needs attention"
   - Red color if > 0

**Second Row - Charts (2 columns):**

1. **Requests by Status (Pie Chart):**
   - Using Recharts library
   - Segments for each status:
     - Draft (gray)
     - Pending (yellow)
     - In Progress (blue)
     - Approved (green)
     - Rejected (red)
     - Closed (dark gray)
   - Show percentages
   - Legend below chart
   - Interactive (click segment to filter)

2. **Requests by Priority (Bar Chart):**
   - Using Recharts library
   - Two bars: Standard vs Express
   - Different colors
   - Show counts
   - Y-axis: Count
   - X-axis: Priority type
   - Interactive

**Third Row - Trend & Actions (2 columns):**

1. **Approval Trend (Line Chart):**
   - Using Recharts library
   - Last 30 days trend
   - X-axis: Dates
   - Y-axis: Number of approvals
   - Line color: Blue
   - Show data points
   - Hover to see exact values
   - Date range selector (7 days, 30 days, 90 days)

2. **Pending Actions Widget:**
   - List of requests needing user's action
   - Each item shows:
     - Request number
     - Title (truncated)
     - Priority badge
     - TAT status indicator
     - Days pending
     - "Review" button
   - Scroll if more than 5 items
   - Click to go to request detail

**Fourth Row - Recent Activities:**
- **Recent Activities Widget:**
  - Table or list of last 10 activities
  - Columns:
    - Activity type icon
    - Description
    - Request number (clickable)
    - Timestamp (relative)
  - "View All" button to go to activity page
  - Auto-refresh every 30 seconds

**Dashboard Features:**
- **Date Range Filter (Top Right):**
  - Dropdown: Last 7 days, 30 days, 90 days, All time
  - Affects all stats and charts
  
- **Refresh Button:**
  - Manual refresh of data
  - Shows loading state
  
- **Export Button:**
  - Export dashboard data as PDF/Excel
  - Include all charts and stats

**2. AI Conclusion Generation (BE-502, FE-403)**

**Backend AI Integration:**

**AI Service Setup:**
- Integrate with OpenAI API (GPT-4) or Google Gemini
- Configure API key and model settings
- Set max tokens for response (500 tokens)

**Conclusion Generation Logic:**

**When to Generate:**
- After final approver approves request
- Before workflow returns to initiator for closure

**Input Data for AI:**
- Workflow title and description
- All approval level comments
- Work notes (relevant messages)
- Decision summary (approved/rejected at each level)
- TAT information
- Documents summary

**Prompt Template:**
```
Generate a concise conclusion for this workflow request:

Title: [Request Title]
Description: [Request Description]

Approval Journey:
- Level 1: Approved by [Name]. Comment: [Comment]
- Level 2: Approved by [Name]. Comment: [Comment]
...

Key Discussion Points from Work Notes:
- [Note 1]
- [Note 2]
...

Generate a professional conclusion summary (max 300 words) covering:
1. What was requested
2. Key discussion points
3. Final decision
4. Next steps (if any)
```

**AI Response Processing:**
- Call AI API with prompt
- Get generated conclusion
- Clean up and format response
- Store as `ai_generated_remark` in database
- Set `is_edited` to false initially

**Conclusion APIs:**

**POST /api/v1/workflows/:id/conclusion/generate:**
- Generate AI conclusion
- Compile input data
- Call AI API
- Store result
- Return generated conclusion

**PUT /api/v1/workflows/:id/conclusion:**
- Update conclusion (initiator only)
- Allow editing AI-generated text
- Set `is_edited` to true
- Store as `final_remark`

**GET /api/v1/workflows/:id/conclusion:**
- Get conclusion for workflow
- Return AI-generated and final (if edited)

**Frontend Conclusion UI:**

**Conclusion Section (After Final Approval):**

**For Initiator (Creator):**
- **Display AI-Generated Conclusion:**
  - Show in read-only card initially
  - Formatted text with proper paragraphs
  - Label: "AI-Generated Conclusion"
  
- **Edit Button:**
  - Opens edit modal
  - Modal shows:
    - Title: "Edit Conclusion"
    - Textarea with AI-generated text pre-filled
    - Character count (max 1000)
    - Rich text editor (bold, italic, lists)
    - "Save" button
    - "Cancel" button
  - After saving:
    - Update display
    - Show "Edited by [User]" badge
    - Close modal

- **Finalize Button:**
  - Visible only to initiator
  - Confirms final conclusion
  - Enables workflow closure

**For Other Users (Approvers, Spectators):**
- **Read-Only Display:**
  - Show final conclusion
  - Cannot edit
  - Show "Finalized by [Initiator]" info

**Conclusion Display Locations:**
- Request detail page (after approval)
- My Requests (approved requests)
- Closed Requests
- Email notifications (summary)

**3. Workflow Closure (BE-503, FE-404)**

**Backend Closure Logic:**

**PATCH /api/v1/workflows/:id/close:**

**Pre-Closure Validations:**
- Verify workflow is fully approved (all levels approved)
- Verify conclusion remark exists
- Verify user is initiator (creator)
- Verify workflow not already closed

**Closure Actions:**
1. Update workflow:
   - Set status to CLOSED
   - Set closure_date to current timestamp
   - Mark as final/immutable
   
2. Stop all TAT tracking:
   - Mark TAT records as complete
   - Calculate total time taken
   
3. Archive workflow data:
   - Create snapshot of final state
   - Preserve for audit
   
4. Send closure notifications:
   - To all participants (approvers, spectators)
   - Notification: "Workflow [REQ-ID] has been closed"
   - Include conclusion summary
   
5. Create final activity log:
   - Activity type: REQUEST_CLOSED
   - Description: "Request closed by [Initiator Name]"
   - Include closure date

**Frontend Closure UI:**

**Close Request Button (Request Detail Page):**

**Visibility:**
- Only shown to initiator (creator)
- Only after final approval
- Only if conclusion exists
- Not shown if already closed

**Button Placement:**
- Prominent button in top-right
- Label: "Close Request"
- Primary/success color
- Icon: Checkmark or lock

**Click Behavior:**
- Opens confirmation modal

**Close Request Modal:**
- **Title:** "Close Workflow Request"
- **Content:**
  - Request summary:
    - Request number
    - Title
    - Final status: APPROVED
    - Total approval time
  - Conclusion display:
    - Show final conclusion
    - Read-only
  - Warning message:
    - "Closing this request is final"
    - "This action cannot be undone"
    - "All participants will be notified"
- **Action Buttons:**
  - "Confirm Close" button (primary/green)
    - Shows loading spinner during API call
  - "Cancel" button (secondary)
    - Closes modal without action

**After Closure:**
- Close modal
- Show success notification: "Request closed successfully"
- Update page to show closed status
- Change button to "Closed" (disabled)
- Display closure date
- Navigate to Closed Requests OR stay on page
- All editing disabled

**4. Search & Filter Components (FE-501)**

**Global Search Bar:**
- **Location:** Top of request list pages
- **Features:**
  - Text input with search icon
  - Placeholder: "Search by title or request number..."
  - Debounce search (300ms delay)
  - Show search results as you type
  - Clear button (X icon)
  - Search on Enter key

**Filter Panel:**
- **Location:** Sidebar or top bar
- **Filters Available:**
  
  **1. Status Filter:**
  - Checkboxes for each status:
    - ☐ Draft
    - ☐ Pending
    - ☐ In Progress
    - ☐ Approved
    - ☐ Rejected
    - ☐ Closed
  - Select multiple
  - Show count for each status
  
  **2. Priority Filter:**
  - Radio buttons or checkboxes:
    - ☐ Standard
    - ☐ Express
  - Select one or both
  
  **3. Date Range Filter:**
  - Date picker component
  - "From" date input
  - "To" date input
  - Preset options:
    - Today
    - Last 7 days
    - Last 30 days
    - Last 90 days
    - Custom range
  
  **4. Department Filter:**
  - Dropdown select
  - List of all departments
  - Filter requests by initiator's department
  
  **5. Initiator Filter:**
  - User search input
  - @mention style autocomplete
  - Filter by who created the request

**Filter Actions:**
- **Apply Filters button:**
  - Apply selected filters
  - Update request list
  - Show loading state
  
- **Clear Filters button:**
  - Reset all filters
  - Reload full list

**Filter State Management:**
- **URL Query Parameters:**
  - Save filters in URL
  - Example: `?status=PENDING&priority=EXPRESS&from=2025-11-01`
  - Enable sharing filtered views
  - Browser back/forward works
  
- **Active Filter Display:**
  - Show active filters as chips/tags
  - Example: "Status: Pending" (X to remove)
  - "2 filters active" counter
  - Quick remove individual filters

**5. Responsive Design & Polish (FE-502)**

**Mobile Responsiveness:**

**Breakpoints:**
- Mobile: 320px - 767px
- Tablet: 768px - 1023px
- Desktop: 1024px+

**Mobile Optimizations:**
- **Sidebar:** Collapsible hamburger menu
- **Request Cards:** Full width, stacked vertically
- **Tables:** Convert to cards
- **Modals:** Full-screen on mobile
- **Forms:** Single column layout
- **Buttons:** Larger touch targets (44px minimum)
- **Navigation:** Bottom tab bar (optional)

**Tablet Optimizations:**
- **Sidebar:** Collapsible or always visible
- **Request Cards:** 2 per row
- **Tables:** Scrollable horizontally
- **Forms:** Two column layout

**Desktop:**
- **Sidebar:** Always visible
- **Request Cards:** 3 per row
- **Tables:** Full table view
- **Forms:** Optimized multi-column

**6. Loading States & Error Handling (FE-503)**

**Loading Skeletons:**
- **Request List Skeleton:**
  - Show placeholder cards
  - Animated shimmer effect
  - Same layout as actual cards
  
- **Request Detail Skeleton:**
  - Placeholder for all sections
  - Shimmer animation
  
- **Dashboard Skeleton:**
  - Placeholder cards for metrics
  - Placeholder charts

**Error States:**
- **Network Error:**
  - Show error message
  - "Retry" button
  - "Go Back" button
  
- **Empty State:**
  - Relevant icon
  - Message: "No requests found"
  - "Create New Request" button
  
- **Error Boundary:**
  - Catch React errors
  - Show friendly error page
  - "Report Issue" button

**7. Accessibility (FE-504)**

**ARIA Labels:**
- Add labels to all interactive elements
- Buttons have clear labels
- Form inputs have associated labels

**Keyboard Navigation:**
- All actions accessible via keyboard
- Tab order logical
- Enter/Space to activate buttons
- Esc to close modals

**Screen Reader Support:**
- Semantic HTML tags
- Alt text for images
- Proper heading hierarchy (H1, H2, H3)

**Color Contrast:**
- Meet WCAG AA standards
- Text contrast ratio >= 4.5:1
- Large text >= 3:1

#### What You Can Do After Sprint 5:
- ✅ View comprehensive dashboard with statistics
- ✅ See visual charts and graphs
- ✅ Generate AI-powered conclusions
- ✅ Edit AI conclusions before finalizing
- ✅ Close approved workflows
- ✅ Search requests by title/number
- ✅ Filter requests by multiple criteria
- ✅ Use on any device (responsive)
- ✅ Better loading and error states
- ✅ Accessible for all users

---

### 🧪 Sprint 6: Testing & Deployment (Weeks 9-10)
**Status:** ⏳ Upcoming | **Focus:** Quality assurance and production deployment

#### Week 9: Testing & Quality Assurance

**1. Backend Unit Testing (BE-601):**

**Service Tests:**
- Auth service: Login, register, token refresh
- Workflow service: CRUD operations, TAT calculations
- Approval service: Approve, reject, level transitions
- TAT service: Calculate elapsed time, status determination
- Notification service: Create, send, mark read
- Document service: Upload, download, delete

**Controller Tests:**
- API endpoint tests
- Request validation
- Response format
- Error handling

**Utility Tests:**
- Date calculations
- TAT business logic
- Email templates
- File validators

**Test Coverage:**
- Target: >80% code coverage
- Use Jest with ts-jest
- Mock external dependencies (database, storage, AI API)

**2. Backend Integration Testing (BE-602):**

**Complete Workflow Tests:**
- User registration → login → token
- Create workflow → submit → approve → close
- Multi-level approval flow (all 10 levels)
- Rejection flow
- TAT tracking and alerts
- Document upload → preview → download

**API Testing:**
- Use Supertest for HTTP testing
- Test all API endpoints
- Test authentication middleware
- Test authorization rules
- Test error responses
- Test pagination and filtering

**3. Frontend Unit Testing (FE-601):**

**Component Tests:**
- Login component
- Registration component
- Workflow wizard steps
- Request cards
- Approval modals
- Work notes chat
- Notification bell

**Redux Tests:**
- Slice reducers
- Async thunks
- Selectors

**Utility Tests:**
- Date formatting
- Validation functions
- API service helpers

**Test Coverage:**
- Target: >70% code coverage
- Use Vitest + React Testing Library
- Mock API calls

**4. Frontend Integration Testing (FE-602):**

**User Flow Tests:**
- Complete registration → login flow
- Create workflow → submit → view flow
- Approve/reject workflow flow
- Add work note flow
- Upload document flow

**Navigation Tests:**
- Route transitions
- Protected routes
- Redirect logic

**5. API Documentation (BE-603):**

**Swagger/OpenAPI Setup:**
- Document all endpoints
- Request schemas with examples
- Response schemas
- Authentication requirements
- Error responses
- Example requests/responses

**Postman Collection:**
- Create collection for all APIs
- Organize by feature
- Add example requests
- Add pre-request scripts (auth token)
- Share with team

#### Week 10: Optimization & Deployment

**6. Performance Optimization (BE-604, FE-603):**

**Backend:**
- Database query optimization
- Add indexes for frequent queries
- Optimize N+1 queries with eager loading
- Add response caching (Redis optional)
- Database connection pooling
- Compress API responses (gzip)
- Rate limiting per user

**Frontend:**
- Code splitting with React.lazy
- Lazy load images
- Bundle size optimization
- Tree shaking
- Memoize components (React.memo)
- Optimize Redux selectors
- Add service worker (optional)

**7. Deployment Setup (BE-605, FE-604):**

**Backend Deployment:**
- Create production Dockerfile
- Setup docker-compose for DB + Backend
- Configure environment variables
- Setup PM2 for process management
- Database migration scripts
- Setup CI/CD pipeline (GitHub Actions)
- Deploy to GCP Cloud Run or VM
- Configure logging and monitoring

**Frontend Deployment:**
- Create production Dockerfile with Nginx
- Production build configuration
- Environment variables for prod
- Setup CI/CD pipeline
- Deploy to GCP Cloud Run or Storage
- Configure CDN
- Setup SSL/HTTPS

**8. Final Testing & QA:**
- End-to-end testing
- User acceptance testing (UAT)
- Load testing
- Security testing
- Browser compatibility testing
- Mobile device testing

**9. Go-Live Checklist:**
- Database backup strategy
- Monitoring setup (logs, errors, performance)
- Error tracking (Sentry optional)
- Documentation complete
- User training materials
- Support plan

#### What You Achieve After Sprint 6:
- ✅ Fully tested application (>80% coverage)
- ✅ Complete API documentation
- ✅ Optimized performance
- ✅ Production deployment
- ✅ CI/CD pipelines configured
- ✅ Monitoring and logging in place
- ✅ Ready for production users!

---

## 🎯 Summary: Why Each Sprint Matters

**Sprint 0:** Foundation - Without proper setup, everything else fails  
**Sprint 1:** Authentication - Users need to login before anything else  
**Sprint 2:** Workflow Creation - Core feature, creates the workflows  
**Sprint 3:** Approvals - Makes workflows actually work, users can act  
**Sprint 4:** Collaboration - Documents and work notes enable teamwork  
**Sprint 5:** Analytics - Dashboard gives insights, AI adds intelligence  
**Sprint 6:** Quality - Testing ensures reliability, deployment makes it live  

**Each sprint builds on the previous one. You cannot skip or reorder them!**

---

## Backend Tasks

### **SPRINT 0: Backend Setup & Infrastructure**

#### **TASK-BE-001: Repository & Environment Setup**
**Priority:** Critical | **Estimated Time:** 0.5 days | **Status:** 🔄 In Progress
- [ ] Create `re-workflow-backend` repository
- [ ] Initialize Node.js 22 project with TypeScript 5.7
- [ ] Setup folder structure as per architecture document
- [ ] Configure `tsconfig.json` with strict mode
- [ ] Create `.env.example` and environment configuration
- [ ] Setup `.gitignore` for Node.js projects
- [ ] Initialize `package.json` with all dependencies

**Dependencies:** None  
**Deliverable:** Repository with basic structure

---

#### **TASK-BE-002: Database Setup & Schema**
**Priority:** Critical | **Estimated Time:** 1 day | **Status:** ⏳ Pending
- [ ] Install PostgreSQL 16 locally/Docker
- [ ] Create database `re_workflow_db`
- [ ] Implement complete database schema from architecture doc
- [ ] Create all tables with indexes and constraints
- [ ] Setup database triggers (request_number generation, timestamps)
- [ ] Create database views (vw_active_requests, vw_user_notifications)
- [ ] Insert initial system settings
- [ ] Document database connection configuration

**Dependencies:** None  
**Deliverable:** Complete PostgreSQL database with schema

---

#### **TASK-BE-003: Core Backend Configuration**
**Priority:** Critical | **Estimated Time:** 0.5 days | **Status:** ⏳ Pending
- [ ] Setup Express.js application (`src/app.ts`)
- [ ] Configure middleware (helmet, cors, body-parser)
- [ ] Setup Winston logger with file rotation
- [ ] Create error handling middleware
- [ ] Configure Morgan for HTTP logging
- [ ] Setup health check endpoint (`/health`)
- [ ] Create `src/server.ts` with graceful shutdown
- [ ] Test server startup and connection

**Dependencies:** TASK-BE-001  
**Deliverable:** Running Express server with logging

---

#### **TASK-BE-004: Sequelize ORM Setup**
**Priority:** Critical | **Estimated Time:** 1 day | **Status:** ⏳ Pending
- [ ] Configure Sequelize connection (`src/config/database.ts`)
- [ ] Create all Sequelize models matching database schema
  - User model
  - WorkflowRequest model
  - ApprovalLevel model
  - Participant model
  - Document model
  - WorkNote model
  - Activity model
  - Notification model
  - TATTracking model
  - ConclusionRemark model
- [ ] Define model associations (relationships)
- [ ] Test database connectivity
- [ ] Create model index file (`src/models/index.ts`)

**Dependencies:** TASK-BE-002  
**Deliverable:** Complete ORM layer with type definitions

---

### **SPRINT 1: SSO Authentication & User Management**

#### **TASK-BE-101: SSO Integration (Awaiting Confirmation)**
**Priority:** Critical | **Estimated Time:** 1.5 days | **Status:** ⏳ Awaiting SSO Details
- [ ] Configure SSO Bridge integration (`src/config/sso.ts`)
- [ ] Implement SSO callback handler (`src/services/auth.service.ts`)
- [ ] User auto-sync from Active Directory
- [ ] JWT token generation for app sessions
- [ ] Authentication middleware (`src/middlewares/auth.middleware.ts`)
- [ ] Auth APIs:
  - GET `/api/v1/auth/login` - Redirect to SSO
  - GET `/api/v1/auth/callback` - Handle SSO callback
  - POST `/api/v1/auth/logout` - Logout
  - GET `/api/v1/auth/me` - Get current user

**Dependencies:** TASK-BE-004  
**Deliverable:** SSO integration (no login/signup screens needed)

---

#### **TASK-BE-102: User Profile Management**
**Priority:** Medium | **Estimated Time:** 0.5 days
- [ ] Create user controller (`src/controllers/user.controller.ts`)
  - GET `/api/v1/users` - Get all active users (for @tagging)
  - GET `/api/v1/users/search?q=` - Search users by name/email
  - GET `/api/v1/users/:id` - Get user details
  - PUT `/api/v1/users/:id` - Update user profile (phone, picture only)
- [ ] Create user service (`src/services/user.service.ts`)
- [ ] Create user routes (`src/routes/user.routes.ts`)

**Dependencies:** TASK-BE-101  
**Deliverable:** User search and profile APIs

**Note:** User data synced from Active Directory (read-only except phone/picture)

---

### **SPRINT 2: Core Workflow Creation**

#### **TASK-BE-201: Workflow Request Creation APIs**
**Priority:** Critical | **Estimated Time:** 10 hours
- [ ] Create workflow service (`src/services/workflow.service.ts`)
  - Create draft workflow
  - Update draft workflow
  - Submit workflow for approval
  - Auto-generate request number (REQ-YYYY-00001)
  - Calculate total TAT from all levels
  - Set TAT start/end dates based on priority
- [ ] Create workflow controller (`src/controllers/workflow.controller.ts`)
  - POST `/api/v1/workflows` - Create new workflow
  - PUT `/api/v1/workflows/:id` - Update draft
  - GET `/api/v1/workflows/:id` - Get workflow details
  - DELETE `/api/v1/workflows/:id` - Delete draft
  - PATCH `/api/v1/workflows/:id/submit` - Submit for approval
- [ ] Implement TAT calculation utility
  - Calculate working days vs calendar days
  - Handle priority (STANDARD vs EXPRESS)
- [ ] Create workflow validation schemas (Zod)
- [ ] Test workflow creation flow end-to-end

**Dependencies:** TASK-BE-103  
**Deliverable:** Workflow creation APIs with TAT calculation

---

#### **TASK-BE-202: Approval Hierarchy Management**
**Priority:** Critical | **Estimated Time:** 8 hours
- [ ] Create approval service (`src/services/approval.service.ts`)
  - Create approval levels (up to 10 levels)
  - Add approver to specific level
  - Update approval level TAT
  - Get approval hierarchy for request
  - Get current approval level
  - Move to next approval level
- [ ] Create approval controller (`src/controllers/approval.controller.ts`)
  - GET `/api/v1/workflows/:id/approvals` - Get hierarchy
  - POST `/api/v1/workflows/:id/approvals` - Add approval level
  - GET `/api/v1/workflows/:id/approvals/current` - Current level
- [ ] Validate max 10 approval levels
- [ ] Ensure unique level numbers per request

**Dependencies:** TASK-BE-201  
**Deliverable:** Approval hierarchy management

---

#### **TASK-BE-203: Participant Management**
**Priority:** High | **Estimated Time:** 4 hours
- [ ] Create participant service (`src/services/participant.service.ts`)
  - Add spectator to request
  - Remove spectator
  - Get all participants
  - Check participant permissions
- [ ] Create participant controller (`src/controllers/participant.controller.ts`)
  - GET `/api/v1/workflows/:id/participants` - Get all
  - POST `/api/v1/workflows/:id/participants` - Add spectator
  - DELETE `/api/v1/workflows/:id/participants/:participantId` - Remove
  - GET `/api/v1/workflows/:id/spectators` - Get spectators only
- [ ] Log participant additions in activity

**Dependencies:** TASK-BE-201  
**Deliverable:** Participant management APIs

---

#### **TASK-BE-204: Workflow List & Filtering APIs**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Implement workflow listing with filters
  - GET `/api/v1/workflows` - Get all workflows (with filters)
  - GET `/api/v1/workflows/my-requests` - User's requests
  - GET `/api/v1/workflows/open` - Open/pending requests
  - GET `/api/v1/workflows/closed` - Closed requests
  - GET `/api/v1/workflows/assigned-to-me` - Assigned requests
- [ ] Implement pagination (page, limit, sortBy, sortOrder)
- [ ] Implement filters (status, priority, date range)
- [ ] Implement search (by title, description, request_number)
- [ ] Add full-text search using PostgreSQL

**Dependencies:** TASK-BE-201  
**Deliverable:** Workflow listing with search/filter

---

### **SPRINT 3: Approval Actions & Notifications**

#### **TASK-BE-301: Approval/Rejection Actions**
**Priority:** Critical | **Estimated Time:** 10 hours
- [ ] Implement approval action workflow
  - PATCH `/api/v1/workflows/:id/approvals/:levelId/approve`
  - PATCH `/api/v1/workflows/:id/approvals/:levelId/reject`
- [ ] Approval logic:
  - Validate approver is current level approver
  - Validate mandatory comments field
  - Update approval level status to APPROVED
  - Move workflow to next level OR close if final approver
  - Update workflow status (IN_PROGRESS, APPROVED)
  - Stop TAT for current level
  - Start TAT for next level
  - Log activity
- [ ] Rejection logic:
  - Validate approver authorization
  - Mandatory rejection comments
  - Mark workflow as REJECTED and CLOSED
  - Stop TAT tracking
  - Send notification to initiator
  - Log activity
- [ ] Create activity logging service

**Dependencies:** TASK-BE-202  
**Deliverable:** Working approval/rejection flow

---

#### **TASK-BE-302: TAT Tracking & Monitoring**
**Priority:** Critical | **Estimated Time:** 8 hours
- [ ] Create TAT service (`src/services/tat.service.ts`)
  - Calculate elapsed time for current level
  - Calculate remaining time
  - Calculate percentage TAT used
  - Determine TAT status (ON_TRACK, APPROACHING, BREACHED)
  - Update TAT tracking table
- [ ] Implement TAT monitoring cron job (`src/jobs/tatMonitor.job.ts`)
  - Run every 30 minutes
  - Check all active requests
  - Identify approaching deadlines (80% threshold)
  - Identify breached TATs (100%+)
  - Update tat_tracking table
  - Trigger reminder notifications
- [ ] Create TAT APIs
  - GET `/api/v1/workflows/:id/tat` - Get TAT status
  - GET `/api/v1/tat/breached` - Get breached requests
  - GET `/api/v1/tat/approaching` - Get approaching deadlines

**Dependencies:** TASK-BE-301  
**Deliverable:** TAT tracking system with cron

---

#### **TASK-BE-303: Notification System**
**Priority:** High | **Estimated Time:** 8 hours
- [ ] Create notification service (`src/services/notification.service.ts`)
  - Create notification
  - Send notification to user(s)
  - Mark notification as read
  - Mark all as read
  - Delete notification
  - Get user notifications
  - Get unread count
- [ ] Notification triggers:
  - New workflow assignment
  - Workflow approval/rejection
  - TAT warning (80% threshold)
  - TAT breach (100%+)
  - Work note mention (@user)
  - Document upload
  - Spectator added
- [ ] Create notification controller
  - GET `/api/v1/notifications` - Get user notifications
  - GET `/api/v1/notifications/unread` - Unread only
  - PATCH `/api/v1/notifications/:id/read` - Mark as read
  - PATCH `/api/v1/notifications/mark-all-read` - Mark all
  - DELETE `/api/v1/notifications/:id` - Delete
- [ ] Add notification priority levels

**Dependencies:** TASK-BE-301  
**Deliverable:** Complete notification system

---

### **SPRINT 4: Documents & Work Notes**

#### **TASK-BE-401: Document Management System**
**Priority:** Critical | **Estimated Time:** 10 hours
- [ ] Setup file upload with Multer
- [ ] Configure GCP Cloud Storage (or local storage for dev)
- [ ] Create storage service (`src/services/storage.service.ts`)
  - Upload file to cloud storage
  - Generate signed URL for file access
  - Delete file from storage
  - Validate file type and size
- [ ] Create document service (`src/services/document.service.ts`)
  - Upload document
  - Get document metadata
  - Get document download URL
  - Delete document
  - Get all documents for request
- [ ] Create document controller
  - POST `/api/v1/workflows/:id/documents` - Upload
  - GET `/api/v1/workflows/:id/documents` - Get all
  - GET `/api/v1/documents/:documentId` - Get details
  - GET `/api/v1/documents/:documentId/download` - Download URL
  - DELETE `/api/v1/documents/:documentId` - Delete
  - GET `/api/v1/documents/:documentId/preview` - Preview URL
- [ ] File validation (max 10MB, allowed types)
- [ ] Support Google Docs/Sheets links

**Dependencies:** TASK-BE-301  
**Deliverable:** Document upload/download APIs

---

#### **TASK-BE-402: Work Notes & Chat System**
**Priority:** High | **Estimated Time:** 8 hours
- [ ] Create work note service (`src/services/workNote.service.ts`)
  - Create work note
  - Update work note
  - Delete work note
  - Add reaction to note
  - Add attachment to note
  - Get all notes for request
  - Parse @mentions from message
- [ ] Create work note controller
  - GET `/api/v1/workflows/:id/work-notes` - Get all notes
  - POST `/api/v1/workflows/:id/work-notes` - Add note
  - PUT `/api/v1/work-notes/:noteId` - Update note
  - DELETE `/api/v1/work-notes/:noteId` - Delete note
  - POST `/api/v1/work-notes/:noteId/reactions` - Add reaction
  - POST `/api/v1/work-notes/:noteId/attachments` - Add attachment
- [ ] Implement @mention detection
- [ ] Send notifications to mentioned users
- [ ] Support file attachments in notes
- [ ] Log work note activities

**Dependencies:** TASK-BE-303  
**Deliverable:** Work notes/chat APIs

---

#### **TASK-BE-403: Activity Log System**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Create activity service (`src/services/activity.service.ts`)
  - Log activity automatically
  - Get activity timeline
  - Filter activities by type
- [ ] Activity tracking for:
  - Request created
  - Request submitted
  - Approval/rejection
  - Approver/spectator added
  - Document uploaded/deleted
  - Work note added
  - TAT warning/breach
  - Status changes
- [ ] Create activity APIs
  - GET `/api/v1/workflows/:id/activities` - Get timeline
  - GET `/api/v1/workflows/:id/activities/:type` - Filter by type
- [ ] Display user-friendly activity descriptions

**Dependencies:** TASK-BE-301  
**Deliverable:** Activity logging system

---

### **SPRINT 5: Dashboard & Reporting**

#### **TASK-BE-501: Dashboard Statistics APIs**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create dashboard service (`src/services/dashboard.service.ts`)
- [ ] Implement dashboard statistics
  - Total requests by user
  - Pending approvals count
  - Approved/rejected count
  - TAT breach count
  - Requests by priority
  - Requests by status
  - Average approval time
- [ ] Create dashboard APIs
  - GET `/api/v1/dashboard/stats` - Get statistics
  - GET `/api/v1/dashboard/recent` - Recent activities
  - GET `/api/v1/dashboard/pending-actions` - Pending count
- [ ] Add date range filters
- [ ] Cache dashboard data for performance

**Dependencies:** TASK-BE-301  
**Deliverable:** Dashboard APIs with statistics

---

#### **TASK-BE-502: AI Conclusion Generation**
**Priority:** Medium | **Estimated Time:** 6 hours
- [ ] Setup AI service integration (OpenAI/Gemini)
- [ ] Create AI service (`src/services/ai.service.ts`)
  - Generate conclusion from workflow data
  - Summarize work notes
  - Extract key decision points
  - Generate conclusion remark
- [ ] Create conclusion APIs
  - POST `/api/v1/workflows/:id/conclusion/generate` - Generate
  - PUT `/api/v1/workflows/:id/conclusion` - Update
  - GET `/api/v1/workflows/:id/conclusion` - Get
- [ ] Allow initiator to edit AI-generated conclusion
- [ ] Store both AI-generated and final remarks

**Dependencies:** TASK-BE-402  
**Deliverable:** AI-powered conclusion generation

---

#### **TASK-BE-503: Workflow Closure**
**Priority:** High | **Estimated Time:** 4 hours
- [ ] Implement workflow closure endpoint
  - PATCH `/api/v1/workflows/:id/close` - Close workflow
- [ ] Closure logic:
  - Only initiator can close after final approval
  - Require conclusion remark (AI or manual)
  - Update workflow status to CLOSED
  - Set closure_date
  - Send closure notifications to all participants
  - Archive workflow data
  - Log closure activity
- [ ] Validate closure permissions

**Dependencies:** TASK-BE-502  
**Deliverable:** Workflow closure functionality

---

### **SPRINT 6: Testing & Optimization**

#### **TASK-BE-601: Unit Testing**
**Priority:** High | **Estimated Time:** 10 hours
- [ ] Setup Jest + ts-jest configuration
- [ ] Write unit tests for services:
  - Auth service tests (login, register, token)
  - Workflow service tests (CRUD, submit)
  - Approval service tests (approve, reject)
  - TAT service tests (calculation, tracking)
  - Notification service tests
  - Document service tests
  - Work note service tests
- [ ] Achieve >80% code coverage
- [ ] Test edge cases and error scenarios
- [ ] Mock external dependencies

**Dependencies:** All Sprint 1-5 tasks  
**Deliverable:** Comprehensive test suite

---

#### **TASK-BE-602: Integration Testing**
**Priority:** High | **Estimated Time:** 8 hours
- [ ] Setup Supertest for API testing
- [ ] Test complete workflows:
  - User registration → login → create workflow
  - Workflow creation → submission → approval
  - Multi-level approval flow
  - Rejection workflow
  - TAT tracking and notifications
  - Document upload and retrieval
- [ ] Test error handling and validation
- [ ] Test authorization and permissions
- [ ] Test pagination and filtering

**Dependencies:** TASK-BE-601  
**Deliverable:** Integration test suite

---

#### **TASK-BE-603: API Documentation**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Setup Swagger/OpenAPI documentation
- [ ] Document all API endpoints with:
  - Request/response schemas
  - Query parameters
  - Request body structure
  - Response codes
  - Authentication requirements
  - Example requests/responses
- [ ] Host documentation at `/api-docs`
- [ ] Create Postman collection

**Dependencies:** All API tasks  
**Deliverable:** Complete API documentation

---

#### **TASK-BE-604: Performance Optimization**
**Priority:** Medium | **Estimated Time:** 6 hours
- [ ] Add database query optimization
- [ ] Implement response caching (Redis optional)
- [ ] Add database connection pooling
- [ ] Optimize N+1 queries with eager loading
- [ ] Add pagination to all list endpoints
- [ ] Implement rate limiting per user
- [ ] Add request/response compression
- [ ] Performance testing and profiling

**Dependencies:** TASK-BE-602  
**Deliverable:** Optimized backend performance

---

#### **TASK-BE-605: Deployment Setup**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create Dockerfile for backend
- [ ] Create docker-compose.yml (backend + PostgreSQL)
- [ ] Setup environment variables for production
- [ ] Configure PM2 for process management
- [ ] Setup database migration scripts
- [ ] Create deployment scripts
- [ ] Configure GCP Cloud Run (or VM)
- [ ] Setup CI/CD pipeline (GitHub Actions)
- [ ] Configure logging and monitoring

**Dependencies:** TASK-BE-604  
**Deliverable:** Deployment-ready backend

---

## Frontend Tasks

### **SPRINT 0: Frontend Setup & Infrastructure**

#### **TASK-FE-001: Repository & Environment Setup**
**Priority:** Critical | **Estimated Time:** 4 hours
- [ ] Create `re-workflow-frontend` repository
- [ ] Initialize React 19 project with Vite 6
- [ ] Setup TypeScript 5.7 configuration
- [ ] Setup folder structure as per architecture
- [ ] Configure `tsconfig.json` with strict mode
- [ ] Create `.env.example` for environment variables
- [ ] Setup `.gitignore` for React projects
- [ ] Initialize `package.json` with dependencies

**Dependencies:** None  
**Deliverable:** Repository with React + TypeScript

---

#### **TASK-FE-002: UI Framework & Styling Setup**
**Priority:** Critical | **Estimated Time:** 4 hours
- [ ] Install Material-UI 6.3 (MUI)
- [ ] Install @emotion for styling
- [ ] Configure MUI theme (`src/assets/styles/theme.ts`)
  - Primary/secondary colors
  - Typography settings
  - Breakpoints for responsive design
- [ ] Create global CSS variables
- [ ] Setup CSS reset and normalize
- [ ] Configure responsive layout breakpoints

**Dependencies:** TASK-FE-001  
**Deliverable:** UI framework configured

---

#### **TASK-FE-003: Redux Store & State Management**
**Priority:** Critical | **Estimated Time:** 4 hours
- [ ] Install Redux Toolkit 2.5 and React-Redux
- [ ] Create Redux store (`src/redux/store.ts`)
- [ ] Create typed hooks (`src/redux/hooks.ts`)
- [ ] Create initial slices:
  - authSlice (user, token, isAuthenticated)
  - uiSlice (loading, errors, notifications)
  - workflowSlice (workflows, currentWorkflow)
  - approvalSlice (approvals, currentLevel)
  - notificationSlice (notifications, unreadCount)
  - documentSlice (documents)
  - workNoteSlice (notes)
  - participantSlice (participants, spectators)
- [ ] Configure Redux DevTools
- [ ] Setup persist for auth state (localStorage)

**Dependencies:** TASK-FE-001  
**Deliverable:** Redux store configured

---

#### **TASK-FE-004: API Service Layer Setup**
**Priority:** Critical | **Estimated Time:** 4 hours
- [ ] Create Axios instance (`src/services/api.ts`)
- [ ] Configure base URL from environment
- [ ] Setup request interceptors (add JWT token)
- [ ] Setup response interceptors (error handling)
- [ ] Handle token refresh logic
- [ ] Handle 401 unauthorized (redirect to login)
- [ ] Create service files:
  - `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`

**Dependencies:** TASK-FE-003  
**Deliverable:** API service layer with interceptors

---

#### **TASK-FE-005: Routing & Navigation Setup**
**Priority:** High | **Estimated Time:** 3 hours
- [ ] Install React Router DOM 7.1
- [ ] Create routing configuration (`src/routes/AppRoutes.tsx`)
- [ ] Define all routes:
  - `/login` - Login page
  - `/register` - Registration page
  - `/forgot-password` - Password reset request
  - `/reset-password/:token` - Reset password
  - `/dashboard` - Dashboard (protected)
  - `/workflows/create` - Create request (protected)
  - `/workflows/my-requests` - My requests (protected)
  - `/workflows/open` - Open requests (protected)
  - `/workflows/closed` - Closed requests (protected)
  - `/workflows/:id` - Request detail (protected)
  - `/unauthorized` - 403 page
  - `/not-found` - 404 page
- [ ] Create PrivateRoute component (auth check)
- [ ] Create PublicRoute component (redirect if authenticated)

**Dependencies:** TASK-FE-003  
**Deliverable:** Complete routing structure

---

#### **TASK-FE-006: Common Components Library**
**Priority:** High | **Estimated Time:** 8 hours
- [ ] Create reusable components:
  - **Button** component (primary, secondary, danger variants)
  - **Input** component (text, email, password, textarea)
  - **Dropdown/Select** component
  - **Modal** component (reusable dialog)
  - **Card** component
  - **Table** component with sorting
  - **Tabs** component
  - **Pagination** component
  - **Loader/Spinner** component
  - **Notification/Toast** component (react-toastify)
  - **ErrorBoundary** component
- [ ] Create component tests for each
- [ ] Add TypeScript interfaces for props

**Dependencies:** TASK-FE-002  
**Deliverable:** Reusable component library

---

#### **TASK-FE-007: Layout Components**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create Header component
  - Logo and app name
  - User profile dropdown
  - Notification bell icon with count
  - Logout button
- [ ] Create Sidebar/Navigation component
  - Dashboard link
  - My Requests link
  - Open Requests link
  - Closed Requests link
  - Raise New Request button
  - Active route highlighting
- [ ] Create Footer component
- [ ] Create PageLayout component (header + sidebar + content)
- [ ] Make layout responsive (mobile, tablet, desktop)

**Dependencies:** TASK-FE-006  
**Deliverable:** Complete layout structure

---

### **SPRINT 1: SSO Authentication & User Management**

#### **TASK-FE-101: SSO Callback Handler & Protected Routes**
**Priority:** Critical | **Estimated Time:** 1 day | **Status:** ⏳ Pending
- [ ] Create SSO Callback page (`src/pages/Auth/SSOCallback.tsx`)
  - Handle OAuth2 callback from SSO
  - Extract authorization code from URL params
  - Call backend callback API (GET /api/v1/auth/callback?code=XXX)
  - Receive JWT token from backend
  - Store JWT in Redux + localStorage
  - Redirect to dashboard on success
  - Handle SSO errors (access denied, invalid code)
  - Show loading spinner during authentication
- [ ] Update route configuration (`src/routes/AppRoutes.tsx`)
  - Add `/auth/callback` route (public)
  - Add SSO redirect for unauthenticated users
- [ ] Create PrivateRoute component
  - Check if user authenticated (JWT exists)
  - Redirect to SSO login if not authenticated
  - Allow access if authenticated
- [ ] Create PublicRoute component (optional)
  - Redirect to dashboard if already authenticated
- [ ] Test SSO flow end-to-end

**Dependencies:** TASK-FE-004, TASK-FE-005  
**Deliverable:** Working SSO authentication flow

**Note:** No login/signup/password reset pages needed (SSO handles everything)

---

#### **TASK-FE-102: Login Button & Logout Functionality**
**Priority:** High | **Estimated Time:** 0.5 days | **Status:** ⏳ Pending
- [ ] Create "Login with SSO" button on landing page
  - Redirects to GET /api/v1/auth/login
  - Backend redirects to SSO Bridge
  - Simple button, no form needed
- [ ] Implement logout functionality (Header component)
  - Create logout Redux action
  - Clear user state from Redux
  - Clear JWT from localStorage
  - Call POST /api/v1/auth/logout
  - Redirect to SSO logout URL
  - Show "Logged out successfully" message
- [ ] Add logout button in user profile dropdown

**Dependencies:** TASK-FE-101  
**Deliverable:** Login/logout functionality

---

#### **TASK-FE-103: User Profile & Header**
**Priority:** Medium | **Estimated Time:** 1 day | **Status:** ⏳ Pending
- [ ] Fetch current user from SSO (GET /api/v1/auth/me)
  - Get user details (name, email, employee ID, department, phone)
  - Display in Redux state
  - Show in header dropdown
- [ ] Create user profile dropdown in header
  - User avatar/profile picture
  - Display name and email
  - Department name
  - Employee ID
  - Logout button
- [ ] Create Edit Profile modal (limited fields)
  - Update phone number (only editable field)
  - Update profile picture
  - Connect to PUT /api/v1/users/:id
  - Other fields (name, email, employee ID) are read-only (from AD)
- [ ] User profile page (optional)
  - View complete profile
  - See department, designation
  - View workflow statistics

**Dependencies:** TASK-FE-007, TASK-FE-101  
**Deliverable:** User profile display and limited editing

**Note:** Most user info comes from Active Directory (read-only), only phone/picture editable

---

### **SPRINT 2: Core Workflow Creation**

#### **TASK-FE-201: Create Request - Wizard Structure**
**Priority:** Critical | **Estimated Time:** 6 hours
- [ ] Create CreateRequest page (`src/pages/CreateRequest/CreateRequest.tsx`)
- [ ] Implement 6-step wizard with stepper:
  1. Template Selection
  2. Basic Information
  3. Approval Workflow
  4. Participants & Access
  5. Documents & Attachments
  6. Review & Submit
- [ ] Create WizardStepper component
  - Progress indicator (1/6, 2/6, etc.)
  - Active step highlighting
  - Clickable steps (if previous steps complete)
- [ ] Add Next/Previous navigation buttons
- [ ] Save draft functionality (auto-save)
- [ ] Store wizard state in Redux

**Dependencies:** TASK-FE-007  
**Deliverable:** Wizard navigation structure

---

#### **TASK-FE-202: Step 1 - Template Selection**
**Priority:** High | **Estimated Time:** 3 hours
- [ ] Create Template Selection step
- [ ] Show two options:
  - Custom Request (Non-Templatized) - Enabled
  - Template Request - Disabled (future scope)
- [ ] Visual card-based selection
- [ ] Require selection before proceeding
- [ ] Save selection to Redux state
- [ ] Add helpful description for each option

**Dependencies:** TASK-FE-201  
**Deliverable:** Template selection step

---

#### **TASK-FE-203: Step 2 - Basic Information**
**Priority:** Critical | **Estimated Time:** 6 hours
- [ ] Create Basic Information step
- [ ] Form fields:
  - **Request Title** (max 500 chars, required)
  - **Detailed Description** (rich text editor, required)
    - Support bold, italic, underline
    - Support tables, lists
    - Support links
  - **Priority Level** (radio buttons, required)
    - Standard (working days)
    - Express (calendar days)
- [ ] Form validation (all fields required)
- [ ] Rich text editor integration (Quill/Draft.js/TinyMCE)
- [ ] Save to Redux state
- [ ] Character count indicators

**Dependencies:** TASK-FE-201  
**Deliverable:** Basic information form

---

#### **TASK-FE-204: Step 3 - Approval Workflow**
**Priority:** Critical | **Estimated Time:** 10 hours
- [ ] Create Approval Workflow step
- [ ] Dynamic approval level creation (max 10 levels)
- [ ] For each level:
  - Level name/title input
  - Approver selection with @mention/search
  - TAT input (hours or days dropdown)
  - Add/Remove level buttons
- [ ] User search/tagging component
  - Search users by name/email
  - Display user dropdown with profile pic
  - Select user as approver
- [ ] Real-time TAT calculation
  - Sum all level TATs
  - Display total TAT prominently
- [ ] Approval Flow Summary (read-only view)
  - Show all levels in hierarchy
  - Show approvers and TAT for each
- [ ] TAT Summary widget
- [ ] Validation (at least 1 approver, valid TAT)
- [ ] Save approval hierarchy to Redux

**Dependencies:** TASK-FE-203  
**Deliverable:** Approval workflow builder

---

#### **TASK-FE-205: Step 4 - Participants & Access**
**Priority:** High | **Estimated Time:** 4 hours
- [ ] Create Participants step
- [ ] Add Spectators section
  - @mention/search component (reuse from Step 3)
  - Add multiple spectators
  - Display added spectators with remove option
- [ ] Display participant permissions
  - Spectators can view and comment
  - Spectators cannot approve
- [ ] Save participants to Redux state
- [ ] Validation (optional spectators)

**Dependencies:** TASK-FE-204  
**Deliverable:** Participant management step

---

#### **TASK-FE-206: Step 5 - Documents & Attachments**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create Documents step
- [ ] File upload component (react-dropzone)
  - Drag-and-drop area
  - Browse files button
  - Multiple file upload
  - File type validation (PDF, Word, Excel, PPT, images)
  - File size validation (max 10MB per file)
- [ ] Display uploaded files list
  - File name, size, type
  - Preview icon for PDF/images
  - Remove file option
- [ ] Google Docs/Sheets link section
  - Input for Google Docs URL
  - Input for Google Sheets URL
  - Validate Google URLs
- [ ] Upload progress indicators
- [ ] Save file metadata to Redux (actual upload on submit)

**Dependencies:** TASK-FE-205  
**Deliverable:** Document upload step

---

#### **TASK-FE-207: Step 6 - Review & Submit**
**Priority:** Critical | **Estimated Time:** 6 hours
- [ ] Create Review & Submit step
- [ ] Display comprehensive summary:
  - **Request Overview**
    - Request type, priority, title
  - **Basic Information**
    - Description (formatted)
    - Priority level
  - **Approval Workflow**
    - All levels with approvers and TAT
    - Total TAT calculation
  - **Participants**
    - List of spectators
  - **Documents**
    - List of attached files
    - Google Docs/Sheets links
- [ ] Add Edit buttons for each section (go back to step)
- [ ] Two action buttons:
  - **Save as Draft** (POST /api/v1/workflows with is_draft=true)
  - **Submit Request** (POST /api/v1/workflows + PATCH /submit)
- [ ] Loading state during submission
- [ ] Success notification and redirect to request detail
- [ ] Error handling and display

**Dependencies:** TASK-FE-206  
**Deliverable:** Review & submit workflow

---

#### **TASK-FE-208: Workflow Creation API Integration**
**Priority:** Critical | **Estimated Time:** 6 hours
- [ ] Connect wizard to backend APIs
- [ ] Implement workflow creation flow:
  1. POST /api/v1/workflows (create draft)
  2. Upload documents (POST /api/v1/workflows/:id/documents)
  3. Add approval levels (POST /api/v1/workflows/:id/approvals)
  4. Add spectators (POST /api/v1/workflows/:id/participants)
  5. Submit workflow (PATCH /api/v1/workflows/:id/submit)
- [ ] Handle API errors at each step
- [ ] Show loading states
- [ ] Implement retry logic
- [ ] Clear wizard state after successful submission

**Dependencies:** TASK-FE-207  
**Deliverable:** Fully integrated workflow creation

---

### **SPRINT 3: Request Management & Approval Actions**

#### **TASK-FE-301: My Requests Page**
**Priority:** Critical | **Estimated Time:** 8 hours
- [ ] Create My Requests page (`src/pages/MyRequests/MyRequests.tsx`)
- [ ] Fetch user's workflows (GET /api/v1/workflows/my-requests)
- [ ] Display category tabs:
  - Total
  - In Progress
  - Approved
  - Rejected
  - Draft
- [ ] Request card component displaying:
  - Request number (REQ-YYYY-00001)
  - Title
  - Priority badge (EXPRESS/STANDARD)
  - Status badge (color-coded)
  - Current approval level
  - Submission date
  - Estimated completion date
- [ ] Implement search functionality
- [ ] Implement filters (status, priority, date range)
- [ ] Implement sorting (date, priority, status)
- [ ] Implement pagination
- [ ] Click to navigate to request detail

**Dependencies:** TASK-FE-007  
**Deliverable:** My Requests listing page

---

#### **TASK-FE-302: Open & Closed Requests Pages**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create Open Requests page
  - Fetch GET /api/v1/workflows/open
  - Show requests assigned to user or involving user
  - Same card layout as My Requests
  - Filters and search
- [ ] Create Closed Requests page
  - Fetch GET /api/v1/workflows/closed
  - Show completed workflows
  - Display conclusion remarks
  - Filters and search
- [ ] Reuse request card component from TASK-FE-301
- [ ] Add loading states
- [ ] Handle empty states (no requests)

**Dependencies:** TASK-FE-301  
**Deliverable:** Open and Closed request pages

---

#### **TASK-FE-303: Request Detail Page - Overview Tab**
**Priority:** Critical | **Estimated Time:** 8 hours
- [ ] Create Request Detail page (`src/pages/RequestDetail/RequestDetail.tsx`)
- [ ] Fetch workflow details (GET /api/v1/workflows/:id)
- [ ] Display request information:
  - Request number
  - Title
  - Description (formatted HTML)
  - Initiator name, department, contact
  - Priority badge
  - Status badge
  - Created date
  - Submission date
- [ ] TAT Progress Bar component
  - Visual progress bar (elapsed/total)
  - Color-coded (green: on track, yellow: approaching, red: breached)
  - Display remaining time
  - Show TAT status text
- [ ] Tab navigation:
  - Overview (default)
  - Workflow
  - Documents
  - Activity
- [ ] Spectators list sidebar
- [ ] Quick Actions sidebar (for approvers):
  - Add Work Note
  - Add Approver
  - Add Spectator
  - Approve Request
  - Reject Request

**Dependencies:** TASK-FE-301  
**Deliverable:** Request detail overview

---

#### **TASK-FE-304: Request Detail - Workflow Tab**
**Priority:** Critical | **Estimated Time:** 6 hours
- [ ] Create Workflow Tab component
- [ ] Fetch approval hierarchy (GET /api/v1/workflows/:id/approvals)
- [ ] Display approval levels in vertical timeline:
  - Level number and name
  - Approver name and designation
  - TAT allocation (hours/days)
  - Status indicator (Pending, In Progress, Approved, Rejected, Completed)
  - Action date/timestamp
  - Approver comments
- [ ] Highlight current active level
- [ ] Show TAT tracking for each level:
  - Elapsed time
  - Remaining time
  - TAT status (on track, approaching, breached)
  - Color-coded progress bars
- [ ] Display completion checkmarks for approved levels
- [ ] Show rejection reason if rejected

**Dependencies:** TASK-FE-303  
**Deliverable:** Workflow timeline view

---

#### **TASK-FE-305: Request Detail - Documents Tab**
**Priority:** High | **Estimated Time:** 5 hours
- [ ] Create Documents Tab component
- [ ] Fetch documents (GET /api/v1/workflows/:id/documents)
- [ ] Display documents in list/grid view:
  - File name
  - File type icon
  - File size
  - Uploader name
  - Upload timestamp
  - Preview button (PDF/images only)
  - Download button
- [ ] Implement PDF preview modal (inline viewer)
- [ ] Implement image preview modal (lightbox)
- [ ] Download document (GET /api/v1/documents/:id/download)
- [ ] Display Google Docs/Sheets links separately
- [ ] Show empty state if no documents

**Dependencies:** TASK-FE-303  
**Deliverable:** Documents tab with preview

---

#### **TASK-FE-306: Request Detail - Activity Tab**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Create Activity Tab component
- [ ] Fetch activities (GET /api/v1/workflows/:id/activities)
- [ ] Display activity timeline (reverse chronological):
  - Event icon (color-coded by type)
  - Event description
  - User name (if user action)
  - Timestamp (relative time: "2 hours ago")
  - Metadata (if applicable)
- [ ] Activity types:
  - Request created
  - Request submitted
  - Approver added
  - Spectator added
  - Document uploaded
  - Document deleted
  - Work note added
  - Approval/rejection
  - TAT warning
  - TAT breach
  - Status change
- [ ] Filter by activity type (optional)
- [ ] Auto-refresh on page load

**Dependencies:** TASK-FE-303  
**Deliverable:** Activity timeline view

---

#### **TASK-FE-307: Approve/Reject Modal**
**Priority:** Critical | **Estimated Time:** 6 hours
- [ ] Create Approve Request modal component
  - Display request ID and title
  - Mandatory comments field (max 500 chars)
  - Character counter
  - "Approve Request" button
  - "Cancel" button
- [ ] Create Reject Request modal component
  - Display request ID and title
  - Mandatory rejection reason (max 500 chars)
  - Character counter
  - "Reject Request" button (red/danger)
  - "Cancel" button
- [ ] Form validation (comments required)
- [ ] Connect to APIs:
  - PATCH /api/v1/workflows/:id/approvals/:levelId/approve
  - PATCH /api/v1/workflows/:id/approvals/:levelId/reject
- [ ] Show loading state during submission
- [ ] Success notification
- [ ] Refresh request detail after action
- [ ] Handle errors (not authorized, already actioned, etc.)

**Dependencies:** TASK-FE-303  
**Deliverable:** Approval/rejection modals

---

#### **TASK-FE-308: Add Work Note / Chat Component**
**Priority:** High | **Estimated Time:** 8 hours
- [ ] Create Work Notes component (chat interface)
- [ ] Fetch work notes (GET /api/v1/workflows/:id/work-notes)
- [ ] Display messages in chronological order:
  - User avatar
  - User name and role badge
  - Message text (support line breaks)
  - Timestamp (relative time)
  - Reactions (emoji reactions)
  - Attachments (if any)
- [ ] Message composer at bottom:
  - Text input (textarea, auto-expand)
  - @mention autocomplete dropdown
  - Attach file button
  - Send button
  - Character counter (max 2000 chars)
- [ ] Implement @mention detection and autocomplete
- [ ] Send message (POST /api/v1/workflows/:id/work-notes)
- [ ] Upload attachments with messages
- [ ] Implement reactions (POST /api/v1/work-notes/:id/reactions)
- [ ] Scroll to bottom on new message
- [ ] Auto-refresh messages (polling or websocket)

**Dependencies:** TASK-FE-303  
**Deliverable:** Work notes chat interface

---

#### **TASK-FE-309: Add Approver/Spectator Modal**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Create "Add Approver" modal
  - User search/autocomplete with @mention
  - Dropdown showing matching users
  - Display user name, email, department
  - "Add" and "Cancel" buttons
  - Connect to POST /api/v1/workflows/:id/approvals
- [ ] Create "Add Spectator" modal
  - Same UI as Add Approver
  - Connect to POST /api/v1/workflows/:id/participants
- [ ] Show success notification
- [ ] Refresh request detail after adding
- [ ] Handle errors (user already added)

**Dependencies:** TASK-FE-303  
**Deliverable:** Add participant modals

---

### **SPRINT 4: Notifications & Dashboard**

#### **TASK-FE-401: Notification System**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create NotificationBell component in header
- [ ] Display unread notification count badge
- [ ] Fetch notifications (GET /api/v1/notifications)
- [ ] Create notification dropdown panel:
  - List of recent notifications (max 10)
  - Notification item with:
    - Type icon
    - Title
    - Message
    - Timestamp (relative)
    - Read/unread indicator
  - "View All" link
  - "Mark All as Read" button
- [ ] Click notification to:
  - Mark as read (PATCH /api/v1/notifications/:id/read)
  - Navigate to related request
- [ ] Create full Notifications page (optional)
- [ ] Implement polling for new notifications (every 30 sec)
- [ ] Show toast notifications for high-priority alerts
- [ ] Handle notification types:
  - Approval assignment
  - TAT warning
  - TAT breach
  - Work note mention
  - Approval/rejection
  - Request closure

**Dependencies:** TASK-FE-007  
**Deliverable:** Notification system

---

#### **TASK-FE-402: Dashboard Page**
**Priority:** Medium | **Estimated Time:** 8 hours
- [ ] Create Dashboard page (`src/pages/Dashboard/Dashboard.tsx`)
- [ ] Fetch dashboard statistics (GET /api/v1/dashboard/stats)
- [ ] Display key metrics cards:
  - Total Requests
  - Pending Approvals
  - Approved Requests
  - Rejected Requests
  - TAT Breached
  - Avg. Approval Time
- [ ] Create Recent Activities widget
  - Fetch GET /api/v1/dashboard/recent
  - Display last 10 activities
- [ ] Create Pending Actions widget
  - Fetch GET /api/v1/dashboard/pending-actions
  - Show requests requiring user's action
- [ ] Create charts (using Recharts):
  - Requests by Status (pie chart)
  - Requests by Priority (bar chart)
  - Approval Trend (line chart over time)
- [ ] Add date range filter
- [ ] Make dashboard responsive

**Dependencies:** TASK-FE-401  
**Deliverable:** Dashboard with statistics

---

#### **TASK-FE-403: Conclusion Remark UI**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Create Conclusion section in Request Detail
- [ ] Show after final approval
- [ ] Display AI-generated conclusion
- [ ] For Initiator only:
  - "Edit Conclusion" button
  - Edit modal with textarea
  - "Save" and "Cancel" buttons
  - Connect to PUT /api/v1/workflows/:id/conclusion
- [ ] For other users: Read-only view
- [ ] Display conclusion in:
  - Request detail page
  - My Requests (approved)
  - Open Requests
  - Closed Requests
- [ ] Show placeholder if no conclusion exists

**Dependencies:** TASK-FE-303  
**Deliverable:** Conclusion remark UI

---

#### **TASK-FE-404: Workflow Closure UI**
**Priority:** High | **Estimated Time:** 3 hours
- [ ] Add "Close Request" button in request detail
  - Only visible to initiator
  - Only after final approval
  - Requires conclusion remark
- [ ] Create Close Request confirmation modal
  - Display summary
  - Show final conclusion
  - "Confirm Close" button
  - "Cancel" button
- [ ] Connect to PATCH /api/v1/workflows/:id/close
- [ ] Show success notification
- [ ] Redirect to Closed Requests or stay on page
- [ ] Update request status to CLOSED
- [ ] Display closure date

**Dependencies:** TASK-FE-403  
**Deliverable:** Workflow closure functionality

---

### **SPRINT 5: Polish & User Experience**

#### **TASK-FE-501: Search & Filter Components**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Create SearchBar component (reusable)
- [ ] Create FilterPanel component
  - Status filter (checkboxes)
  - Priority filter (checkboxes)
  - Date range filter (date pickers)
  - Department filter (dropdown)
  - Initiator filter (user search)
- [ ] Implement search logic (debounce 300ms)
- [ ] Implement filter application
- [ ] Add "Clear Filters" button
- [ ] Show active filter count
- [ ] Persist filters in URL query params
- [ ] Apply to:
  - My Requests
  - Open Requests
  - Closed Requests

**Dependencies:** TASK-FE-301, TASK-FE-302  
**Deliverable:** Search and filter functionality

---

#### **TASK-FE-502: Responsive Design & Mobile**
**Priority:** High | **Estimated Time:** 8 hours
- [ ] Make all pages responsive
- [ ] Test on breakpoints:
  - Mobile (320px - 767px)
  - Tablet (768px - 1023px)
  - Desktop (1024px+)
- [ ] Adjust layouts:
  - Collapsible sidebar on mobile
  - Hamburger menu
  - Stack cards vertically on mobile
  - Adjust table to cards on mobile
  - Responsive modals
- [ ] Test touch interactions
- [ ] Optimize images and assets
- [ ] Test on real devices

**Dependencies:** All frontend tasks  
**Deliverable:** Fully responsive UI

---

#### **TASK-FE-503: Loading States & Error Handling**
**Priority:** High | **Estimated Time:** 4 hours
- [ ] Add loading skeletons for all data fetching
  - Request list skeleton
  - Request detail skeleton
  - Dashboard skeleton
- [ ] Create ErrorState component (empty state)
- [ ] Create EmptyState component (no data)
- [ ] Add error boundaries around major sections
- [ ] Implement retry logic for failed requests
- [ ] Show user-friendly error messages
- [ ] Add toast notifications for actions
- [ ] Handle network errors gracefully

**Dependencies:** All data-fetching tasks  
**Deliverable:** Better UX with loading/error states

---

#### **TASK-FE-504: Accessibility (A11y)**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Add ARIA labels to interactive elements
- [ ] Ensure keyboard navigation works
- [ ] Add focus indicators
- [ ] Test with screen readers
- [ ] Ensure proper heading hierarchy
- [ ] Add alt text to images
- [ ] Ensure color contrast meets WCAG AA
- [ ] Add skip navigation links
- [ ] Test tab order

**Dependencies:** All component tasks  
**Deliverable:** Accessible application

---

### **SPRINT 6: Testing & Deployment**

#### **TASK-FE-601: Unit Testing**
**Priority:** High | **Estimated Time:** 10 hours
- [ ] Setup Vitest testing framework
- [ ] Setup React Testing Library
- [ ] Write component tests:
  - Login component test
  - Registration component test
  - Workflow wizard tests
  - Request card test
  - Approval modal test
  - Work notes test
  - Notification test
- [ ] Write Redux slice tests
- [ ] Write utility function tests
- [ ] Achieve >70% code coverage
- [ ] Mock API calls

**Dependencies:** All component tasks  
**Deliverable:** Component test suite

---

#### **TASK-FE-602: Integration Testing**
**Priority:** High | **Estimated Time:** 6 hours
- [ ] Test complete user flows:
  - User registration → login flow
  - Create workflow → submit flow
  - Approve/reject workflow flow
  - Add work note flow
  - Upload document flow
- [ ] Test navigation between pages
- [ ] Test Redux state updates
- [ ] Test API integration with mock server
- [ ] Test error scenarios

**Dependencies:** TASK-FE-601  
**Deliverable:** Integration test suite

---

#### **TASK-FE-603: Performance Optimization**
**Priority:** Medium | **Estimated Time:** 4 hours
- [ ] Implement code splitting with React.lazy
- [ ] Optimize bundle size (tree shaking)
- [ ] Lazy load images
- [ ] Implement virtualization for long lists
- [ ] Memoize expensive components (React.memo)
- [ ] Optimize Redux selectors (reselect)
- [ ] Add service worker for offline support (optional)
- [ ] Compress assets
- [ ] Analyze bundle with Vite build analyzer

**Dependencies:** All frontend tasks  
**Deliverable:** Optimized frontend performance

---

#### **TASK-FE-604: Deployment Setup**
**Priority:** High | **Estimated Time:** 4 hours
- [ ] Create Dockerfile for frontend
- [ ] Create nginx configuration
- [ ] Setup environment variables for production
- [ ] Configure production build (npm run build)
- [ ] Setup CI/CD pipeline (GitHub Actions)
- [ ] Configure GCP Cloud Run or Storage
- [ ] Setup CDN for static assets
- [ ] Configure HTTPS
- [ ] Test production build locally

**Dependencies:** TASK-FE-603  
**Deliverable:** Deployment-ready frontend

---

## Task Dependencies

### Critical Path (Must be completed in order)

```
BACKEND CRITICAL PATH:
TASK-BE-001 → TASK-BE-002 → TASK-BE-003 → TASK-BE-004 
    ↓
TASK-BE-101 → TASK-BE-102 → TASK-BE-103
    ↓
TASK-BE-201 → TASK-BE-202 → TASK-BE-301 → TASK-BE-302
    ↓
TASK-BE-401 → TASK-BE-402

FRONTEND CRITICAL PATH:
TASK-FE-001 → TASK-FE-002 → TASK-FE-003 → TASK-FE-004
    ↓
TASK-FE-101 → TASK-FE-102
    ↓
TASK-FE-201 → TASK-FE-202 → ... → TASK-FE-207 → TASK-FE-208
    ↓
TASK-FE-301 → TASK-FE-303 → TASK-FE-307
```

### Parallel Tasks (Can be done simultaneously)

**Sprint 0:**
- TASK-BE-001 and TASK-FE-001 (both teams can setup repos)
- TASK-BE-002 (DB) and TASK-FE-002 (UI framework)

**Sprint 1:**
- TASK-BE-103 (User APIs) and TASK-FE-103 (Password reset)

**Sprint 3:**
- TASK-FE-304, TASK-FE-305, TASK-FE-306 (all tabs can be done in parallel)

**Sprint 5:**
- TASK-FE-501, TASK-FE-502, TASK-FE-503, TASK-FE-504 (all polish tasks)

---

## Revised Timeline & Milestones (Week-Based with Current Status)

### Updated Week-by-Week Breakdown

| Week | Sprint | Backend Tasks | Backend Time | Frontend Tasks | Frontend Time | Status | Milestone |
|------|--------|---------------|--------------|----------------|---------------|--------|-----------|
| **Week 1** | Sprint 0 | BE-001 to BE-004 | 3 days | FE-001, FE-002, FE-006, FE-007 (UI) | 0 days (Figma) | 🔄 Both In Progress | UI extraction ongoing |
| **Week 2** | Sprint 0+1 | BE-004 (Complete)<br>BE-101 Start | 2 days | FE-003, FE-004, FE-005<br>FE-101 Start | 4 days | 🔄 Current Week | Foundation + Auth Start |
| **Week 3** | Sprint 1+2 | BE-101 to BE-103<br>BE-201 Start | 4 days | FE-101 to FE-104<br>FE-201 to FE-203 | 4 days | ⏳ Upcoming | Auth Complete + Workflow Start |
| **Week 4** | Sprint 2 | BE-201, BE-202 | 4 days | FE-204 to FE-207 | 4 days | ⏳ Upcoming | Workflow wizard functional |
| **Week 5** | Sprint 2+3 | BE-203, BE-204<br>BE-301 Start | 4 days | FE-208, FE-301, FE-302 | 4 days | ⏳ Upcoming | Workflow + Approvals Start |
| **Week 6** | Sprint 3 | BE-301, BE-302 | 4 days | FE-303 to FE-306 | 4 days | ⏳ Upcoming | Approval flow working |
| **Week 7** | Sprint 3+4 | BE-303, BE-401 | 4 days | FE-307 to FE-309, FE-401 | 4 days | ⏳ Upcoming | Approvals + Docs Start |
| **Week 8** | Sprint 4+5 | BE-402, BE-403, BE-501 | 4 days | FE-402 to FE-404, FE-501 | 4 days | ⏳ Upcoming | Docs + Dashboard |
| **Week 9** | Sprint 5+6 | BE-502, BE-503, BE-601 | 4 days | FE-502 to FE-504, FE-601 | 4 days | ⏳ Upcoming | Testing starts |
| **Week 10** | Sprint 6 | BE-602 to BE-605 | 4 days | FE-602 to FE-604 | 4 days | ⏳ Upcoming | Testing + Deployment |

**Revised Timeline:**
- **Frontend:** 7-8 weeks (due to API integration work)
- **Backend:** 8 weeks (as planned)
- **Overall:** ~10 weeks total

---

## Task Estimation Summary (Week-Based)

### Backend Tasks (Time Estimates in Days/Weeks)

| Sprint | Task ID | Task Name | Estimated Time | Status |
|--------|---------|-----------|----------------|--------|
| **Sprint 0** | BE-001 | Repository Setup | 0.5 days | 🔄 In Progress |
| | BE-002 | Database Schema | 1 day | ⏳ Pending |
| | BE-003 | Backend Configuration | 0.5 days | ⏳ Pending |
| | BE-004 | Sequelize ORM Setup | 1 day | ⏳ Pending |
| | **Sprint 0 Total** | | **3 days** | |
| **Sprint 1** | BE-101 | Authentication System | 2 days | ⏳ Pending |
| | BE-102 | User Management APIs | 1 day | ⏳ Pending |
| | BE-103 | User Profile | 1 day | ⏳ Pending |
| | **Sprint 1 Total** | | **4 days** | |
| **Sprint 2** | BE-201 | Workflow Creation APIs | 2 days | ⏳ Pending |
| | BE-202 | Approval Hierarchy | 1.5 days | ⏳ Pending |
| | BE-203 | Participant Management | 1 day | ⏳ Pending |
| | BE-204 | Workflow Listing/Filtering | 1.5 days | ⏳ Pending |
| | **Sprint 2 Total** | | **2 weeks (8 days)** | |
| **Sprint 3** | BE-301 | Approval/Rejection Actions | 2 days | ⏳ Pending |
| | BE-302 | TAT Tracking & Monitoring | 2 days | ⏳ Pending |
| | BE-303 | Notification System | 2 days | ⏳ Pending |
| | **Sprint 3 Total** | | **1.5 weeks (6 days)** | |
| **Sprint 4** | BE-401 | Document Management | 2 days | ⏳ Pending |
| | BE-402 | Work Notes & Chat | 2 days | ⏳ Pending |
| | BE-403 | Activity Log System | 1 day | ⏳ Pending |
| | **Sprint 4 Total** | | **1 week (5 days)** | |
| **Sprint 5** | BE-501 | Dashboard Statistics | 1.5 days | ⏳ Pending |
| | BE-502 | AI Conclusion Generation | 1.5 days | ⏳ Pending |
| | BE-503 | Workflow Closure | 1 day | ⏳ Pending |
| | **Sprint 5 Total** | | **4 days** | |
| **Sprint 6** | BE-601 | Unit Testing | 2 days | ⏳ Pending |
| | BE-602 | Integration Testing | 2 days | ⏳ Pending |
| | BE-603 | API Documentation | 1 day | ⏳ Pending |
| | BE-604 | Performance Optimization | 1.5 days | ⏳ Pending |
| | BE-605 | Deployment Setup | 1.5 days | ⏳ Pending |
| | **Sprint 6 Total** | | **2 weeks (8 days)** | |
| **TOTAL BACKEND** | | **25 Tasks** | **~8 weeks (42 days)** | |

---

### Frontend Tasks (Time Estimates in Days/Weeks)

| Sprint | Task ID | Task Name | Estimated Time | Status |
|--------|---------|-----------|----------------|--------|
| **Sprint 0** | FE-001 | Repository Setup | 0 days | ✅ Complete |
| | FE-002 | UI Framework | 0 days | ✅ Complete |
| | FE-003 | Redux Store Setup | 2 days | ❌ NOT STARTED |
| | FE-004 | API Service Layer | 1 day | ❌ NOT STARTED |
| | FE-005 | Route Guards | 1 day | ❌ NOT STARTED |
| | FE-006 | Components (Figma UI) | 0 days (80% done) | 🔄 In Progress |
| | FE-007 | Layout (Figma UI) | 0 days (80% done) | 🔄 In Progress |
| | **Sprint 0 Actual** | | **1 week (4 days)** | **16% Done** |
| **Sprint 1** | FE-101 | SSO Callback & Routes | 1 day | ⏳ Waiting for BE-101 |
| | FE-102 | Login/Logout Buttons | 0.5 days | ⏳ Pending |
| | FE-103 | User Profile Header | 1 day | ⏳ Pending |
| | **Sprint 1 Total** | | **2.5 days** | **SSO: No login/signup screens** |
| **Sprint 2** | FE-201 | Wizard Structure + Redux | 1 day | 🔄 UI Done, Need Redux |
| | FE-202 | Template Selection | 0.5 days | 🔄 UI Done, Need Logic |
| | FE-203 | Basic Info + Validation | 1 day | 🔄 UI Done, Need Validation |
| | FE-204 | Approval Workflow + Logic | 2 days | 🔄 UI Done, Need TAT Logic |
| | FE-205 | Participants + API | 1 day | 🔄 UI Done, Need API |
| | FE-206 | Documents Upload + API | 1 day | 🔄 UI Done, Need Upload Logic |
| | FE-207 | Review & Submit + API | 1 day | 🔄 UI Done, Need API |
| | FE-208 | Full API Integration | 2 days | ❌ NOT STARTED |
| | **Sprint 2 Revised** | | **2 weeks (9 days)** | **UI: 80%, Logic: 0%** |
| **Sprint 3** | FE-301 | My Requests + API | 1.5 days | 🔄 UI Done, Need API |
| | FE-302 | Open/Closed + API | 1 day | 🔄 UI Done, Need API |
| | FE-303 | Request Detail + API | 2 days | 🔄 UI Done, Need API |
| | FE-304 | Workflow Tab + API | 1 day | 🔄 UI Done, Need API |
| | FE-305 | Documents Tab + API | 1 day | 🔄 UI Done, Need API |
| | FE-306 | Activity Tab + API | 1 day | 🔄 UI Done, Need API |
| | FE-307 | Approve/Reject + API | 1.5 days | 🔄 UI Done, Need API |
| | FE-308 | Work Notes + Backend | 1 day | 🔄 UI + Partial Logic Done |
| | FE-309 | Add Approver/Spectator | 1 day | 🔄 UI Done, Need API |
| | **Sprint 3 Revised** | | **2 weeks (10 days)** | **UI: 80%, API: 0%** |
| **Sprint 4** | FE-401 | Notification + Polling | 1.5 days | 🔄 UI Done, Need API |
| | FE-402 | Dashboard + Charts | 2 days | 🔄 UI Done, Need API |
| | FE-403 | Conclusion + AI | 1 day | 🔄 UI Done, Need API |
| | FE-404 | Workflow Closure | 1 day | 🔄 UI Done, Need API |
| | **Sprint 4 Revised** | | **1 week (5 days)** | **UI: 80%, API: 0%** |
| **Sprint 5** | FE-501 | Search & Filter | 1 day | ⏳ Pending |
| | FE-502 | Responsive Design | 1 day | ⏳ Pending |
| | FE-503 | Loading/Error States | 0.5 days | ⏳ Pending |
| | FE-504 | Accessibility (A11y) | 0.5 days | ⏳ Pending |
| | **Sprint 5 Total** | | **3 days** | |
| **Sprint 6** | FE-601 | Unit Testing | 2 days | ⏳ Pending |
| | FE-602 | Integration Testing | 1 day | ⏳ Pending |
| | FE-603 | Performance Optimization | 1 day | ⏳ Pending |
| | FE-604 | Deployment Setup | 1 day | ⏳ Pending |
| | **Sprint 6 Total** | | **1 week (5 days)** | |
| **TOTAL FRONTEND** | | **40 Tasks** | **~7 weeks (35 days)** | **16% Complete (UI Only)** |

---

### ⚠️ REVISED FRONTEND EFFORT BREAKDOWN

**Figma UI Extraction vs Actual Development:**

| Work Category | Figma Extracted | Still Required | Total Time |
|--------------|-----------------|----------------|------------|
| **Visual UI Components** | 80% Done | 20% remaining | 1-2 days |
| **Redux Store Setup** | 0% | 100% needed | 2-3 days |
| **API Service Layer** | 0% | 100% needed | 1 day |
| **Route Guards & Auth** | 0% | 100% needed | 1 day |
| **Form Validations** | 0% | 100% needed | 3-4 days |
| **API Integration (All Pages)** | 0% | 100% needed | 10-12 days |
| **State Management Logic** | 0% | 100% needed | 5-6 days |
| **Error Handling** | 0% | 100% needed | 2-3 days |
| **Loading States** | 0% | 100% needed | 2-3 days |
| **Testing** | 0% | 100% needed | 5 days |
| **TOTAL** | **16%** | **84%** | **~35 days** |

**Key Insight:** 
- Figma gave us the "look and feel" (16% of work)
- We still need to build the "brain and connections" (84% of work)

---

## Task Summary

### Backend Tasks Summary
- **Sprint 0:** 4 tasks (Setup & Infrastructure)
- **Sprint 1:** 3 tasks (Authentication)
- **Sprint 2:** 4 tasks (Workflow Creation)
- **Sprint 3:** 3 tasks (Approvals & Notifications)
- **Sprint 4:** 3 tasks (Documents & Work Notes)
- **Sprint 5:** 3 tasks (Dashboard & AI)
- **Sprint 6:** 5 tasks (Testing & Deployment)

**Total Backend Tasks:** 25 tasks

### Frontend Tasks Summary
- **Sprint 0:** 7 tasks (Setup & Components)
- **Sprint 1:** 4 tasks (Authentication)
- **Sprint 2:** 8 tasks (Workflow Wizard)
- **Sprint 3:** 9 tasks (Request Management)
- **Sprint 4:** 4 tasks (Notifications & Dashboard)
- **Sprint 5:** 4 tasks (Polish & UX)
- **Sprint 6:** 4 tasks (Testing & Deployment)

**Total Frontend Tasks:** 40 tasks

---

## Notes for Development Team

### Backend Team Notes
1. **Standard Login First:** Implement email/password authentication before SSO integration
2. **Database First:** Complete database schema before starting API development
3. **Testing:** Write tests alongside development, not at the end
4. **Documentation:** Document all APIs in Swagger as you build them
5. **TAT Logic:** TAT calculation is critical - test thoroughly
6. **Notifications:** Build notification system early as many features depend on it

### Frontend Team Notes
1. **Component Library First:** Build reusable components before pages
2. **Redux Structure:** Plan Redux structure carefully to avoid refactoring
3. **API Service Layer:** Keep all API calls in service files, not in components
4. **Responsive from Start:** Build responsive layouts from the beginning
5. **Accessibility:** Consider keyboard navigation and screen readers
6. **Loading States:** Always show loading indicators for async operations

### Key Integration Points
1. **Authentication:** Backend must provide JWT tokens, frontend must store and send them
2. **File Upload:** Backend accepts multipart/form-data, frontend uses FormData
3. **TAT Display:** Backend sends TAT in hours, frontend converts to days/hours for display
4. **Real-time Updates:** Use polling (every 30 sec) for notifications and work notes
5. **Error Handling:** Backend returns consistent error format, frontend displays user-friendly messages

---

## Risk Management

### High Risk Areas
1. **TAT Calculation Logic:** Complex business rules for working days vs calendar days
2. **Multi-level Approvals:** Ensure workflow progression logic is bulletproof
3. **File Upload:** Large files, network issues, storage quotas
4. **Real-time Notifications:** Polling vs WebSockets decision
5. **AI Integration:** Third-party API dependency for conclusion generation

### Mitigation Strategies
1. **TAT:** Write comprehensive unit tests, create test scenarios document
2. **Approvals:** State machine diagram, thorough testing of all paths
3. **Files:** Implement chunked upload, progress indicators, retry logic
4. **Notifications:** Start with polling, plan for WebSocket upgrade
5. **AI:** Mock AI responses for development, have fallback to manual conclusion

---

## Definition of Done (DoD)

### For Backend Tasks
- [ ] Code written and follows TypeScript best practices
- [ ] API endpoint tested with Postman/Insomnia
- [ ] Unit tests written and passing (>80% coverage)
- [ ] API documented in Swagger
- [ ] Error handling implemented
- [ ] Logging added for debugging
- [ ] Code reviewed and merged to develop branch

### For Frontend Tasks
- [ ] Component/page implemented and styled
- [ ] Responsive design tested (mobile, tablet, desktop)
- [ ] Connected to backend API (if applicable)
- [ ] Loading and error states handled
- [ ] Component tests written (if reusable)
- [ ] Accessibility considerations addressed
- [ ] Code reviewed and merged to develop branch

---

## Getting Started

### For Backend Developers
1. Clone `re-workflow-backend` repository
2. Install Node.js 22 LTS and PostgreSQL 16
3. Run `npm install` to install dependencies
4. Create `.env` file from `.env.example`
5. Setup database with schema SQL file
6. Start development: `npm run dev`
7. Pick tasks from Sprint 0 and start building!

### For Frontend Developers
1. Clone `re-workflow-frontend` repository
2. Install Node.js 22 LTS
3. Run `npm install` to install dependencies
4. Create `.env` file from `.env.example`
5. Configure API base URL to backend
6. Start development: `npm run dev`
7. Pick tasks from Sprint 0 and start building!

---

## Communication & Coordination

### Daily Standup Questions
1. What did you complete yesterday?
2. What will you work on today?
3. Any blockers or dependencies?
4. Any integration points with other tasks?

### Weekly Sync
1. Review sprint progress
2. Demo completed features
3. Discuss upcoming integration points
4. Adjust timeline if needed

### Tools
- **Project Management:** Jira / Linear / Trello
- **Communication:** Slack / Microsoft Teams
- **Code Review:** GitHub Pull Requests
- **API Testing:** Postman (shared collection)
- **Documentation:** Confluence / Notion

---

---

## 📊 Visual Timeline & Current Progress

### Project Progress Overview

```
PROJECT START ─────────────────────────────────── PROJECT END
                  ↓ YOU ARE HERE (Week 2)

Week 1: ████████░░░░  80% 🔄 Frontend Sprint 0 - UI Only (No Functionality)
Week 1: ███████░░░░░  70% 🔄 Backend Sprint 0 In Progress

Week 2: ██░░░░░░░░░░  15% 🔄 Sprint 1 - Authentication (CURRENT)
Week 3: ░░░░░░░░░░░░   0% ⏳ Sprint 2 Part 1 - Workflow Creation
Week 4: ░░░░░░░░░░░░   0% ⏳ Sprint 2 Part 2 - Workflow Creation
Week 5: ░░░░░░░░░░░░   0% ⏳ Sprint 3 Part 1 - Approvals
Week 6: ░░░░░░░░░░░░   0% ⏳ Sprint 3 Part 2 - Approvals
Week 7: ░░░░░░░░░░░░   0% ⏳ Sprint 4 - Documents & Work Notes
Week 8: ░░░░░░░░░░░░   0% ⏳ Sprint 5 - Dashboard & AI
Week 9: ░░░░░░░░░░░░   0% ⏳ Sprint 6 Part 1 - Testing
Week 10: ░░░░░░░░░░░░  0% ⏳ Sprint 6 Part 2 - Deployment

OVERALL PROGRESS: ██░░░░░░░░░░░░░░░░░░  10% Complete (Mostly UI)

⚠️ WARNING: 80% UI ≠ 80% Complete
   - UI extraction is only 20% of total work
   - 80% UI done = 16% of frontend complete
   - Still need: Redux, API integration, validations, business logic
```

---

### Sprint-by-Sprint Detailed Timeline

#### 🔄 IN PROGRESS: Sprint 0 (Week 1-2) - Frontend
**Status:** 80% UI EXTRACTED (Visuals Only)  

**What's Actually Complete:**
- ✅ FE-001: Repository & Environment Setup (100%)
- ✅ FE-002: UI Framework & Styling (Material-UI configured) (100%)
- 🔄 FE-003: Redux Store & State Management (0% - NOT STARTED)
- 🔄 FE-004: API Service Layer (0% - NOT STARTED)
- 🔄 FE-005: Routing & Navigation Guards (0% - NOT STARTED)
- ✅ FE-006: Common Components Library - UI Only (80% - Dummy Data)
- ✅ FE-007: Layout Components - UI Only (80% - Dummy Data)

**Achievement:** 
- ✅ Visual UI extracted from Figma (80% complete)
- ✅ Mobile responsive design included
- ✅ All packages installed and dependencies resolved
- ❌ **But:** No Redux, no API calls, no validations, no business logic

**Remaining Sprint 0 Work (1 week):**
- Complete 20% UI extraction (1-2 days)
- Setup Redux store and all slices (2-3 days)
- Configure Axios service layer (1 day)
- Implement route guards (1 day)
- Add basic form validations (1-2 days)

**Revised Sprint 0 Completion:** End of Week 2

---

#### 🔄 IN PROGRESS: Sprint 0 (Week 1) - Backend
**Status:** 70% COMPLETE  
**Completed Tasks:**
- ✅ BE-001: Repository & Environment Setup (70% done)

**Remaining Tasks (0.5 weeks):**
- ⏳ BE-001: Complete repository setup (30% remaining)
- ⏳ BE-002: Database Setup & Schema (1 day)
- ⏳ BE-003: Backend Configuration (0.5 days)
- ⏳ BE-004: Sequelize ORM Setup (1 day)

**Target Completion:** End of Week 1

---

#### 🔄 CURRENT: Sprint 1 (Week 2) - Authentication
**Status:** ACTIVE THIS WEEK  
**Start Date:** Week 2 Day 1  
**Target Completion:** Week 2 End

**Backend Tasks (4 days):**
- ⏳ BE-101: User Authentication System (2 days)
  - JWT configuration
  - Register, login, password reset APIs
  - Authentication middleware
- ⏳ BE-102: User Management APIs (1 day)
- ⏳ BE-103: User Profile Management (1 day)

**Frontend Tasks (2 days):**
- 🔄 FE-101: Login Page (0.5 days) - IN PROGRESS
- ⏳ FE-102: Registration Page (0.5 days)
- ⏳ FE-103: Forgot/Reset Password (0.5 days)
- ⏳ FE-104: User Profile & Header (0.5 days)

**Milestone:** Fully working authentication with login, registration, and user profile.

---

#### ⏳ UPCOMING: Sprint 2 (Weeks 3-4) - Workflow Creation
**Duration:** 2 weeks  
**Frontend Advantage:** Wizard UI already complete from Figma!

**Week 3 Tasks:**
- Backend: BE-201 (Workflow APIs), BE-202 (Approval Hierarchy)
- Frontend: Connect wizard steps to backend APIs (FE-203, FE-204)

**Week 4 Tasks:**
- Backend: BE-203 (Participants), BE-204 (Filtering)
- Frontend: Complete wizard integration (FE-205 to FE-208)

**Milestone:** Complete workflow creation wizard functional end-to-end.

---

#### ⏳ UPCOMING: Sprint 3 (Weeks 5-6) - Approvals & Actions
**Duration:** 2 weeks  
**Frontend Advantage:** Request pages & modals already built!

**Week 5 Tasks:**
- Backend: BE-301 (Approval Actions), BE-302 (TAT Tracking)
- Frontend: Connect request listing pages to APIs (FE-301 to FE-303)

**Week 6 Tasks:**
- Backend: BE-303 (Notifications)
- Frontend: Connect tabs and modals (FE-304 to FE-309)

**Special Note:** FE-308 (Work Notes) is ALREADY COMPLETE with full functionality! ✅

**Milestone:** Full approval workflow operational with notifications.

---

#### ⏳ UPCOMING: Sprint 4 (Week 7) - Documents & Collaboration
**Duration:** 1 week  
**Frontend Advantage:** UI already complete, only need API integration!

**Backend Tasks (4 days):**
- BE-401: Document Management (2 days)
- BE-402: Work Notes APIs (2 days) - Frontend already has UI!
- BE-403: Activity Log System (1 day)

**Frontend Tasks (2 days):**
- Connect document upload/preview to APIs
- Connect work notes chat to backend
- Wire up activity timeline

**Milestone:** Documents and collaboration features working.

---

#### ⏳ UPCOMING: Sprint 5 (Week 8) - Dashboard & Polish
**Duration:** 1 week

**Backend Tasks:**
- BE-501: Dashboard Statistics (1.5 days)
- BE-502: AI Conclusion Generation (1.5 days)
- BE-503: Workflow Closure (1 day)

**Frontend Tasks:**
- FE-501: Search & Filter Components (1 day)
- FE-502: Responsive Design Polish (1 day)
- FE-503: Loading & Error States (0.5 days)
- FE-504: Accessibility Improvements (0.5 days)

**Milestone:** Complete feature set with analytics.

---

#### ⏳ UPCOMING: Sprint 6 (Weeks 9-10) - Testing & Deployment
**Duration:** 2 weeks

**Week 9 - Testing:**
- Unit tests (backend & frontend)
- Integration tests
- API documentation
- Bug fixes

**Week 10 - Deployment:**
- Performance optimization
- Production deployment setup
- CI/CD pipeline
- Final QA and go-live

**Milestone:** Production deployment! 🚀

---

## 🎯 Critical Path & Priorities

### THIS WEEK (Week 2) - Must Complete:
1. **Backend Priority:**
   - ✅ Complete BE-001 (finish repo setup)
   - 🔥 BE-002: Database schema MUST be done (blocks everything)
   - 🔥 BE-101: Authentication APIs (blocks frontend integration)

2. **Frontend Priority:**
   - 🔄 FE-101: Complete login page integration
   - FE-102 to FE-104: Wire up remaining auth pages

### NEXT WEEK (Week 3) - Prepare Now:
- Review workflow creation requirements
- Ensure backend workflow APIs design is ready
- Frontend wizard UI is ready (already done ✅), just need backend connection

---

## 📈 Velocity & Progress Tracking (REALISTIC)

### Completed Work:
- **Frontend UI:** 80% complete (visual components only, NO functionality)
  - Translation: 16% of total frontend work (UI is ~20% of effort)
  - Still need: Redux, API integration, validations, state management
- **Frontend Functionality:** 5% complete (work notes partial)
- **Backend:** 10% complete (repo setup in progress)
- **Overall Project:** 10% complete (mostly static UI)

### ⚠️ Reality Check - What "80% UI" Means:
**Completed:**
- Visual components (buttons, inputs, cards, modals)
- Layout and styling
- Mobile responsive design
- Dummy data display

**NOT Completed (This is 84% of remaining work):**
- Redux state management (0%)
- API integration (0%)
- Form validations (0%)
- Error handling (0%)
- Loading states (0%)
- Business logic (0%)
- Authentication (0%)
- Route guards (0%)

### Estimated Remaining:
- **Backend:** ~8 weeks (42 days remaining)
- **Frontend:** ~7-8 weeks (35 days remaining)
  - Redux setup: 3 days
  - API integration: 12 days
  - Validations: 4 days
  - State management: 6 days
  - Error/Loading states: 5 days
  - Testing: 5 days
- **Overall:** ~10 weeks to production

### Time Actually Saved:
- **Frontend UI Extraction:** Saved ~1 week (not 2-3 weeks as initially thought)
  - Figma generated HTML/CSS/basic JSX
  - Still need all functionality (API, Redux, logic)
- **Work Notes Feature:** UI done, partial functionality (emoji, doc selection)
  - Still need: Backend API integration, @mentions, notifications
  - Saved: ~2-3 days

---

## 🚨 Risks & Mitigation

### Current Risks:
1. **Backend Setup Delay:** If BE-002 (database) takes longer, it blocks everything
   - **Mitigation:** Prioritize database schema completion this week
   
2. **API Integration Complexity:** Frontend-backend integration may reveal issues
   - **Mitigation:** Early API testing, clear documentation, Postman collections

3. **TAT Calculation Logic:** Complex business rules for working days
   - **Mitigation:** Dedicated unit tests, test scenarios document

### Advantages We Have:
1. ✅ Frontend UI 80% extracted from Figma (saves ~1 week)
2. ✅ Mobile responsive design included (saves testing time)
3. ✅ Work notes UI + partial functionality (saves 2-3 days)
4. ✅ Clear requirements from documentation
5. ✅ Modern tech stack (TypeScript, React 19, Node.js 22)
6. ✅ No need to design UI (Figma already provided)

### Challenges We Face:
1. ❌ **False sense of completion:** UI looks done but needs 84% more work
2. ❌ **Integration complexity:** Each page needs API + Redux + validation
3. ❌ **Backend dependency:** Frontend blocked until APIs are ready
4. ❌ **TAT logic complexity:** Working days calculation is non-trivial
5. ⚠️ **SSO uncertainty:** May need to refactor auth later

---

## 📅 Key Dates & Milestones

| Date | Week | Milestone | Status |
|------|------|-----------|--------|
| Oct 16-20 | Week 1 | Figma UI Extraction Started | 🔄 80% Complete (Visual Only) |
| Oct 21-25 | Week 2 | Sprint 0 Complete (Foundation) | 🔄 IN PROGRESS |
| Oct 28 - Nov 1 | Week 3 | Authentication Working | ⏳ Target |
| Nov 4-8 | Week 4 | Workflow Creation Started | ⏳ Upcoming |
| Nov 11-15 | Week 5 | Workflow Creation Complete | ⏳ Upcoming |
| Nov 18-22 | Week 6 | Approvals 50% | ⏳ Upcoming |
| Nov 25-29 | Week 7 | Approvals Complete | ⏳ Upcoming |
| Dec 2-6 | Week 8 | Documents & Work Notes | ⏳ Upcoming |
| Dec 9-13 | Week 9 | Dashboard & AI | ⏳ Upcoming |
| Dec 16-20 | Week 10 | Testing Phase | ⏳ Upcoming |
| Dec 23-27 | Week 11 | **PRODUCTION LAUNCH** 🚀 | ⏳ Revised Target |

**Timeline Adjustment:** +1 week due to realistic frontend effort assessment

---

## 💡 Recommendations for Success

### For Backend Team:
1. **This Week:** Focus 100% on database schema (BE-002) - this is critical path
2. **Next Week:** Authentication APIs must be solid for frontend integration
3. **Use Swagger:** Document APIs as you build them
4. **Test Early:** Use Postman collections for quick testing
5. **Communication:** Sync with frontend daily on API contracts

### For Frontend Team:
1. **🔥 THIS WEEK (CRITICAL):** Complete Sprint 0 foundation
   - Finish last 20% UI extraction (1-2 days)
   - **Setup Redux store with ALL slices** (2-3 days) ← MUST DO
   - **Configure Axios service layer** (1 day) ← MUST DO
   - Implement route guards (1 day)
   - Without these, you CANNOT integrate with backend!
   
2. **Understand the Reality:**
   - Having UI ≠ Having functionality
   - Every page needs:
     - Redux actions/reducers connected
     - API service calls implemented
     - Form validation logic
     - Error handling
     - Loading states
     - Success/failure notifications
   - Example: Login page needs ~1 day AFTER backend API is ready
   
3. **Don't Underestimate Integration:**
   - Each form needs validation (1-2 hours)
   - Each API call needs error handling (1 hour)
   - Each list needs loading skeleton (1 hour)
   - Each action needs success/error toast (30 min)
   - Total: API integration ≈ 30-40% of total frontend work
   
4. **Prepare for Sprint 1:**
   - Review auth API contracts from backend team
   - Plan Redux auth flow (login → store token → redirect)
   - Understand JWT storage strategy
   - Plan form validation rules
   
5. **Work Smart:**
   - Create reusable hooks (useApi, useForm, useNotification)
   - Create reusable validation functions
   - Create reusable error handling
   - Don't repeat code across pages

### For Both Teams:
1. **Daily Standup:** Quick 15-min sync every morning
   - What did you complete?
   - What are you working on today?
   - Any blockers?
   - Any dependencies on other team?
   
2. **Integration Points:** Test API integration early and often
   - Backend: Provide Postman collection with example requests
   - Frontend: Test API calls as soon as endpoints are ready
   - Don't wait until sprint end to integrate!
   
3. **Code Review:** Review each other's code for consistency
   - All PRs need 1 approval before merge
   - Check for TypeScript errors
   - Check for security issues
   - Check for code duplication
   
4. **Git Workflow:** Use feature branches, PR reviews mandatory
   - Branch naming: `feature/TASK-BE-001-repo-setup`
   - Commit messages: Follow conventional commits
   - Squash commits before merge
   
5. **Realistic Expectations:**
   - ✅ You have good UI foundation (16% done)
   - ❌ You're not 60% done (common misconception)
   - 💪 You have 84% of challenging work ahead
   - 🎯 Focus on quality, not speed
   - 📅 10-11 weeks is realistic, don't rush

---

**Document Prepared By:** .NET Expert Team  
**Last Updated:** October 23, 2025  
**Status:** ✅ Updated with REALISTIC Progress Assessment  
**Total Estimated Duration:** 10-11 weeks (Target: End Dec 2025 / Early Jan 2026)  
**Current Progress:** 10% Complete (Week 2 of 11)  
**Frontend Reality:** 80% UI ≠ 80% Complete (Actually 16% complete)

---

## Quick Reference

### Backend Ports
- Development: `http://localhost:5000`
- API Docs: `http://localhost:5000/api-docs`
- Health Check: `http://localhost:5000/health`

### Frontend Ports
- Development: `http://localhost:3000`

### Databases
- PostgreSQL: `localhost:5432`
- Database Name: `re_workflow_db`

### Key Environment Variables
**Backend:**
- `NODE_ENV=development`
- `PORT=5000`
- `DB_HOST=localhost`
- `JWT_SECRET=your_secret_key`

**Frontend:**
- `REACT_APP_API_BASE_URL=http://localhost:5000/api/v1`

---

## 🎯 FRONTEND DEVELOPER GUIDE: What to Build Each Week

### ⚠️ REALITY CHECK BEFORE YOU START:

**"We have 80% UI from Figma" does NOT mean "We're 80% done"**

**What it ACTUALLY means:**
- You have pretty buttons, inputs, and layouts (20% of total work)
- You still need to build the "brain" (80% of total work):
  - Redux state management
  - API integration
  - Form validations
  - Error handling
  - Loading states
  - Business logic
  - Testing

**Current True Completion:** 16% (not 80%)

---

### 📅 Week-by-Week Frontend Build Plan

#### **WEEK 2 (THIS WEEK - CRITICAL FOUNDATION)**

**🔥 Priority 1: Complete UI Extraction (1-2 days)**
- Finish remaining 20% components
- Fix any styling bugs
- Ensure mobile responsive works on all breakpoints
- **Deliverable:** 100% UI extraction

**🔥 Priority 2: Redux Store Setup (2-3 days) ← CANNOT SKIP**
Create these files:
1. `src/redux/store.ts` - Configure Redux store
2. `src/redux/hooks.ts` - Typed useDispatch and useSelector
3. `src/redux/slices/authSlice.ts` - User auth state
4. `src/redux/slices/workflowSlice.ts` - Workflows state
5. `src/redux/slices/approvalSlice.ts` - Approvals state
6. `src/redux/slices/notificationSlice.ts` - Notifications state
7. `src/redux/slices/documentSlice.ts` - Documents state
8. `src/redux/slices/workNoteSlice.ts` - Work notes state
9. `src/redux/slices/participantSlice.ts` - Participants state
10. `src/redux/slices/uiSlice.ts` - UI state (modals, loading)

**🔥 Priority 3: Axios Service Layer (1 day) ← CANNOT SKIP**
Create these files:
1. `src/services/api.ts` - Axios instance with interceptors
2. `src/services/auth.service.ts` - Auth API calls
3. `src/services/workflow.service.ts` - Workflow API calls
4. `src/services/approval.service.ts` - Approval API calls
5. `src/services/document.service.ts` - Document API calls
6. `src/services/notification.service.ts` - Notification API calls
7. `src/services/workNote.service.ts` - Work note API calls
8. `src/services/participant.service.ts` - Participant API calls
9. `src/services/dashboard.service.ts` - Dashboard API calls
10. `src/services/user.service.ts` - User API calls

**Priority 4: Route Guards (1 day)**
- Create `PrivateRoute` component
- Create `PublicRoute` component
- Protect all authenticated routes

**End of Week 2:** Foundation complete, ready for integration

---

#### **WEEK 3: Authentication Pages Integration**

**Prerequisite:** Backend auth APIs must be ready (BE-101, BE-102)

**Login Page (1 day):**
- Connect form to Redux loginUser action
- Add email validation (regex)
- Add password validation (required)
- Handle form submit
- Call auth API via Redux thunk
- Store JWT token in localStorage + Redux
- Handle errors (401, network errors)
- Show loading state on button
- Redirect to dashboard on success
- Add "Remember Me" functionality
- **Deliverable:** Working login

**Registration Page (0.5 days):**
- Connect form to Redux registerUser action
- Validate all fields (name, email, password, employee ID)
- Password strength indicator
- Confirm password match
- Call register API
- Show success message
- Redirect to login
- **Deliverable:** Working registration

**Password Reset (0.5 days):**
- Forgot password page with email input
- Reset password page with new password
- Connect to backend APIs
- **Deliverable:** Working password reset

**User Profile (0.5 days):**
- Fetch current user from API
- Display in header dropdown
- Edit profile modal
- Update profile API integration
- **Deliverable:** Working profile management

**End of Week 3:** Users can login, register, reset password, edit profile

---

#### **WEEKS 4-5: Workflow Creation Wizard (2 weeks)**

**Week 4: Steps 1-3 (Core Workflow)**

**Template Selection (0.5 days):**
- Connect selection to Redux
- Save choice in workflow state
- Enable/disable based on selection

**Basic Information (1 day):**
- Connect form to Redux
- Validate title (required, max 500 chars)
- Validate description (required, max 5000 chars)
- Integrate rich text editor
- Validate priority selection
- Save to Redux workflow state
- **Complex:** Rich text editor integration

**Approval Workflow Builder (2-3 days) ← MOST COMPLEX:**
- Dynamic level creation (add/remove)
- User search for @mention
  - Call user search API as user types
  - Display dropdown with results
  - Handle selection
- Validate each level:
  - Level name (optional)
  - Approver (required)
  - TAT value (required, > 0)
- **Real-time TAT calculation:**
  - Sum all level TATs
  - Calculate total hours/days
  - Display prominently
- Approval flow summary (live preview)
- Save all levels to Redux
- Validate max 10 levels
- Validate unique approvers
- **Challenge:** Complex form with dynamic fields + real-time calculation

**Week 5: Steps 4-6 (Finalization)**

**Participants & Access (1 day):**
- User search for spectators
- Add multiple spectators
- Display as chips
- Save to Redux
- **Deliverable:** Spectator management

**Documents Upload (1 day):**
- Implement drag-drop (react-dropzone)
- Validate file type
- Validate file size (10MB)
- Show upload progress
- Multiple file upload
- Google Docs/Sheets links
- Save metadata to Redux
- **Challenge:** File upload with progress tracking

**Review & Submit (1 day):**
- Display complete summary from Redux
- Edit buttons (navigate back)
- **Save as Draft:**
  - Call POST /api/v1/workflows (is_draft=true)
  - Save workflow ID
  - Navigate to My Requests
- **Submit Request:**
  - Upload all documents (multiple API calls)
  - Create workflow (POST /api/v1/workflows)
  - Add approval levels (multiple POST calls)
  - Add spectators (multiple POST calls)
  - Submit workflow (PATCH /api/v1/workflows/:id/submit)
  - Handle errors at each step
  - Show progress indicator
  - Navigate to request detail on success
- **Challenge:** Multi-step API orchestration

**API Integration & Testing (2 days):**
- Connect all wizard steps to backend
- Handle errors
- Test complete flow end-to-end
- Fix bugs
- **Deliverable:** Working workflow creation

**End of Week 5:** Users can create workflows with approvals, spectators, documents

---

#### **WEEKS 6-7: Request Management & Approval Actions (2 weeks)**

**Week 6: Request Listing Pages (1 week)**

**My Requests Page (1.5 days):**
- Fetch workflows via Redux (GET /api/v1/workflows/my-requests)
- Display loading skeleton while fetching
- Handle empty state (no requests)
- Handle error state
- Implement tabs (Total, In Progress, Approved, Rejected, Draft)
- Filter requests by tab
- Implement search (debounced)
- Implement filters (status, priority, date range)
- Implement sorting
- Implement pagination
- Connect click to navigate to detail
- **Deliverable:** Functional request listing

**Open & Closed Requests (1 day):**
- Similar to My Requests
- Different API endpoints
- Show conclusion remarks for closed requests
- **Deliverable:** All listing pages working

**Request Detail Overview (1.5 days):**
- Fetch workflow details (GET /api/v1/workflows/:id)
- Display all information
- Fetch and display TAT status
- Calculate TAT progress percentage
- Color-code progress bar
- Display spectators
- Show quick actions (based on user role)
- **Deliverable:** Request detail page

**Week 7: Tabs & Actions (1 week)**

**Workflow Tab (1 day):**
- Fetch approval hierarchy
- Display approval timeline
- Show status for each level
- Display TAT for each level
- Show approver comments
- **Deliverable:** Approval timeline view

**Documents Tab (1 day):**
- Fetch documents
- Display document list
- Implement PDF preview modal
- Implement image preview modal
- Implement download
- **Deliverable:** Document viewing

**Activity Tab (1 day):**
- Fetch activities
- Display timeline
- Group by date
- Filter by type
- **Deliverable:** Activity timeline

**Approve/Reject Modals (1.5 days):**
- Create modal components
- Validate mandatory comments
- Call approve/reject APIs
- Handle success/errors
- Refresh page after action
- **Deliverable:** Approval actions working

**Add Approver/Spectator (0.5 days):**
- User search
- Call add APIs
- Refresh page
- **Deliverable:** Add participants working

**End of Week 7:** Complete request management + approval actions

---

#### **WEEK 8: Documents, Work Notes & Dashboard**

**Document Upload Integration (1 day):**
- Connect upload to API
- Show upload progress (0-100%)
- Handle upload errors
- **Deliverable:** Document upload working

**Work Notes API Integration (1 day):**
- Connect chat to backend API
- Fetch messages
- Send messages
- Add reactions
- Parse @mentions
- **Deliverable:** Work notes fully functional

**Dashboard (2 days):**
- Fetch statistics API
- Display metric cards
- Integrate charts with real data
- Fetch recent activities
- Fetch pending actions
- **Deliverable:** Working dashboard

**End of Week 8:** Documents, collaboration, dashboard complete

---

#### **WEEK 9: Notifications, Filters & Polish**

**Notification System (1 day):**
- Fetch notifications from API
- Display in bell dropdown
- Mark as read
- Implement polling (every 30 sec)
- Toast for high-priority
- **Deliverable:** Notifications working

**Search & Filters (1 day):**
- Implement search across pages
- Implement filter panels
- URL query params
- **Deliverable:** Search/filter working

**Conclusion & Closure (1 day):**
- Connect to AI conclusion API
- Edit functionality
- Close workflow API
- **Deliverable:** Workflow closure working

**Responsive & Polish (1 day):**
- Fix mobile issues
- Add loading skeletons everywhere
- Add error boundaries
- Accessibility improvements

**End of Week 9:** All features functional

---

#### **WEEK 10: Testing & Deployment**

**Testing (3 days):**
- Write unit tests for components
- Write Redux slice tests
- Integration tests
- Fix bugs found during testing

**Deployment (2 days):**
- Production build
- Docker setup
- CI/CD pipeline
- Deploy to GCP

**End of Week 10:** Production ready! 🚀

---

## 📊 FINAL REALITY CHECK FOR STAKEHOLDERS

### Common Misconceptions vs Reality:

| Misconception | Reality | Impact |
|---------------|---------|--------|
| "80% UI = 80% done" | "80% UI = 16% done" | +6 weeks timeline |
| "Just connect APIs" | "Build Redux, API layer, validations, logic" | +4 weeks effort |
| "Work notes complete" | "Work notes UI done, need backend integration" | +1 week |
| "6 weeks total" | "10-11 weeks realistic" | +4-5 weeks |
| "Launch Dec 15" | "Launch Dec 27 / Early Jan" | +2 weeks |

### Honest Timeline Assessment:

**Optimistic (if everything goes perfect):** 9 weeks  
**Realistic (with normal challenges):** 10-11 weeks  
**Pessimistic (if issues arise):** 12-13 weeks  

**Recommended Target:** Early January 2026 (11-12 weeks)

---

## 💡 FINAL RECOMMENDATIONS

### For Project Manager:
1. **Set realistic expectations** with stakeholders
2. **Communicate:** "UI looks done but needs integration work"
3. **Timeline:** Plan for 10-11 weeks, not 6-8 weeks
4. **Buffer:** Add 1-2 weeks buffer for unforeseen issues
5. **Milestones:** Weekly demos to show actual progress

### For Frontend Team Lead:
1. **This week:** Complete Sprint 0 foundation (Redux + API layer)
2. **Don't rush:** Build it right, don't cut corners
3. **Reusability:** Create hooks and utilities to avoid duplication
4. **Testing:** Test as you build, not at the end
5. **Communication:** Daily sync with backend on API contracts

### For Backend Team Lead:
1. **This week:** Database schema is CRITICAL - blocks everything
2. **Documentation:** Document APIs in Swagger as you build
3. **Postman:** Share collection with frontend team
4. **Testing:** Use Postman to test before frontend integration
5. **Communication:** Notify frontend when APIs are ready

### Success Criteria:

**Week 2:** ✅ Foundation complete (Redux, API layer, DB)  
**Week 3:** ✅ Authentication working end-to-end  
**Week 5:** ✅ Can create and submit workflows  
**Week 7:** ✅ Can approve/reject workflows  
**Week 9:** ✅ All features functional  
**Week 11:** ✅ Production deployment  

---

**🎉 YOU'VE GOT THIS! Focus on building quality software, one sprint at a time. Good luck! 🚀**

---



## 🎯 EXECUTIVE SUMMARY: Where We Stand (REALISTIC ASSESSMENT)

### What's Actually Complete ✅
1. **Frontend UI:** 80% extracted via Figma (visual components ONLY)
   - ⚠️ This is just HTML/CSS/JSX with dummy data
   - No functionality, no API calls, no state management
2. **Frontend Packages:** All dependencies installed and resolved
3. **Work Notes Feature:** UI complete + basic functionality (emoji, doc selection)
   - Still needs: Backend API integration, @mentions, real data
4. **Backend Repository:** 70% setup complete
5. **Mobile Responsive:** All UI is responsive (320px - 1920px)

### What's NOT Complete ❌ (Common Misconception)
1. **Redux Store:** 0% - Not even created yet
2. **API Service Layer:** 0% - Not configured
3. **Form Validations:** 0% - All forms accept any input
4. **API Integration:** 0% - Nothing connects to backend
5. **Business Logic:** 0% - No TAT calculations, no workflows
6. **Authentication:** 0% - Login UI exists but doesn't work
7. **Route Guards:** 0% - All routes are publicly accessible
8. **Error Handling:** 0% - No error messages
9. **Loading States:** 0% - No spinners or skeletons

### What's In Progress 🔄
1. **Backend Setup:** Completing repository (30% remaining)
2. **Frontend UI Extraction:** Completing last 20% of Figma extraction
3. **Work Notes:** Adding remaining functionality

### What's Critical This Week 🔥
1. **Complete Frontend Sprint 0 (This Week):**
   - ✅ Finish UI extraction (20% remaining) - 1-2 days
   - 🔥 Setup Redux store with all slices - 2-3 days (CRITICAL)
   - 🔥 Configure Axios service layer - 1 day (CRITICAL)
   - 🔥 Implement route guards - 1 day
   - Total: 4-5 days of work

2. **Complete Backend Sprint 0 (This Week):**
   - 🔥 BE-002: Database schema MUST be done - 1 day (BLOCKS EVERYTHING)
   - BE-003: Backend configuration - 0.5 days
   - BE-004: Sequelize ORM setup - 1 day

3. **Start Sprint 1 (Next Week):**
   - Backend: Auth APIs (BE-101)
   - Frontend: Connect login/register pages

### Time to Production 🚀
- **Estimated:** 9 more weeks (10 weeks total)
- **Target Launch:** End of December 2025 / Early January 2026
- **Current Progress:** 10% complete (realistic)
- **Confidence Level:** Medium (more work than initially thought)

### Reality Check 📊
**Initial Assumption:** "Figma UI = 60% complete"  
**Reality:** "Figma UI = 16% complete"  

**Why the Gap?**
- Figma only gives you visual components (20% of work)
- Still need to build:
  - Redux state management (20% of work)
  - API integration (30% of work)
  - Validations & logic (20% of work)
  - Testing & polish (10% of work)

**Calculation:**
- 80% of 20% = 16% total frontend work complete
- 84% of frontend work still remaining

### Key Success Factors 💪
1. ✅ Frontend UI base ready (saves ~1 week)
2. ✅ Mobile responsive from start (saves testing time)
3. ✅ Clear requirements and documentation
4. ✅ Modern, proven tech stack
5. ❌ Still need significant integration work
6. ⏳ Backend and frontend must sync closely

### Immediate Next Steps (This Week & Next)

#### **WEEK 2 (Current Week) - Complete Sprint 0**

**Backend Priority (2.5 days):**
1. 🔥 BE-002: Setup PostgreSQL database (1 day) ← CRITICAL - BLOCKS EVERYTHING
   - Install PostgreSQL 16
   - Create database
   - Run schema SQL file (from documentation)
   - Create all 15+ tables with indexes
   - Setup triggers and views
   - Verify database connection
   
2. BE-003: Backend configuration (0.5 days)
   - Complete Express.js setup
   - Configure all middleware
   - Setup Winston logger
   - Create error handlers
   - Test health check endpoint
   
3. BE-004: Sequelize ORM setup (1 day)
   - Configure Sequelize connection
   - Create all TypeScript models
   - Define model associations
   - Test database queries

**Frontend Priority (4 days):**
1. 🔥 Complete UI extraction - 20% remaining (1-2 days)
   - Finish any incomplete pages
   - Fix any styling issues
   - Ensure all dummy data displays correctly
   
2. 🔥 FE-003: Setup Redux Store (2-3 days) ← CRITICAL
   - Create `src/redux/store.ts`
   - Create typed hooks (`src/redux/hooks.ts`)
   - Create all Redux slices:
     - authSlice (user, token, isAuthenticated)
     - workflowSlice (workflows, currentWorkflow, drafts)
     - approvalSlice (approvals, currentLevel)
     - notificationSlice (notifications, unreadCount)
     - documentSlice (documents, uploadProgress)
     - workNoteSlice (notes, mentions)
     - participantSlice (participants, spectators)
     - uiSlice (loading, errors, modals)
   - Test Redux DevTools
   - Setup Redux persist for auth
   
3. 🔥 FE-004: Configure Axios Service Layer (1 day) ← CRITICAL
   - Create `src/services/api.ts` (Axios instance)
   - Configure base URL from .env
   - Setup request interceptor (add JWT token to headers)
   - Setup response interceptor (handle errors)
   - Handle token refresh logic (on 401)
   - Create all service files:
     - `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`
   
4. FE-005: Implement Route Guards (1 day)
   - Create `PrivateRoute` component
   - Create `PublicRoute` component
   - Protect all authenticated routes
   - Redirect to login if not authenticated
   - Redirect to dashboard if already logged in (for login page)

**End of Week 2 Target:**
- ✅ Backend: Database ready, ORM working, server running
- ✅ Frontend: UI 100%, Redux configured, API layer ready, routes protected
- ✅ Both ready for Sprint 1 (Authentication integration)

---

#### **WEEK 3 - Sprint 1: Authentication Integration**

**Backend (4 days):**
1. BE-101: Build authentication APIs (2 days)
   - Register, login, logout, token refresh
   - Password hashing with bcrypt
   - JWT token generation
   - Auth middleware
   
2. BE-102: User management APIs (1 day)
3. BE-103: User profile APIs (1 day)

**Frontend (2.5 days - waiting for backend):**
1. FE-101: Connect login page to backend (1 day)
   - Call POST /api/v1/auth/login
   - Store JWT in Redux + localStorage
   - Handle errors
   - Redirect on success
   
2. FE-102: Connect registration page (0.5 days)
3. FE-103: Connect password reset (0.5 days)
4. FE-104: Connect user profile (0.5 days)

**End of Week 3 Target:**
- ✅ Users can register, login, logout
- ✅ JWT authentication working
- ✅ Protected routes functional
- ✅ User profile management working

---

## 📞 Support & Communication

### Team Collaboration
- **Daily Standup:** 10:00 AM (15 minutes)
- **Weekly Demo:** Friday 3:00 PM
- **Integration Sync:** As needed (Slack/Teams)

### Questions or Blockers?
- **Backend Lead:** Escalate database or API design questions immediately
- **Frontend Lead:** Escalate UI/UX or integration questions
- **Both Teams:** Communicate early and often!

### Success Metrics
- **Sprint Velocity:** Track completed vs planned tasks weekly
- **Code Quality:** Maintain >80% test coverage
- **Integration Success:** All APIs tested before frontend integration
- **Deployment Readiness:** All features tested end-to-end

---

**🎉 CONGRATULATIONS! You're off to a great start with 60% of frontend UI already complete! Let's build something amazing! 🚀**

---

Good luck with the development! 💪

