# Frontend Documentation โ€“ Funeral Policy Manager (Production Implementation Guide) ## ๐Ÿ“Œ 1. Overview This is the complete frontend documentation for a **unified funeral policy management web application** that serves both Branch Staff and Admin users, integrated with a **100% complete backend API system**. | Application | Description | Technology Stack | |-------------|-------------|------------------| | **Funeral Policy Manager** | Single unified web app for all staff | React 18 + Vite + Tailwind CSS + TypeScript | **Key Features:** - **Role-based interface** - Different dashboards and permissions for Branch vs Admin users - **Single codebase** - Easier maintenance and deployment - **Production-ready** - Built for scalability and performance - **37 complete backend endpoints** - Fully functional API integration **โš ๏ธ CRITICAL: This documentation is for an AI agent (Copilot) to build PRODUCTION-READY code. No shortcuts, no demo code, no placeholder functions. Every component must be fully functional, secure, and optimized for production use.** --- ## ๐Ÿ› ๏ธ 2. Production Tech Stack | Layer | Technology | Version | Purpose | |-------|------------|---------|---------| | **Framework** | React 18 + Vite 5 | Latest | Fast development + HMR | | **Language** | TypeScript 5 | Latest | Type safety + IntelliSense | | **API Layer** | Axios + React Query | Latest | HTTP client + caching | | **State Management** | Zustand + React Context | Latest | Global state + auth | | **Navigation** | React Router v6 | Latest | SPA routing | | **UI Framework** | Tailwind CSS + Headless UI | Latest | Responsive design | | **Forms** | React Hook Form + Zod | Latest | Validation + performance | | **Charts** | Recharts | Latest | Analytics dashboards | | **Icons** | Heroicons | Latest | Consistent iconography | | **Testing** | Vitest + Testing Library | Latest | Unit + integration tests | | **Build Tool** | Vite | Latest | Fast builds + bundling | | **Deployment** | Netlify / Vercel | Latest | CDN + auto-deploy | **โš ๏ธ PRODUCTION REQUIREMENTS:** - All dependencies must be pinned to specific versions - TypeScript strict mode enabled - ESLint + Prettier configured - Environment variables for all configs - Error boundaries for all major components - Loading states for all async operations - Proper error handling with user feedback --- ## ๐Ÿงฑ 3. Production Folder Structure ### ๐Ÿ–ฅ๏ธ Unified Web Application (funeral-policy-manager) ``` funeral-policy-manager/ โ”œโ”€โ”€ public/ โ”‚ โ”œโ”€โ”€ favicon.ico โ”‚ โ”œโ”€โ”€ manifest.json โ”‚ โ””โ”€โ”€ robots.txt โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ components/ # Reusable UI components โ”‚ โ”‚ โ”œโ”€โ”€ ui/ # Base UI components (Button, Input, etc.) โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Button.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Input.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Modal.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Table.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”‚ โ”œโ”€โ”€ forms/ # Form-specific components โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ PolicyForm.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ClaimForm.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ PaymentForm.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”‚ โ”œโ”€โ”€ layout/ # Layout components โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Header.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Sidebar.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Layout.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”‚ โ”œโ”€โ”€ charts/ # Analytics charts โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ DashboardChart.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ClaimsChart.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”‚ โ””โ”€โ”€ shared/ # Shared components โ”‚ โ”‚ โ”œโ”€โ”€ LoadingSpinner.tsx โ”‚ โ”‚ โ”œโ”€โ”€ ErrorBoundary.tsx โ”‚ โ”‚ โ”œโ”€โ”€ ConfirmDialog.tsx โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”œโ”€โ”€ pages/ # Page components (route components) โ”‚ โ”‚ โ”œโ”€โ”€ auth/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ LoginPage.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ProfilePage.tsx โ”‚ โ”‚ โ”œโ”€โ”€ dashboard/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ DashboardPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ BranchDashboard.tsx # For branch users โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ AdminDashboard.tsx # For admin users โ”‚ โ”‚ โ”œโ”€โ”€ policies/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ PoliciesPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ CreatePolicyPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ PolicyDetailsPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ UpdatePolicyPage.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ PolicyTypesPage.tsx # Admin only โ”‚ โ”‚ โ”œโ”€โ”€ members/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ MembersPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ AddMemberPage.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ UploadDocumentsPage.tsx โ”‚ โ”‚ โ”œโ”€โ”€ claims/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ClaimsPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ QueueClaimPage.tsx # Branch users โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ApproveClaimPage.tsx # Admin users โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ RejectClaimPage.tsx # Admin users โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ RecordPayoutPage.tsx # Admin users โ”‚ โ”‚ โ”œโ”€โ”€ payments/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ PaymentsPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ RecordPaymentPage.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ SuspensionCheckPage.tsx # Admin only โ”‚ โ”‚ โ”œโ”€โ”€ tickets/ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ TicketsPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ CreateTicketPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ TicketDetailsPage.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ResolveTicketPage.tsx # Admin only โ”‚ โ”‚ โ”œโ”€โ”€ reports/ # Admin only โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ReportsPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ClaimReportPage.tsx โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ PaymentReportPage.tsx โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ BranchReportPage.tsx โ”‚ โ”‚ โ”œโ”€โ”€ users/ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ CreateUserPage.tsx โ”‚ โ”‚ โ””โ”€โ”€ tools/ โ”‚ โ”‚ โ”œโ”€โ”€ QRScannerPage.tsx # Branch users โ”‚ โ”‚ โ””โ”€โ”€ NotificationsPage.tsx # Admin users โ”‚ โ”œโ”€โ”€ services/ # API service layer โ”‚ โ”‚ โ”œโ”€โ”€ api.ts # Base API configuration โ”‚ โ”‚ โ”œโ”€โ”€ auth.service.ts โ”‚ โ”‚ โ”œโ”€โ”€ policy.service.ts โ”‚ โ”‚ โ”œโ”€โ”€ claim.service.ts โ”‚ โ”‚ โ”œโ”€โ”€ payment.service.ts โ”‚ โ”‚ โ”œโ”€โ”€ ticket.service.ts โ”‚ โ”‚ โ”œโ”€โ”€ report.service.ts โ”‚ โ”‚ โ”œโ”€โ”€ notification.service.ts โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”œโ”€โ”€ stores/ # Global state management โ”‚ โ”‚ โ”œโ”€โ”€ auth.store.ts # Authentication state โ”‚ โ”‚ โ”œโ”€โ”€ app.store.ts # Application state โ”‚ โ”‚ โ”œโ”€โ”€ notification.store.ts โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”œโ”€โ”€ hooks/ # Custom React hooks โ”‚ โ”‚ โ”œโ”€โ”€ useAuth.ts โ”‚ โ”‚ โ”œโ”€โ”€ useApi.ts โ”‚ โ”‚ โ”œโ”€โ”€ usePermissions.ts โ”‚ โ”‚ โ”œโ”€โ”€ useNotifications.ts โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”œโ”€โ”€ utils/ # Utility functions โ”‚ โ”‚ โ”œโ”€โ”€ formatters.ts # Data formatting โ”‚ โ”‚ โ”œโ”€โ”€ validators.ts # Form validation schemas โ”‚ โ”‚ โ”œโ”€โ”€ constants.ts # App constants โ”‚ โ”‚ โ”œโ”€โ”€ permissions.ts # Role-based permissions โ”‚ โ”‚ โ”œโ”€โ”€ types.ts # TypeScript type definitions โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”œโ”€โ”€ routes/ # Route configuration โ”‚ โ”‚ โ”œโ”€โ”€ AppRouter.tsx # Main router component โ”‚ โ”‚ โ”œโ”€โ”€ ProtectedRoute.tsx โ”‚ โ”‚ โ”œโ”€โ”€ AdminRoute.tsx # Admin-only routes โ”‚ โ”‚ โ”œโ”€โ”€ BranchRoute.tsx # Branch-only routes โ”‚ โ”‚ โ””โ”€โ”€ index.ts โ”‚ โ”œโ”€โ”€ styles/ # Global styles โ”‚ โ”‚ โ”œโ”€โ”€ globals.css # Global CSS + Tailwind โ”‚ โ”‚ โ””โ”€โ”€ components.css # Component-specific styles โ”‚ โ”œโ”€โ”€ App.tsx # Root component โ”‚ โ”œโ”€โ”€ main.tsx # App entry point โ”‚ โ””โ”€โ”€ vite-env.d.ts # Vite type definitions โ”œโ”€โ”€ .env.example # Environment variables template โ”œโ”€โ”€ .env.local # Local environment (gitignored) โ”œโ”€โ”€ .gitignore โ”œโ”€โ”€ .eslintrc.js # ESLint configuration โ”œโ”€โ”€ .prettierrc # Prettier configuration โ”œโ”€โ”€ tailwind.config.js # Tailwind configuration โ”œโ”€โ”€ tsconfig.json # TypeScript configuration โ”œโ”€โ”€ vite.config.ts # Vite configuration โ”œโ”€โ”€ package.json # Dependencies and scripts โ””โ”€โ”€ README.md # Setup instructions **โš ๏ธ PRODUCTION STRUCTURE REQUIREMENTS:** - Every file must have proper TypeScript interfaces - All components must be exported through index.ts files - Error boundaries must wrap all page components - Loading states for every API call - Consistent naming conventions (PascalCase for components, camelCase for functions) - JSDoc comments for all public functions and complex logic --- ## ๐Ÿ—„๏ธ 4. Complete Database Schema The backend uses a MySQL database with **13 core tables**: ### **Core Tables:** 1. **`users`** - User accounts with roles (client, branch_admin, admin) 2. **`branches`** - Branch locations and contact info 3. **`policy_types`** - Policy plans with pricing and member limits 4. **`policies`** - Individual policies with status tracking 5. **`policy_members`** - Family members covered by policies 6. **`payments`** - Payment records and history 7. **`claims`** - Death claims with approval workflow 8. **`claim_payouts`** - Payout records with beneficiary details 9. **`tickets`** - Support ticket system 10. **`ticket_messages`** - Ticket conversation threads 11. **`signatures`** - Digital signatures for claims/policies 12. **`notifications`** - Push notifications and alerts 13. **`user_tokens`** - Authentication tokens ### **Key Field Details:** ```sql -- Users table structure users: id, name, phone, email, password, role, branch_id, status, push_token, created_at -- Policies table structure policies: id, policy_number, user_id, policy_type_id, branch_id, start_date, status, last_payment -- Claims table structure claims: id, policy_id, member_id, description, documents, status, submitted_by, approved_by, queued_at, approved_at -- Tickets table structure tickets: id, ticket_number, subject, context_type, context_id, priority, created_by, status, resolved_at ``` --- ## ๐Ÿ” 5. Authentication & Session Management ### **Authentication Flow:** 1. **Login** via email + password 2. **Token** stored in LocalStorage (web) 3. **Token** sent with every API request via `Authorization: Bearer {token}` 4. **Session** expires after 30 days or manual logout 5. **Role-based** access control enforced by backend ### **Implementation Example:** ```javascript // AuthContext.js const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [token, setToken] = useState(null); const [loading, setLoading] = useState(true); const login = async (email, password) => { try { const response = await api.post('/shared/login.php', { email, password }); if (response.data.status === 'success') { setUser(response.data.data.user); setToken(response.data.data.token); // Store in LocalStorage localStorage.setItem('token', response.data.data.token); return { success: true }; } } catch (error) { return { success: false, message: error.response?.data?.message || 'Login failed' }; } }; const logout = async () => { try { await api.post('/shared/logout.php'); } finally { setUser(null); setToken(null); localStorage.removeItem('token'); } }; return ( {children} ); }; ``` --- ## ๐Ÿ“ก 6. Complete API Integration ### **API Base Configuration:** ```javascript // api.js import axios from 'axios'; const API_BASE_URL = 'https://policy.dannel.co.za/api/routes'; const api = axios.create({ baseURL: API_BASE_URL, timeout: 10000, headers: { 'Content-Type': 'application/json', }, }); // Request interceptor to add auth token api.interceptors.request.use((config) => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); // Response interceptor for error handling api.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401) { // Redirect to login on token expiry localStorage.removeItem('token'); window.location.href = '/login'; } return Promise.reject(error); } ); ``` ### **API Service Examples:** ```javascript // policyService.js export const policyService = { // Get policy details getPolicy: async (policyId) => { const response = await api.get(`/clients/get_policy.php?policy_id=${policyId}`); return response.data; }, // Create new policy (Branch Admin) createPolicy: async (policyData) => { const response = await api.post('/branches/create_policy.php', policyData); return response.data; }, // Update policy (Branch Admin/Admin) updatePolicy: async (policyId, updateData) => { const response = await api.post('/branches/update_policy.php', { policy_id: policyId, ...updateData }); return response.data; }, // Get policy statement getStatement: async (policyId) => { const response = await api.get(`/shared/get_statement.php?policy_id=${policyId}`); return response.data; } }; // claimService.js export const claimService = { // Submit new claim (Client) submitClaim: async (claimData) => { const response = await api.post('/clients/submit_claim.php', claimData); return response.data; }, // Get claims list with filtering getClaims: async (filters = {}) => { const params = new URLSearchParams(filters).toString(); const response = await api.get(`/shared/get_claims.php?${params}`); return response.data; }, // Queue claim for admin review (Branch) queueClaim: async (claimId, notes) => { const response = await api.post('/branches/queue_claim.php', { claim_id: claimId, notes }); return response.data; }, // Approve claim (Admin) approveClaim: async (claimId, adminNotes) => { const response = await api.post('/admin/approve_claim.php', { claim_id: claimId, admin_notes: adminNotes }); return response.data; }, // Record payout (Admin) recordPayout: async (payoutData) => { const response = await api.post('/admin/record_payout.php', payoutData); return response.data; } }; // ticketService.js export const ticketService = { // Create support ticket createTicket: async (ticketData) => { const response = await api.post('/shared/create_ticket.php', ticketData); return response.data; }, // Get tickets list getTickets: async (filters = {}) => { const params = new URLSearchParams(filters).toString(); const response = await api.get(`/shared/get_tickets.php?${params}`); return response.data; }, // Reply to ticket replyToTicket: async (ticketId, message, isInternal = false) => { const response = await api.post('/shared/reply_ticket.php', { ticket_id: ticketId, message, is_internal: isInternal }); return response.data; }, // Resolve ticket (Admin) resolveTicket: async (ticketId, resolutionNotes) => { const response = await api.post('/admin/resolve_ticket.php', { ticket_id: ticketId, resolution_notes: resolutionNotes }); return response.data; } }; ``` --- ## ๐Ÿ‘ฅ 7. Role-Based Application Design ### ๐ŸŽฏ Unified App with Role-Based Interface The application dynamically shows different interfaces based on user role: #### **๐ŸŸง Branch Staff Features** | Page/Feature | Description | API Endpoints | Access Level | |--------------|-------------|---------------|--------------| | **Dashboard** | Branch metrics, daily tasks, policy overview | `admin/get_branch_summary.php` | Branch Only | | **Policy Management** | Create, view, update policies for branch clients | `branches/create_policy.php`, `branches/update_policy.php` | Branch + Admin | | **Member Management** | Add/remove members, upload documents | `branches/add_member.php`, `branches/remove_member.php` | Branch + Admin | | **Payment Processing** | Record client payments, view payment history | `branches/record_payment.php`, `shared/get_statement.php` | Branch + Admin | | **Claims Handling** | Queue claims for admin review | `branches/queue_claim.php`, `shared/get_claims.php` | Branch + Admin | | **QR Scanner** | Scan client virtual cards for quick access | `branches/scan_qr.php` | Branch Only | | **Support Tickets** | Create and reply to support tickets | `shared/create_ticket.php`, `shared/reply_ticket.php` | Branch + Admin | | **User Management** | Create new branch users | `branches/create_user.php` | Branch + Admin | #### **๐ŸŸฅ Admin Features (All Branch Features +)** | Page/Feature | Description | API Endpoints | Access Level | |--------------|-------------|---------------|--------------| | **Global Dashboard** | System-wide metrics, all branches overview | `admin/get_global_summary.php` | Admin Only | | **Policy Types** | Create and manage policy plans | `admin/create_policy_type.php` | Admin Only | | **Claims Approval** | Approve/reject claims, record payouts | `admin/approve_claim.php`, `admin/reject_claim.php` | Admin Only | | **Advanced Reports** | Claims, payment, and branch performance reports | `admin/get_claim_report.php`, `admin/get_payment_report.php` | Admin Only | | **System Management** | Run suspension checks, manage notifications | `admin/run_suspension_check.php`, `admin/send_notification.php` | Admin Only | | **Ticket Resolution** | Resolve escalated support tickets | `admin/resolve_ticket.php` | Admin Only | | **All Branch Access** | View and manage any branch's data | Various with branch filtering | Admin Only | ### **๐Ÿ” Role-Based UI Implementation** ```tsx // Example: Conditional rendering based on user role const DashboardPage = () => { const { user } = useAuth(); if (user.role === 'admin') { return ; } else if (user.role === 'branch_admin') { return ; } return ; }; // Example: Protected route with role checking const AdminRoute = ({ children }: { children: React.ReactNode }) => { const { user, isLoading } = useAuth(); if (isLoading) return ; if (!user || user.role !== 'admin') { return ; } return <>{children}; }; ``` **โš ๏ธ CRITICAL SECURITY REQUIREMENT:** - Every route must check user permissions - API calls must include proper authentication headers - Role-based access control must be enforced on both frontend and backend - No sensitive admin features should be visible to branch users - All state management must respect user permissions --- ## ๐Ÿงพ 8. Complete API Response Standards ### **Success Response Format:** ```json { "status": "success", "data": { // Response data object or array }, "message": "Optional success message" } ``` ### **Error Response Format:** ```json { "status": "error", "message": "Error description", "data": { // Optional additional error data } } ``` ### **Complete API Endpoint Reference:** #### **Authentication (3 endpoints)** ```javascript // Login POST /shared/login.php Body: { email, password } // Logout POST /shared/logout.php Headers: Authorization: Bearer {token} // Get Profile GET /shared/get_profile.php Headers: Authorization: Bearer {token} ``` #### **Policy Management (5 endpoints)** ```javascript // Create policy type (Admin only) POST /admin/create_policy_type.php Body: { name, description, premium, max_members } // Get policy types GET /shared/get_policy_types.php // Create policy (Branch Admin) POST /branches/create_policy.php Body: { user_id, policy_type_id, start_date } // Get policy details GET /clients/get_policy.php?policy_id={id} // Update policy (Branch/Admin) POST /branches/update_policy.php Body: { policy_id, status?, end_date?, notes? } ``` #### **Member Management (3 endpoints)** ```javascript // Add member POST /branches/add_member.php Body: { policy_id, name, type, dob } // Upload member documents POST /branches/upload_member_docs.php Body: FormData with files // Remove member POST /branches/remove_member.php Body: { member_id, reason } ``` #### **Payments & Billing (3 endpoints)** ```javascript // Record payment POST /branches/record_payment.php Body: { policy_id, amount, method, paid_on } // Get policy statement GET /shared/get_statement.php?policy_id={id} // Run suspension check (Admin) GET /admin/run_suspension_check.php ``` #### **Claims Workflow (6 endpoints)** ```javascript // Submit claim (Client) POST /clients/submit_claim.php Body: { policy_id, member_id, description, documents } // Get claims list GET /shared/get_claims.php?status={status}&policy_id={id} // Queue claim (Branch) POST /branches/queue_claim.php Body: { claim_id, notes } // Approve claim (Admin) POST /admin/approve_claim.php Body: { claim_id, admin_notes } // Reject claim (Admin) POST /admin/reject_claim.php Body: { claim_id, rejection_reason, admin_notes } // Record payout (Admin) POST /admin/record_payout.php Body: { claim_id, amount, beneficiary_name, beneficiary_relationship, payment_method, reference_number } ``` #### **Ticket System (4 endpoints)** ```javascript // Create ticket POST /shared/create_ticket.php Body: { subject, context_type, context_id, priority, message } // Reply to ticket POST /shared/reply_ticket.php Body: { ticket_id, message, is_internal } // Get tickets GET /shared/get_tickets.php?status={status}&priority={priority} // Resolve ticket (Admin) POST /admin/resolve_ticket.php Body: { ticket_id, resolution_notes } ``` #### **Signature System (2 endpoints)** ```javascript // Submit signature POST /shared/submit_signature.php Body: { context_type, context_id, signature } // Get signature GET /shared/get_signature.php?signature_id={id} ``` #### **Virtual Card/QR (2 endpoints)** ```javascript // Get virtual card data (Client) GET /clients/get_virtual_card_data.php // Scan QR code (Branch) POST /branches/scan_qr.php Body: { qr_data } ``` #### **Notifications (2 endpoints)** ```javascript // Get notifications GET /shared/get_notifications.php?page={page}&limit={limit} // Send notification (Admin) POST /admin/send_notification.php Body: { user_id, title, body } ``` #### **Reports & Analytics (4 endpoints)** ```javascript // Branch summary GET /admin/get_branch_summary.php?branch_id={id}&period={period} // Global summary GET /admin/get_global_summary.php?period={period} // Claims report GET /admin/get_claim_report.php?start_date={date}&end_date={date} // Payment report GET /admin/get_payment_report.php?start_date={date}&end_date={date} ``` #### **System Endpoints (2 endpoints)** ```javascript // Health check GET /shared/health.php // API documentation GET /index.php ``` --- ## โœ… 9. Frontend Development Guidelines ### **Code Quality Standards:** ```javascript // โœ… Always validate forms const validatePolicyForm = (data) => { const errors = {}; if (!data.user_id) errors.user_id = 'Client is required'; if (!data.policy_type_id) errors.policy_type_id = 'Policy type is required'; if (!data.start_date) errors.start_date = 'Start date is required'; return { isValid: Object.keys(errors).length === 0, errors }; }; // โœ… Use proper error handling const handleSubmit = async (formData) => { try { setLoading(true); const { isValid, errors } = validatePolicyForm(formData); if (!isValid) { setFormErrors(errors); return; } const response = await policyService.createPolicy(formData); if (response.status === 'success') { showSuccess('Policy created successfully'); navigate('/policies'); } else { showError(response.message || 'Failed to create policy'); } } catch (error) { showError(error.response?.data?.message || 'Network error'); } finally { setLoading(false); } }; // โœ… Use loading and error states const PolicyList = () => { const [policies, setPolicies] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchPolicies = async () => { try { const response = await policyService.getPolicies(); if (response.status === 'success') { setPolicies(response.data); } } catch (err) { setError('Failed to load policies'); } finally { setLoading(false); } }; fetchPolicies(); }, []); if (loading) return ; if (error) return ; return (
{policies.map(policy => ( ))}
); }; ``` ### **State Management Patterns:** ```javascript // โœ… Use Context for global state const AppContext = createContext(); export const AppProvider = ({ children }) => { const [notifications, setNotifications] = useState([]); const [policies, setPolicies] = useState([]); const addNotification = (notification) => { setNotifications(prev => [notification, ...prev]); }; const markNotificationRead = (id) => { setNotifications(prev => prev.map(n => n.id === id ? { ...n, read_status: true } : n) ); }; return ( {children} ); }; // โœ… Custom hooks for API calls const usePolicy = (policyId) => { const [policy, setPolicy] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { if (!policyId) return; const fetchPolicy = async () => { try { const response = await policyService.getPolicy(policyId); if (response.status === 'success') { setPolicy(response.data); } } catch (err) { setError('Failed to load policy'); } finally { setLoading(false); } }; fetchPolicy(); }, [policyId]); return { policy, loading, error, refetch: () => fetchPolicy() }; }; ``` ### **Production Code Examples:** #### TypeScript Interface Example: ```tsx // types.ts - PRODUCTION TYPE DEFINITIONS export interface User { id: number; name: string; email: string; role: 'admin' | 'branch_admin'; branch_id?: number; status: 'active' | 'suspended' | 'deleted'; created_at: string; } export interface Policy { id: number; policy_number: string; user_id: number; policy_type_id: number; branch_id: number; start_date: string; status: 'active' | 'suspended' | 'archived'; last_payment?: string; created_at: string; } export interface ApiResponse { status: 'success' | 'error'; data?: T; message?: string; } ``` #### Production Component Example: ```tsx // pages/policies/PolicyDetailsPage.tsx - PRODUCTION COMPONENT import React, { useEffect, useState } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { useQuery } from '@tanstack/react-query'; import { policyService } from '@/services'; import { LoadingSpinner, ErrorAlert, Button } from '@/components/ui'; import { usePermissions } from '@/hooks'; import type { Policy } from '@/utils/types'; const PolicyDetailsPage: React.FC = () => { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const { canEdit } = usePermissions(); const { data: policy, isLoading, error, refetch } = useQuery({ queryKey: ['policy', id], queryFn: () => policyService.getPolicy(Number(id)), enabled: !!id, staleTime: 5 * 60 * 1000, // 5 minutes retry: 3, retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000) }); if (isLoading) { return (
); } if (error) { return ( refetch()} /> ); } if (!policy) { return (

Policy not found

); } return (

Policy #{policy.policy_number}

{canEdit && ( )}
{policy.status.toUpperCase()}

{new Date(policy.start_date).toLocaleDateString()}

); }; export default PolicyDetailsPage; ``` **โš ๏ธ PRODUCTION CODE REQUIREMENTS:** - All components must use TypeScript with strict typing - Proper error handling with user-friendly messages - Loading states for all async operations - Accessibility features (ARIA labels, keyboard navigation) - Responsive design for all screen sizes - Performance optimization (React.memo, useMemo, useCallback where needed) - Proper cleanup in useEffect hooks - Error boundaries to catch component errors --- ## ๐Ÿš€ 10. Complete Production Setup Guide ### **Step 1: Project Initialization** ```bash # Create new Vite project with TypeScript npm create vite@latest funeral-policy-manager -- --template react-ts cd funeral-policy-manager # Install production dependencies npm install \ @tanstack/react-query \ @tanstack/react-query-devtools \ react-router-dom \ react-hook-form \ @hookform/resolvers \ zod \ zustand \ axios \ @headlessui/react \ @heroicons/react \ recharts \ clsx \ tailwind-merge # Install development dependencies npm install -D \ @types/node \ @typescript-eslint/eslint-plugin \ @typescript-eslint/parser \ eslint \ eslint-plugin-react-hooks \ eslint-plugin-react-refresh \ prettier \ prettier-plugin-tailwindcss \ tailwindcss \ postcss \ autoprefixer \ vitest \ @testing-library/react \ @testing-library/jest-dom \ jsdom # Initialize Tailwind CSS npx tailwindcss init -p ``` ### **Step 2: Environment Configuration** ```bash # Create environment files cp .env.example .env.local # .env.example VITE_API_BASE_URL=https://policy.dannel.co.za/api/routes VITE_APP_NAME=Funeral Policy Manager VITE_APP_VERSION=1.0.0 VITE_UPLOAD_MAX_SIZE=5242880 VITE_ENVIRONMENT=production # .env.local (for development) VITE_API_BASE_URL=http://localhost/api/routes VITE_ENVIRONMENT=development ``` ### **Step 3: TypeScript Configuration** ```json // tsconfig.json - PRODUCTION TYPESCRIPT CONFIG { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "baseUrl": ".", "paths": { "@/*": ["./src/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ``` ### **Step 4: Vite Configuration** ```typescript // vite.config.ts - PRODUCTION VITE CONFIG import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; export default defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, './src'), }, }, build: { target: 'esnext', minify: 'terser', sourcemap: true, rollupOptions: { output: { manualChunks: { vendor: ['react', 'react-dom'], router: ['react-router-dom'], ui: ['@headlessui/react', '@heroicons/react'], api: ['axios', '@tanstack/react-query'], }, }, }, }, server: { port: 3000, host: true, }, preview: { port: 4173, host: true, }, }); ``` ### **Step 5: Package.json Scripts** ```json { "scripts": { "dev": "vite", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "lint:fix": "eslint . --ext ts,tsx --fix", "format": "prettier --write \"src/**/*.{ts,tsx,js,jsx,css,md}\"", "preview": "vite preview", "test": "vitest", "test:coverage": "vitest --coverage", "type-check": "tsc --noEmit" } } ``` ### **Step 6: Production Build Process** ```bash # Development workflow npm run dev # Start development server npm run lint # Check for linting errors npm run type-check # Check TypeScript types npm run format # Format code with Prettier # Production build workflow npm run lint:fix # Fix linting errors npm run type-check # Ensure no TypeScript errors npm run build # Build for production npm run preview # Preview production build locally # Testing workflow npm run test # Run unit tests npm run test:coverage # Run tests with coverage report ``` ### **Step 7: Deployment Configuration** #### **Netlify Deployment:** ```toml # netlify.toml [build] publish = "dist" command = "npm run build" [build.environment] NODE_VERSION = "18" [[redirects]] from = "/*" to = "/index.html" status = 200 [[headers]] for = "/static/*" [headers.values] Cache-Control = "public, max-age=31536000, immutable" ``` #### **Vercel Deployment:** ```json // vercel.json { "rewrites": [ { "source": "/(.*)", "destination": "/index.html" } ], "headers": [ { "source": "/static/(.*)", "headers": [ { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } ] } ] } ``` ### **Step 8: Production Testing Checklist** **โš ๏ธ MANDATORY PRODUCTION TESTS:** - [ ] **Authentication Flow**: Login/logout works correctly - [ ] **Role-Based Access**: Branch users can't access admin features - [ ] **API Integration**: All 37 endpoints work properly - [ ] **Error Handling**: Graceful error messages for all failure scenarios - [ ] **Loading States**: Loading indicators for all async operations - [ ] **Form Validation**: All forms validate inputs and show errors - [ ] **Responsive Design**: Works on desktop, tablet, and mobile - [ ] **Performance**: Lighthouse score > 90 for all metrics - [ ] **Accessibility**: WCAG 2.1 AA compliance - [ ] **Cross-Browser**: Works on Chrome, Firefox, Safari, Edge - [ ] **Network Errors**: Handles offline/network failure scenarios - [ ] **Memory Leaks**: No memory leaks after navigation - [ ] **Security**: No exposed sensitive data in console/network --- ## ๐Ÿ“š 11. Documentation Summary ### **Available Documentation:** - โœ… **frontend_final.txt** - This complete frontend guide - โœ… **COMPLETE_IMPLEMENTATION_REPORT.md** - Backend completion status - โœ… **data_structure.json** - Full API endpoint documentation - โœ… **setup_database.sql** - Complete database schema - โœ… **README.md** - Setup and deployment instructions ### **Quick Start Commands:** ```bash # PRODUCTION SETUP - COMPLETE WORKFLOW # 1. Create project with all dependencies npm create vite@latest funeral-policy-manager -- --template react-ts cd funeral-policy-manager # 2. Install all production dependencies npm install @tanstack/react-query @tanstack/react-query-devtools react-router-dom react-hook-form @hookform/resolvers zod zustand axios @headlessui/react @heroicons/react recharts clsx tailwind-merge # 3. Install development dependencies npm install -D @types/node @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-plugin-react-hooks eslint-plugin-react-refresh prettier prettier-plugin-tailwindcss tailwindcss postcss autoprefixer vitest @testing-library/react @testing-library/jest-dom jsdom # 4. Initialize configurations npx tailwindcss init -p # 5. Start development npm run dev # 6. Production build and test npm run build npm run preview ``` ### **โš ๏ธ CRITICAL INSTRUCTIONS FOR AI AGENT (COPILOT)** **PRODUCTION CODE MANDATE:** 1. **NO PLACEHOLDER CODE** - Every function must be fully implemented 2. **NO TODO COMMENTS** - All features must be complete 3. **TYPE SAFETY** - All components must use strict TypeScript 4. **ERROR HANDLING** - Every API call must have proper error handling 5. **LOADING STATES** - Every async operation must show loading indicators 6. **ACCESSIBILITY** - All components must be accessible (ARIA labels, keyboard nav) 7. **PERFORMANCE** - Use React.memo, useMemo, useCallback where appropriate 8. **SECURITY** - All user inputs must be validated and sanitized 9. **RESPONSIVE** - All components must work on mobile, tablet, desktop 10. **TESTING** - All critical functions must be testable **IMPLEMENTATION PRIORITY:** 1. **Authentication system** with role-based access 2. **API service layer** with proper error handling 3. **Core pages** (Dashboard, Policies, Claims, Payments) 4. **Form handling** with validation 5. **State management** with Zustand 6. **UI components** with Tailwind CSS 7. **Routing** with protected routes 8. **Error boundaries** and loading states 9. **Performance optimization** 10. **Production build testing** --- ## ๐ŸŽฏ Final Implementation Notes ### **โœ… Production Ready:** - All 37 backend endpoints implemented and tested - Complete database schema with proper indexing - Role-based access control enforced - File upload security implemented - Token-based authentication system - Push notification support ready - QR code functionality operational ### **๐Ÿš€ Ready for Production Development:** - **Single unified application** with role-based interface - **100% TypeScript implementation** with strict typing - **Complete API integration** with all 37 endpoints - **Production-grade architecture** with proper error handling - **Scalable state management** with Zustand - **Comprehensive testing setup** with Vitest - **Optimized build process** with code splitting - **Deployment-ready configuration** for Netlify/Vercel ### **๐Ÿ–ฅ๏ธ Application Features:** - **Unified codebase** - Single app serving both roles - **Role-based dashboards** - Different interfaces for Branch vs Admin - **Advanced reporting** - Comprehensive analytics and insights - **Real-time updates** - Live data with React Query - **Responsive design** - Works on all devices - **Accessibility compliant** - WCAG 2.1 AA standards - **Performance optimized** - Lazy loading and code splitting - **Secure authentication** - JWT token-based auth with role verification The funeral policy management application is now **100% ready** for production development with a complete, secure, and fully functional backend API integration! --- **๐ŸŽฏ FINAL MANDATE FOR AI AGENT:** **YOU MUST BUILD PRODUCTION-READY CODE. NO EXCEPTIONS.** This is not a demo, prototype, or learning project. This is a production business application that will handle real customer data and financial transactions. Every line of code must be: โœ… **Fully functional and tested** โœ… **Type-safe with TypeScript** โœ… **Secure and validated** โœ… **Accessible and responsive** โœ… **Performant and optimized** โœ… **Error-handled and robust** โœ… **Maintainable and documented** **BUILD IT RIGHT THE FIRST TIME.** --- **๐ŸŽ‰ BUILD THE PRODUCTION APPLICATION NOW! ๐ŸŽ‰**