# Homelegance Chatbot Full-Stack Upgrade

## Phase 1: Backend Infrastructure
- [x] Upgrade project to web-db-user (backend + database)
- [x] Create database schema (conversations, messages, agents, workflow_nodes)
- [x] Build API routes for chat, agents, and workflows
- [x] Set up AI integration for chatbot responses

## Phase 2: Agent Dashboard
- [x] Build agent dashboard page with conversation list
- [x] Real-time chat view for agents to monitor conversations
- [x] Agent reply functionality
- [x] Conversation status management (active, escalated, resolved)
- [x] Agent metrics and stats

## Phase 3: Workflow Designer
- [x] Build visual drag-and-drop workflow canvas
- [x] Node types: greeting, intent detection, response, condition, escalation
- [x] Connection drawing between nodes
- [x] Save/load workflow configurations
- [ ] Workflow preview/test mode

## Phase 4: Integration & Testing
- [x] Connect chatbot widget to real backend API
- [x] Connect agent dashboard to live data
- [x] Test full conversation flow (user → bot → escalation → agent)
- [x] Verify workflow designer saves and loads correctly
- [x] Write unit tests for backend API (14 tests passing)

## Phase 5: Role-Based Access Control & User Management
- [x] Add login restriction to Agent Dashboard (redirect unauthenticated users)
- [x] Add login restriction to Workflow Designer (redirect unauthenticated users)
- [x] Admin-only access to Workflow Designer (agents cannot see it)
- [x] Build user management module in Agent Dashboard (admin can set user roles)
- [x] Add admin-only backend procedures for user management
- [x] Update navigation to show/hide links based on user role
- [x] Optimize dashboard structure with sidebar navigation (DashboardLayout)
- [x] Write unit tests for RBAC (31 new tests, 45 total passing)
- [x] Add 'agent' role to user schema (admin, agent, user)
- [x] agentProcedure middleware (requires agent or admin role)
- [x] adminProcedure middleware (requires admin role only)
- [x] Self-role-change prevention
- [x] Role badges and access denied screens

## Phase 6: Enhanced User Management
- [x] Invitation system — send email invitations with unique invite links
- [x] Invitation status tracking (pending, accepted, expired, revoked)
- [x] Invitation table in database with token, email, role, status, expiry
- [x] Invite acceptance flow — landing page to accept invite and create account
- [x] Resend invitation functionality
- [x] Revoke/cancel pending invitations
- [x] Delete user with confirmation dialog and cascade handling
- [x] User activity log (last login, invite date, role changes)
- [x] Bulk actions (bulk delete, bulk role change)
- [x] User search and advanced filtering (by role, status, date joined)
- [x] Export users list to CSV
- [x] User detail view / profile card
- [x] Invitation history tab showing all sent invitations
- [x] Backend API for all invitation CRUD operations
- [x] Backend API for user deletion
- [x] Write unit tests for invitation and deletion features (31 new tests, 76 total passing)

## Phase 7: Login Page & Password Authentication
- [x] Add passwordHash field to users table
- [x] Add password_reset_tokens table to schema
- [x] Build backend: register with email/password
- [x] Build backend: login with email/password (session cookie)
- [x] Build backend: forgot password (generate reset token)
- [x] Build backend: reset password (validate token, update password)
- [x] Create custom Login page with email/password form
- [x] Add "Forgot your password?" link on login page
- [x] Create Forgot Password page (enter email, receive reset link)
- [x] Create Reset Password page (enter new password with token)
- [x] Create Register page for new users
- [x] Update routing: protect dashboard, workflow, user-management behind login
- [x] Keep home page publicly accessible
- [x] Update DashboardLayout to use custom auth instead of OAuth-only
- [x] Write unit tests for login, register, forgot password, reset password (18 new tests, 94 total passing)

## Phase 8: Conversation History Redesign & Bot Naming
- [x] Add pagination to conversations API (limit, offset, total count)
- [x] Add search by visitor name/email/message content
- [x] Add filter by agent (who replied)
- [x] Add filter by status (active, escalated, resolved, closed)
- [x] Add filter by date range
- [x] Add sort options (newest, oldest, most messages, last activity)
- [x] Track assigned agent on conversations
- [x] Redesign conversation list with compact card layout for large volumes
- [x] Add conversation search bar with debounced input
- [x] Add filter sidebar/toolbar with dropdowns
- [x] Add pagination controls (page numbers, prev/next)
- [x] Add conversation count and summary stats
- [x] Add bulk actions for conversations (close, resolve, delete)
- [x] Give AI bot a professional friendly name — **Ellie**
- [x] Update bot name across chatbot widget, dashboard, and system prompt
- [x] Write tests for new pagination and filtering API (20 new tests, 114 total passing)

## Phase 9: Customer ID & Sales Rep in Conversation Table
- [x] Add customerId field to conversations schema
- [x] Add salesRep field to conversations schema
- [x] Run database migration
- [x] Update backend API to include Customer ID and Sales Rep in search and sort
- [x] Update Agent Dashboard table with Customer ID and Sales Rep columns
- [x] Display Customer ID and Sales Rep in chat panel header
- [x] Add sort by Customer ID and Sales Rep
- [x] Include Customer ID and Sales Rep in search
- [x] Write tests for new sort options (116 total passing)

## Phase 10: Agent Name Column & Customer Message Notifications
- [x] Display assigned agent name in conversation table rows
- [x] Add agent name column header with sorting
- [x] Show agent name in chat panel header
- [x] Implement browser push notifications when customer sends a message
- [x] Add notification toggle button in dashboard header
- [x] Add notification permission request UI
- [x] Show in-app toast notification for new messages with "View" action button
- [x] Write tests for agent name and sort features (119 total passing)

## Phase 11: Workflow Designer Enhancements — Data, Guardrails & AI Suggestions
- [x] Update greeting node to auto-detect customer ID from logged-in user session
- [x] Add "Customer Data" node type — connects chatbot to customer account data (CRM lookup)
- [x] Add "Sales Order" node type — connects chatbot to sales order data (order history, status)
- [x] Add "Content Guardrail" node type — blocks sensitive questions (revenue, margin, internal data)
- [x] Add configurable blocked topics list in guardrail node properties
- [x] Add "AI Suggested" node type — auto-generated from frequently asked questions
- [x] Build AI recommendation panel that analyzes FAQ patterns and suggests new nodes
- [x] Implement approve/wait/decline moderation UI for AI-suggested nodes
- [x] Approved nodes get added to the workflow canvas
- [x] Declined nodes are removed from suggestions
- [x] Waiting nodes stay in the queue for later review
- [x] Update database schema to support new node types (workflow_suggestions table + expanded node type enum)
- [x] Update backend to persist new node types and AI suggestion states (4 new endpoints)
- [x] Write tests for new workflow features (133 total passing across 6 files)

## Phase 12: Tidio-Inspired Enhancements — Flows, Playground, Analytics, Data Import

### 12a. Workflow Designer — Flow Categories & Sub-categories
- [x] Reorganize Workflow Designer into tabbed categories: Support Flows, Leads Flows, Sales Flows, Others
- [x] Support Flows sub-categories: Orders, Shipping, Returning, Cancelling, Deflect, Self Service
- [x] Leads Flows sub-categories: Lead Capture, Qualify, Nurture
- [x] Sales Flows sub-categories: Product Search, Recommendations, Dealer Locator
- [x] Flow template gallery with preview cards per category (7 pre-built templates)
- [x] Category sidebar with counts and sub-category drill-down

### 12b. Greeting Redesign — Button Options
- [x] Redesign chatbot greeting with avatar, name, online status indicator (Tidio-inspired)
- [x] Show "What can we help you with today?" greeting message
- [x] Add quick-reply buttons: Orders, Shipping, Returning, Cancelling
- [x] "Hit the buttons to respond" placeholder text
- [x] Each button sends the corresponding message to start the flow

### 12c. Playground — Chatbot Testing
- [x] Build Playground page accessible from sidebar navigation
- [x] Interactive chatbot widget preview (simulates customer view)
- [x] Test specific flows by selecting from flow list
- [x] Show flow execution path in real-time during test
- [x] Reset/restart test session button

### 12d. Analytics — Resolution Rate Tracking
- [x] Build Analytics page with dashboard charts
- [x] Track and display resolution rate (bot-resolved vs escalated)
- [x] Interactions over time chart (bar chart)
- [x] Average response time metrics
- [x] Category breakdown (Orders/Shipping/Returning/Cancelling)
- [x] Database schema for analytics_events table

### 12e. AI Agent Data Import Module (Lyro-inspired)
- [x] Build Data Sources management page with tabbed UI (Sources / Connections / Templates)
- [x] URL import — crawl website pages for FAQ/product data
- [x] File upload — CSV/JSON import for bulk data
- [x] Manual Q&A pairs entry
- [x] API Connections — configure external API endpoints (sales orders, customer data)
- [x] Connection testing and validation
- [x] Action templates (Check Order Status, Track Shipment, Return Request, Cancel Order, Customer Lookup)
- [x] Input/output variable mapping for API actions
- [x] Database schema for data_sources and api_connections tables
- [x] Write tests for all new features (144 total passing across 6 files)
