# React Migration Plan - Single Page at a Time ## Overview Gradual migration from PHP to React while maintaining full system functionality. Both PHP and React versions will coexist during the transition period. --- ## ✅ COMPLETED: Phase 0 - Foundation Setup (Completed: January 9, 2026) **Status**: All foundation setup tasks completed successfully! - React app deployed and accessible at: https://rebusys.uk/red-desk-v4/react-app/dist/ - Authentication working with live PHP session sharing - API infrastructure created and tested - Ready to proceed to Phase 1: Core Infrastructure --- ## Phase 0: Foundation Setup (Week 1-2) ### 0.1 Project Structure ``` /home/keith/git/red-desk-v3/ ├── api/ # NEW: REST API endpoints │ ├── auth/ │ │ ├── check.php # Session validation │ │ └── user.php # Current user info │ ├── tickets/ │ ├── clients/ │ ├── quotes/ │ ├── activities/ │ └── shared/ │ ├── db.php # Database connection │ ├── auth-middleware.php # Auth checking │ └── response.php # JSON response helpers ├── react-app/ # NEW: React application │ ├── public/ │ ├── src/ │ │ ├── components/ │ │ ├── pages/ │ │ ├── hooks/ │ │ ├── services/ # API calls │ │ ├── contexts/ # Auth, theme, etc. │ │ └── App.jsx │ ├── package.json │ └── vite.config.js ├── [existing PHP files] # Keep all existing files └── .htaccess # Update for routing ``` ### 0.2 Technology Stack - **Frontend**: React 18+ with Vite - **Routing**: React Router v6 - **State Management**: React Context + hooks (start simple) - **HTTP Client**: Axios or fetch - **UI Framework**: Bootstrap 5 (matches current design) or Material-UI - **Forms**: React Hook Form - **Date Handling**: date-fns or day.js ### 0.3 Initial Setup Tasks - [x] Install Node.js and npm (Node v16.20.2, npm v8.19.4) - [x] Create React app with Vite 4.5.3 (Node 16 compatible) - [x] Install core dependencies (react-router-dom, axios, bootstrap, bootstrap-icons, react-hook-form) - [x] Create `/api` directory structure - [x] Create shared API authentication middleware - [x] Set up CORS configuration - [x] Update `.htaccess` for routing - [x] Create API response helper functions - [x] Set up environment variables (.env files) ### 0.4 Authentication Bridge ✅ COMPLETE Create shared authentication between PHP and React: **API Endpoint**: `api/auth/check.php` ✅ - Validates existing PHP session - Returns user data as JSON - Returns 401 if not authenticated **API Endpoint**: `api/auth/user.php` ✅ - Returns detailed user information - Requires authentication **React Auth Context**: `src/contexts/AuthContext.jsx` ✅ - Checks authentication on app load - Stores user data - Redirects to PHP login if unauthenticated (optional, can be enabled) - Provides auth state to all components - Successfully tested with live PHP session --- ## ✅ Phase 1: Core Infrastructure (Week 3-4) - COMPLETE ### 1.1 Database API Layer ✅ Create reusable database connection and query helpers: - [x] `api/shared/db.php` - Database connection (completed in Phase 0) - [x] `api/shared/auth-middleware.php` - Session validation (completed in Phase 0) - [x] `api/shared/response.php` - JSON response formatting (completed in Phase 0) ### 1.2 Common API Endpoints ✅ Build foundational endpoints used across multiple pages: - [x] `api/auth/check.php` - Authentication status (completed in Phase 0) - [x] `api/auth/user.php` - Current user details (completed in Phase 0) - [x] `api/clients/list.php` - Client dropdown data with pagination and search - [x] `api/clients/contacts.php` - Contact dropdown data with client filtering - [x] `api/resources/engineers.php` - Engineer list with role filtering ### 1.3 React Core Components ✅ Build reusable UI components: - [x] Layout components (Header, Sidebar, Footer, Layout wrapper) - [x] DataTable component (sortable, clickable rows, empty states) - [x] Form components (Input, Select, Textarea, DatePicker, Checkbox) - [x] Modal component (with backdrop, sizes, footer support) - [x] Loading/Error states (Loading spinner, ErrorMessage, EmptyState) - [x] Notification/Toast component (with ToastContext for easy usage) ### 1.4 Routing Configuration ✅ React Router configured with all main application routes: - [x] App.jsx updated with React Router and all route definitions - [x] ToastProvider integrated at app level - [x] Placeholder pages created for all main routes: - Dashboard (`/dashboard`) - Tickets (`/tickets`) - Clients (`/clients`) - Contacts (`/contacts`) - Quotes (`/quotes`) - Calendar (`/calendar`) - Reports (`/reports`) - Test page (`/test`) - [x] Default route redirects to `/dashboard` - [x] 404 handling (redirects to dashboard) - [x] `.htaccess` configured to serve React app (completed in Phase 0) --- ## Phase 1a: Authentication ### 1.0 Authentication Create a new authentication system to replace the current system in /auth. This needs to maintain access for both old and new codebase. ## Phase 2: First Migration - Dashboard (Week 5-6) ### Why Dashboard First? - Mostly read-only (lower risk) - Heavy on data visualization (shows React benefits) - High visibility (demonstrates progress) - No complex forms to handle ### 2.1 API Endpoints for Dashboard Create these endpoints in `api/dashboard/`: - `summary.php` - Overview metrics - `monthly-tickets.php` - Ticket trends - `engineer-time.php` - Engineer utilization - `uninvoiced-value.php` - Financial metrics - `active-expenses.php` - Expense data - `quote-win-rate.php` - Quote statistics ### 2.2 React Dashboard Page - `src/pages/Dashboard.jsx` - Main dashboard - `src/components/dashboard/MetricCard.jsx` - Stat cards - `src/components/dashboard/ChartWidget.jsx` - Charts - `src/services/dashboardService.js` - API calls ### 2.3 Migration Checklist - [ ] Create all dashboard API endpoints - [ ] Test API endpoints with Postman/curl - [ ] Build React dashboard components - [ ] Implement charts (Chart.js or Recharts) - [ ] Match existing dashboard layout/design - [ ] Test with real data - [ ] Add loading states - [ ] Add error handling - [ ] Update navigation to link to `/app/dashboard` - [ ] Deploy and monitor ### 2.4 Deployment Strategy - Deploy React dashboard to `/app/dashboard` - Keep PHP dashboard at `/dashboard.php` - Update main menu to point to React version - Monitor for 1 week before removing PHP version --- ## Phase 3: Second Migration - Client Management (Week 7-9) ### Why Clients Second? - Moderately complex (has forms) - Core business functionality - Tests CRUD operations - Manageable scope ### 3.1 API Endpoints for Clients Create these endpoints in `api/clients/`: - `list.php` - Client list with pagination/search - `details.php?id=X` - Single client details - `create.php` (POST) - Create new client - `update.php` (POST) - Update client - `delete.php` (POST) - Delete/deactivate client - `sites.php?client_id=X` - Client sites - `contacts.php?client_id=X` - Client contacts - `summary.php?id=X` - Client summary data ### 3.2 React Client Pages - `src/pages/clients/ClientList.jsx` - Client listing - `src/pages/clients/ClientSummary.jsx` - Client details - `src/pages/clients/ClientForm.jsx` - Create/edit form - `src/components/clients/ClientTable.jsx` - Reusable table - `src/components/clients/SitesList.jsx` - Sites component - `src/services/clientService.js` - API calls ### 3.3 Migration Checklist - [ ] Create all client API endpoints - [ ] Build client list page with search/filter - [ ] Build client detail/summary page - [ ] Build client create/edit form - [ ] Implement form validation - [ ] Test all CRUD operations - [ ] Add confirmation dialogs for delete - [ ] Handle errors gracefully - [ ] Update routes in .htaccess - [ ] Update navigation links - [ ] Deploy and monitor for 1 week --- ## Phase 4: Third Migration - Ticket Management (Week 10-14) ### Why Tickets Third? - Most complex/critical feature - By now, team is comfortable with React - Can reuse patterns from clients - Highest user interaction ### 4.1 API Endpoints for Tickets Create these endpoints in `api/tickets/`: - `list.php` - Ticket list with filters - `details.php?id=X` - Ticket details - `summary.php?id=X` - Ticket summary - `create.php` (POST) - Create ticket - `update.php` (POST) - Update ticket - `close.php` (POST) - Close ticket - `notes.php?ticket_id=X` - Ticket notes - `activities.php?ticket_id=X` - Ticket activities - `files.php?ticket_id=X` - File attachments - `images.php?ticket_id=X` - Image attachments - `expenses.php?ticket_id=X` - Ticket expenses - `timesheet.php?ticket_id=X` - Time entries - `stats.php?id=X` - Ticket statistics ### 4.2 React Ticket Pages - `src/pages/tickets/TicketList.jsx` - Ticket listing - `src/pages/tickets/TicketSummary.jsx` - Ticket details - `src/pages/tickets/TicketForm.jsx` - Create/edit - `src/pages/tickets/TicketSearch.jsx` - Search modal - `src/components/tickets/NotesPanel.jsx` - Notes section - `src/components/tickets/ActivitiesPanel.jsx` - Activities - `src/components/tickets/FilesPanel.jsx` - File uploads - `src/components/tickets/TimesheetPanel.jsx` - Time tracking - `src/services/ticketService.js` - API calls ### 4.3 Migration Checklist - [ ] Create all ticket API endpoints - [ ] Build ticket list with advanced filtering - [ ] Build ticket summary page with tabs - [ ] Build ticket create/edit form - [ ] Implement file upload functionality - [ ] Build notes/comments component - [ ] Build activities timeline - [ ] Build timesheet entry component - [ ] Implement ticket status workflow - [ ] Add real-time updates (optional: WebSockets) - [ ] Test all workflows thoroughly - [ ] Deploy and monitor for 2 weeks --- ## Phase 5: Remaining Pages (Week 15-24) ### 5.1 Quote Management (Week 15-17) - API: `api/quotes/` - Pages: Quote list, summary, create/edit, line items - Similar complexity to tickets ### 5.2 Calendar/Activities (Week 18-19) - API: `api/calendar/`, `api/activities/` - Pages: Calendar view, activity planning - Consider using FullCalendar library for React ### 5.3 Contact Management (Week 20) - API: `api/contacts/` - Pages: Contact list, details, create/edit - Similar to clients (reuse patterns) ### 5.4 Employee/Resource Management (Week 21) - API: `api/employees/`, `api/vehicles/`, `api/resources/` - Pages: Employee list/details, vehicle tracking, accreditations ### 5.5 Invoicing (Week 22) - API: `api/invoices/` - Pages: Invoice list, uninvoiced items, invoice details - Keep PDF generation in PHP backend ### 5.6 Reports (Week 23-24) - API: `api/reports/` - Pages: Various reports, annual leave, method statements - Keep PDF/Excel generation in PHP backend - React just displays and triggers generation --- ## Phase 6: Module-Specific Features (Week 25-32) ### 6.1 Red Engineer Module - Mobile-friendly timesheet entry - Expense submission - File/image uploads - Activity management ### 6.2 Red Gas Module - Gas certificate forms - Service records - Appliance testing ### 6.3 Red Air Module - Air certificate forms ### 6.4 Red Drain Module - Drain survey forms ### 6.5 Red PAT Module - PAT testing certificates ### 6.6 Red ME Module - Building/portfolio management - Service tracking --- ## Phase 7: Optimization & Polish (Week 33-36) ### 7.1 Performance Optimization - [ ] Implement code splitting - [ ] Add lazy loading for routes - [ ] Optimize API responses (pagination, field selection) - [ ] Add caching strategies - [ ] Optimize images and assets - [ ] Implement service worker for offline support (optional) ### 7.2 User Experience Enhancements - [ ] Add loading skeletons - [ ] Improve error messages - [ ] Add success notifications - [ ] Implement keyboard shortcuts - [ ] Add dark mode (optional) - [ ] Improve mobile responsiveness - [ ] Add print stylesheets ### 7.3 Testing - [ ] Unit tests for critical components - [ ] Integration tests for API calls - [ ] End-to-end tests for critical workflows - [ ] Cross-browser testing - [ ] Mobile device testing - [ ] Performance testing ### 7.4 Documentation - [ ] API documentation - [ ] Component documentation - [ ] User guide updates - [ ] Developer onboarding guide --- ## Phase 8: PHP Cleanup (Week 37-40) ### 8.1 Remove PHP Frontend Files Once all pages are migrated and stable: - [ ] Backup entire PHP codebase - [ ] Remove PHP view files (keep API backend) - [ ] Update .htaccess to route all traffic to React - [ ] Remove unused dependencies - [ ] Clean up old assets ### 8.2 Backend Consolidation - [ ] Consolidate API endpoints - [ ] Standardize API response formats - [ ] Add API versioning - [ ] Add API rate limiting - [ ] Improve API security - [ ] Add API logging/monitoring --- ## Migration Best Practices ### Development Workflow 1. **Always create API endpoint first** - Test with Postman/curl 2. **Build React page second** - Connect to tested API 3. **Deploy both versions** - New at `/app/X`, old at `/X.php` 4. **Monitor for 1-2 weeks** - Check for issues 5. **Deprecate old version** - Remove PHP page 6. **Update documentation** - Keep docs current ### Code Standards - **API**: RESTful conventions, consistent JSON responses - **React**: Functional components with hooks - **Naming**: Clear, descriptive names for components/files - **Comments**: Document complex logic - **Error Handling**: Always handle errors gracefully - **Validation**: Validate on both frontend and backend ### Testing Strategy - Test each new API endpoint thoroughly before building UI - Test React components in isolation - Test complete workflows end-to-end - Have users test new pages before deprecating old ones - Monitor error logs daily during migration ### Rollback Plan If a React page has critical issues: 1. Update navigation to point back to PHP version 2. Fix issues in development 3. Re-deploy and test thoroughly 4. Switch back to React version --- ## Success Metrics ### Technical Metrics - API response time < 200ms (95th percentile) - Page load time < 2 seconds - Zero critical bugs in production - 100% feature parity with PHP version ### User Metrics - User satisfaction maintained or improved - No increase in support tickets - Positive feedback on new interface - Training time for new features reduced ### Business Metrics - Development velocity increased - Bug fix time reduced - Easier to onboard new developers - Modern, maintainable codebase --- ## Timeline Summary | Phase | Weeks | Deliverable | |-------|-------|-------------| | 0 - Foundation | 1-2 | React setup, API structure, auth bridge | | 1 - Infrastructure | 3-4 | Core APIs, shared components | | 2 - Dashboard | 5-6 | Dashboard migrated to React | | 3 - Clients | 7-9 | Client management in React | | 4 - Tickets | 10-14 | Ticket management in React | | 5 - Remaining Pages | 15-24 | Quotes, calendar, contacts, etc. | | 6 - Modules | 25-32 | Red-* modules migrated | | 7 - Polish | 33-36 | Optimization, testing, docs | | 8 - Cleanup | 37-40 | Remove old PHP frontend | **Total Duration**: 9-10 months (assuming 1 developer working part-time) --- ## Risk Mitigation ### Technical Risks - **Risk**: API performance issues with large datasets - **Mitigation**: Implement pagination, caching, database indexing - **Risk**: Session management between PHP and React - **Mitigation**: Thorough testing of auth flow, use HTTP-only cookies - **Risk**: File upload complexity - **Mitigation**: Start with simple uploads, use proven libraries ### Business Risks - **Risk**: User resistance to UI changes - **Mitigation**: Keep UI similar initially, gather feedback, iterate - **Risk**: Extended timeline impacts other projects - **Mitigation**: Prioritize critical pages, maintain PHP as fallback - **Risk**: Knowledge gap in React - **Mitigation**: Training, pair programming, code reviews --- ## Next Steps 1. **Review and approve this plan** 2. **Set up development environment** (Phase 0) 3. **Create project timeline** with specific dates 4. **Assign resources** (developers, testers) 5. **Begin Phase 0** - Foundation setup 6. **Schedule weekly progress reviews** 7. **Start API development** for dashboard 8. **Begin React development** in parallel --- ## Notes - This plan assumes one developer working part-time on the migration - Adjust timeline based on team size and availability - Prioritize pages based on business needs - Consider running A/B tests for critical pages - Keep stakeholders informed of progress - Celebrate milestones to maintain momentum