MunDoctor Healthcare Platform Development
Expert AI assistant specialized in building and maintaining the MunDoctor healthcare platform - a comprehensive HIPAA-compliant application connecting patients with healthcare professionals.
Platform Overview
MunDoctor is a multi-role healthcare platform with:
**Frontend**: React 18 + Vite + TypeScript + TailwindCSS + Radix UI**Backend**: Node.js + Express + PostgreSQL**Authentication**: Clerk with role-based access control (RBAC)**Real-time**: Socket.io WebSocket notifications**Payments**: Stripe subscriptions and commission tracking**Compliance**: HIPAA-compliant with 6-year audit retention**Security**: Rate limiting, input validation, audit logging, automated monitoringUser Roles
🩺 Healthcare Professionals
Profile management with licenses and certificationsAppointment scheduling and managementPatient records and treatment plansService offerings and pricingAnalytics dashboard (income, statistics)Professional validation and verificationReview management and responses🏥 Patients
Professional search with filters (specialty, location, rating, availability)Appointment booking with real-time availabilityMedical records managementReview and rating systemFavorites and appointment historyProfile and notification preferences⚙️ Administrators
User management (all roles)Professional credential validationPlatform analytics and monitoringSupport ticket managementContent moderationSubscription and commission oversightSecurity monitoring and audit logsHIPAA compliance managementDevelopment Instructions
1. Healthcare Context Awareness
**Always prioritize:**
Patient privacy and HIPAA complianceSecurity-first approach for all featuresReal-time requirements for appointments and notificationsMulti-role permission checksProper audit logging for sensitive operations**Never:**
Log PHI (Protected Health Information) in application logsBypass authentication or authorization checksCreate files longer than 500 lines (refactor into modules)Implement features without proper input validation2. Architecture & Code Structure
**Frontend (`/src`):**
Feature-based component organizationTypeScript for all new codeTailwind CSS with consistent design systemReact hooks for state managementClerk hooks for authenticationRadix UI for accessible components**Backend (`/backend/src`):**
RESTful API with Express.jsFeature-based route organizationMiddleware for auth, validation, loggingPostgreSQL with connection poolingComprehensive error handlingEnvironment-based configuration**Database (PostgreSQL):**
Core tables: `users`, `patients`, `professionals`Operations: `appointments`, `professional_schedules`, `reviews`Validation: `professional_validations`, `validation_documents`Business: `subscriptions`, `payments`, `support_tickets`Compliance: `audit_logs` (6-year retention), `security_events`3. Security & Compliance Requirements
**Authentication (Clerk):**
Protect all sensitive routes with Clerk middlewareImplement role-based access control (RBAC)Validate JWT tokens on API requestsSync users via Clerk webhooks**Data Protection:**
Encrypt sensitive data at rest and in transitUse Zod schemas for input validationImplement rate limiting on all endpointsAudit log all data access and modifications**HIPAA Compliance:**
6-year audit retention for all medical data operationsSecure file upload for medical documentsNo PHI in application logs or error messagesData retention policies for patient records4. API Development Patterns
**Route Structure:**
```
Public: /api/professionals/search, /api/professionals/:id
Auth Required: /api/appointments, /api/users/profile
Professional Only: /api/professionals/dashboard/stats, /api/services
Admin Only: /api/admin/users, /api/admin/validation/:id/status
```
**Standard Response Format:**
Success: `{ success: true, data: {...} }`Error: `{ success: false, error: "message" }` (no PHI in errors)Pagination: Include `total`, `page`, `limit` metadata**Error Handling:**
Use proper HTTP status codes (400, 401, 403, 404, 500)Generic error messages to usersDetailed errors logged server-side onlyAudit log security-relevant failures5. Healthcare-Specific Features
**Appointment Management:**
Real-time availability checking with conflict resolutionStatus workflow: Pending → Confirmed/Rejected → Completed/CancelledAudit trail in `appointment_history` tableWebSocket notifications for status changesEmail/SMS reminders via Nodemailer/Twilio**Professional Validation:**
Document upload workflow for licenses and certificationsMulti-step approval: Pending → Under Review → Approved/RejectedAdmin review interface with batch processingReal-time status notificationsSecure document storage with encryption**Review & Rating System:**
Patient reviews with moderationRating calculations with caching in `professional_rating_summaries`Content moderation and abuse reportingProfessional response capability**Payment Processing:**
Stripe integration for subscriptions (Free, Basic, Premium, Enterprise)Commission tracking (platform takes percentage of appointments)Automated billing and invoice generationDispute handling and refund management6. Real-time Features (Socket.io)
**Implement WebSocket events for:**
Live appointment updates and confirmationsDashboard notifications (new appointments, reviews, messages)Professional availability changesAdmin alerts (validation requests, support tickets)Security events and system notifications**Event naming convention:**
`appointment:created`, `appointment:updated`, `appointment:cancelled``notification:new`, `notification:read``validation:submitted`, `validation:approved`7. Testing & Quality Standards
**Required for all new code:**
Unit tests for business logicIntegration tests for API endpointsE2E tests for critical user flows (appointment booking, payment processing)Security testing for auth/authzTypeScript type checking with no `any` typesESLint and Prettier compliance8. Performance Optimization
**Implement:**
Redis caching for frequently accessed data (professional listings, reviews)Database query optimization with proper indexingImage optimization for profile pictures and documentsAPI rate limiting to prevent abuseConnection pooling for PostgreSQLLazy loading for frontend components9. Third-Party Integrations
**Clerk (Authentication):**
JWT token validation middlewareRole synchronization via webhooksUser metadata for role-specific data**Stripe (Payments):**
Webhook handling for subscription eventsSecure payment intent creationCommission calculation logic**Twilio (SMS):**
Appointment remindersEmergency notificationsVerification codes**Nodemailer (Email):**
Appointment confirmations and remindersValidation status updatesSupport ticket responses10. AI Assistant Workflow
**When receiving a task:**
1. **Understand healthcare context** - Consider patient privacy, compliance, and security implications
2. **Check existing patterns** - Review similar implementations in the codebase
3. **Ask clarifying questions** - Verify requirements, especially for healthcare-specific features
4. **Plan implementation** - Consider all three roles (Patient, Professional, Admin) if applicable
5. **Implement with quality** - Follow TypeScript patterns, add validation, include error handling
6. **Add tests** - Unit and integration tests for new functionality
7. **Document changes** - Update comments and type definitions
8. **Verify compliance** - Ensure HIPAA compliance and audit logging
**Code quality checklist:**
[ ] TypeScript types defined (no `any`)[ ] Input validation with Zod schemas[ ] Authentication and authorization checks[ ] Audit logging for sensitive operations[ ] Error handling with proper status codes[ ] No PHI in logs or error messages[ ] Tests written and passing[ ] Performance considerations addressedKey Files & Locations
**Frontend:**
`/src/pages/` - Role-based dashboards`/src/components/` - Reusable UI components`/src/hooks/` - Custom React hooks`/src/services/` - API communication`/src/types/` - TypeScript definitions**Backend:**
`/backend/src/routes/` - API endpoints`/backend/src/services/` - Business logic`/backend/src/middleware/` - Auth, validation, logging`/backend/src/models/` - Database schemas**Configuration:**
`/backend/.env` - Environment variables`/backend/src/config/` - Application configuration`/docker-compose.yml` - Local development setupConstraints & Important Notes
**File size limit**: Never create files longer than 500 lines - refactor into modules**Security first**: All features must implement proper authentication and authorization**HIPAA mandatory**: All code must maintain privacy and security standards**Real-time critical**: Appointments and notifications require WebSocket implementation**Multi-role design**: Consider all three user roles when implementing features**Node.js 20**: Use modern ES modules and async/await patterns**No PHI exposure**: Never log, display, or transmit PHI insecurelyExample Usage
**Task: "Add appointment cancellation with reason tracking"**
AI will:
1. Review existing appointment schema and status workflow
2. Add `cancellation_reason` field to `appointments` table
3. Update API endpoint with validation for cancellation reasons
4. Implement audit logging in `appointment_history`
5. Add WebSocket notification for real-time updates
6. Update frontend UI with cancellation modal
7. Send email/SMS notification to affected parties
8. Write integration tests for cancellation flow
9. Verify HIPAA compliance for data retention