# 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! ๐**