# a7med7c/rafiq architecture

> Architecture diagram of the GitHub repository a7med7c/rafiq, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-04). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/a7med7c/rafiq
- Repository: https://github.com/a7med7c/rafiq

## Overview

#### Purpose and deployable surfaces
Rafiq is a health-management platform for patients and family-managed health profiles: records/documents, medicines and reminders, appointments, emergency contacts, AI chat/voice assistance, notifications, reviews, and administration. It has:
- ASP.NET Core API entry point: `src/Rafiq.API/Program.cs`
- Angular browser client: `RafiqAngular/src/main.ts`
- Capacitor-packaged Angular mobile client: `RafiqMobile/src/main.ts`, with Android host `RafiqMobile/android/app/src/main/java/com/rafiq/app/MainActivity.java`

The Angular and mobile app trees are largely parallel; mobile adds device-oriented services and Capacitor native shells.

#### Backend layering and request boundary
The backend follows clean/CQRS-style separation:
- HTTP controllers expose feature APIs and mediate requests: `src/Rafiq.API/Controllers/AuthController.cs`, `src/Rafiq.API/Controllers/PatientProfilesController.cs`, `src/Rafiq.API/Controllers/AiChatController.cs`.
- Application commands, queries, handlers, validators, DTOs, and cross-cutting pipeline behaviors implement use cases: `src/Rafiq.Application/Features/PatientProfiles`, `src/Rafiq.Application/Features/AiChat`, `src/Rafiq.Application/Common/Behaviors/ValidationBehavior.cs`.
- Domain owns entities, enums, exceptions, and repository contracts: `src/Rafiq.Domain/Entities`, `src/Rafiq.Domain/Repositories`, `src/Rafiq.Domain/Constants/Roles.cs`.
- Infrastructure implements persistence and external integrations: `src/Rafiq.Infrastructure/Persistence/RafiqDbContext.cs`, `src/Rafiq.Infrastructure/DependencyInjection.cs`.

`Program.cs` and service-registration extensions compose these layers; API middleware centralizes exception mapping, user access restrictions, and Hangfire dashboard authorization.

#### Identity, authorization, and profile ownership
Authentication supports registration/login, refresh/revoke token lifecycle, password recovery, phone verification, and Google login. API/client boundaries attach and retain credentials through:
`src/Rafiq.Application/Features/Auth`, `src/Rafiq.Infrastructure/Services/auth/IdentityService.cs`, `RafiqAngular/src/app/Interceptors/auth.interceptor.ts`.

Health data is scoped to a patient health profile rather than simply an account. Family/caregiver sharing is modeled as profile access with invitations, roles, and access requests:
`src/Rafiq.Domain/Entities/User/HealthProfileAccess.cs`,
`src/Rafiq.Application/Features/PatientProfiles`,
`src/Rafiq.Infrastructure/Services/HealthProfileAuthorizationService.cs`.
Client route guards enforce authenticated, guest, and admin navigation states.

#### Clinical-data and scheduling workflows
Feature handlers manage appointments, allergies/chronic diseases, emergency contacts, prescriptions, imaging/lab/general documents, user medicines, and reminder definitions/logs. Key data model boundaries are:
`src/Rafiq.Domain/Entities/Documents`,
`src/Rafiq.Application/Features/MedicineReminders`,
`src/Rafiq.Application/Features/MedicationReminderEngine`.

Uploads are stored through a file-storage abstraction, currently with API-hosted upload directories and a local implementation:
`src/Rafiq.Infrastructure/Services/LocalFileStorageService.cs`,
`src/Rafiq.API/wwwroot/uploads`,
`src/Rafiq.Application/Common/Interfaces/IFileStorageService.cs`.

Medication and appointment changes schedule background work; due reminders can be confirmed, skipped, or snoozed and produce log records.

#### AI document, chat, and voice subsystem
AI is a first-class backend capability with access controls, telemetry, request classification, usage/audit operations, persisted conversations/messages, and health-profile-aware context:
`src/Rafiq.Infrastructure/Services/Ai/InstrumentedAiChatService.cs`,
`src/Rafiq.Application/Features/AiChat/Services/HealthQueryContextBuilder.cs`,
`src/Rafiq.Domain/Entities/Chat/AiConversation.cs`.

Document uploads for prescriptions, labs, imaging, medicine boxes, and general documents are analyzed asynchronously using specialized prompts/DTOs:
`src/Rafiq.Application/AI/Prompts`,
`src/Rafiq.Infrastructure/Services/BackgroundJobs/DocumentAnalysisJob.cs`,
`src/Rafiq.Application/Features/GeneralDocuments/Commands/UploadGeneralDocumentAsync`.

Voice interactions create sessions, process messages through an agent loop, and execute registered domain tools such as booking appointments or managing medicines:
`src/Rafiq.Application/VoiceAgent/Agent/VoiceAgentLoop.cs`,
`src/Rafiq.Application/VoiceAgent/Tools/ToolRegistry.cs`,
`RafiqMobile/src/app/Services/voice-agent.service.ts`.

#### Notifications, jobs, and external services
Hangfire-backed background jobs handle document analysis, chat processing/classification, missed appointments, and medication schedules:
`src/Rafiq.Infrastructure/Services/BackgroundJobs`,
`src/Rafiq.Infrastructure/Services/MedicationReminders/MedicationReminderScheduler.cs`,
`src/Rafiq.API/Middleware/HangfireDashboardAuthorizationFilter.cs`.

Real-time in-app notifications use SignalR hub and connection management:
`src/Rafiq.Infrastructure/Services/Notifications/NotificationHub.cs`,
`src/Rafiq.Infrastructure/Services/Notifications/SignalRNotificationService.cs`,
`RafiqAngular/src/app/Services/signalr.service.ts`.

Named integrations indicate AWS Bedrock for AI, Google token validation, and email/SMS/WhatsApp delivery (including Twilio settings):
`src/Rafiq.Infrastructure/Services/BedrockService.cs`,
`src/Rafiq.Infrastructure/Services/auth/GoogleTokenValidator.cs`,
`src/Rafiq.Infrastructure/Services/Notifications/WhatsAppService.cs`.

#### Client composition
Angular routes bootstrap public/auth/onboarding flows, authenticated health-management pages, AI UI, and a separate admin feature area:
`RafiqAngular/src/app/app.routes.ts`,
`RafiqAngular/src/app/Pages/onboarding`,
`RafiqAngular/src/app/Features/admin/admin.routes.ts`.

Client services form the API-facing boundary and maintain selected profile, token, notification, document-analysis, and localization state:
`RafiqAngular/src/app/Services/profile-selection.service.ts`,
`RafiqAngular/src/app/Services/document-analysis-state.service.ts`,
`RafiqAngular/src/app/i18n/ar.ts`.
The mobile variant additionally provides media-picker/download capabilities and native deployment through Capacitor.

Main entry points: [`src/Rafiq.Application/Features/PatientProfiles`](https://github.com/a7med7c/rafiq/tree/main/src/Rafiq.Application/Features/PatientProfiles) (CQRS application layer), [`src/Rafiq.Infrastructure/Services/MedicationReminders/MedicationReminderScheduler.cs`](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/MedicationReminders/MedicationReminderScheduler.cs) (Hangfire jobs and scheduler), [`src/Rafiq.API/Program.cs`](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.API/Program.cs) (ASP.NET API host), [`RafiqAngular/src/main.ts`](https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/main.ts) (Angular web client)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_clients["Client surfaces"]
  node_web["Angular web client<br/>browser client<br/>[main.ts]"]
  node_mobile["Capacitor mobile client<br/>[main.ts]"]
  node_android["Android native host<br/>Capacitor host<br/>[MainActivity.java]"]
  node_client_auth["Client auth and guards<br/>client boundary"]
  node_client_state["Profile and UI state<br/>client services"]
end

subgraph group_api["API and application"]
  node_api_entry["ASP.NET API host<br/>API composition<br/>[Program.cs]"]
  node_controllers["HTTP controllers<br/>request boundary<br/>[AuthController.cs]"]
  node_application["CQRS application layer<br/>use cases<br/>[PatientProfiles]"]
  node_validation["Validation pipeline<br/>pipeline behavior"]
end

subgraph group_core["Domain and data"]
  node_domain["Domain model and contracts<br/>domain core<br/>[Entities]"]
  node_profile_access["Profile access control<br/>ownership authorization"]
  node_persistence[("Persistence and repositories<br/>infrastructure persistence<br/>[RafiqDbContext.cs]")]
  node_file_storage["Upload storage<br/>file storage"]
end

subgraph group_async["Async and integrations"]
  node_identity["Identity and token service<br/>authentication integration<br/>[IdentityService.cs]"]
  node_jobs["Hangfire jobs and scheduler<br/>background processing"]
  node_document_analysis["Document analysis job<br/>AI pipeline stage"]
  node_ai_chat["AI chat and context<br/>AI application service"]
  node_voice_agent["Voice agent and tools<br/>agent workflow<br/>[VoiceAgentLoop.cs]"]
  node_notifications["SignalR notifications<br/>realtime delivery"]
  node_external_ai{{"AWS Bedrock<br/>external AI provider"}}
  node_messaging{{"Email, SMS, WhatsApp<br/>external messaging<br/>[WhatsAppService.cs]"}}
end

node_web -->|"uses"| node_client_auth
node_mobile -->|"uses"| node_client_auth
node_mobile -->|"packaged by"| node_android
node_client_auth -->|"authenticated API calls"| node_api_entry
node_web -->|"maintains"| node_client_state
node_api_entry -->|"routes requests"| node_controllers
node_controllers -->|"dispatches use cases"| node_application
node_application -->|"validates"| node_validation
node_application -->|"applies domain rules"| node_domain
node_application -->|"authorizes profile scope"| node_profile_access
node_application -->|"reads and writes"| node_persistence
node_application -->|"stores uploads"| node_file_storage
node_api_entry -->|"authenticates"| node_identity
node_application -->|"schedules work"| node_jobs
node_jobs -->|"executes"| node_document_analysis
node_document_analysis -->|"uses AI extraction"| node_ai_chat
node_ai_chat -->|"invokes"| node_external_ai
node_application -->|"serves voice sessions"| node_voice_agent
node_voice_agent -->|"executes domain tools"| node_application
node_jobs -->|"emits reminder events"| node_notifications
node_notifications -->|"pushes realtime events"| node_web
node_jobs -->|"sends delivery messages"| node_messaging

click node_web "https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/main.ts"
click node_mobile "https://github.com/a7med7c/rafiq/blob/main/RafiqMobile/src/main.ts"
click node_android "https://github.com/a7med7c/rafiq/blob/main/RafiqMobile/android/app/src/main/java/com/rafiq/app/MainActivity.java"
click node_client_auth "https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/app/Interceptors/auth.interceptor.ts"
click node_client_state "https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/app/Services/profile-selection.service.ts"
click node_api_entry "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.API/Program.cs"
click node_controllers "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.API/Controllers/AuthController.cs"
click node_application "https://github.com/a7med7c/rafiq/tree/main/src/Rafiq.Application/Features/PatientProfiles"
click node_validation "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Application/Common/Behaviors/ValidationBehavior.cs"
click node_domain "https://github.com/a7med7c/rafiq/tree/main/src/Rafiq.Domain/Entities"
click node_profile_access "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Domain/Entities/User/HealthProfileAccess.cs"
click node_persistence "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Persistence/RafiqDbContext.cs"
click node_identity "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/auth/IdentityService.cs"
click node_file_storage "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/LocalFileStorageService.cs"
click node_jobs "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/MedicationReminders/MedicationReminderScheduler.cs"
click node_document_analysis "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/BackgroundJobs/DocumentAnalysisJob.cs"
click node_ai_chat "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/Ai/InstrumentedAiChatService.cs"
click node_voice_agent "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Application/VoiceAgent/Agent/VoiceAgentLoop.cs"
click node_notifications "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/Notifications/SignalRNotificationService.cs"
click node_messaging "https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/Notifications/WhatsAppService.cs"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_web,node_mobile,node_android,node_client_auth,node_client_state toneBlue
class node_api_entry,node_controllers,node_application,node_validation toneAmber
class node_domain,node_profile_access,node_persistence,node_file_storage toneMint
class node_identity,node_jobs,node_document_analysis,node_ai_chat,node_voice_agent,node_notifications,node_external_ai,node_messaging toneRose
```

## Components

### Client surfaces

- [Angular web client](https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/main.ts): browser client · Health, AI, onboarding, and admin UI. · `RafiqAngular/src/main.ts`
- [Capacitor mobile client](https://github.com/a7med7c/rafiq/blob/main/RafiqMobile/src/main.ts): mobile client · Angular client with device services. · `RafiqMobile/src/main.ts`
- [Android native host](https://github.com/a7med7c/rafiq/blob/main/RafiqMobile/android/app/src/main/java/com/rafiq/app/MainActivity.java): Capacitor host · `RafiqMobile/android/app/src/main/java/com/rafiq/app/MainActivity.java`
- [Client auth and guards](https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/app/Interceptors/auth.interceptor.ts): client boundary · Attaches credentials and restricts routes. · `RafiqAngular/src/app/Interceptors/auth.interceptor.ts`
- [Profile and UI state](https://github.com/a7med7c/rafiq/blob/main/RafiqAngular/src/app/Services/profile-selection.service.ts): client services · Selected profile, analysis, notification, and localization state. · `RafiqAngular/src/app/Services/profile-selection.service.ts`

### API and application

- [ASP.NET API host](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.API/Program.cs): API composition · Composes services, middleware, and dashboard authorization. · `src/Rafiq.API/Program.cs`
- [HTTP controllers](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.API/Controllers/AuthController.cs): request boundary · Feature endpoints for auth, profiles, and AI chat. · `src/Rafiq.API/Controllers/AuthController.cs`
- [CQRS application layer](https://github.com/a7med7c/rafiq/tree/main/src/Rafiq.Application/Features/PatientProfiles): use cases · Commands, queries, handlers, DTOs, and validators. · `src/Rafiq.Application/Features/PatientProfiles`
- [Validation pipeline](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Application/Common/Behaviors/ValidationBehavior.cs): pipeline behavior · `src/Rafiq.Application/Common/Behaviors/ValidationBehavior.cs`

### Domain and data

- [Domain model and contracts](https://github.com/a7med7c/rafiq/tree/main/src/Rafiq.Domain/Entities): domain core · Entities, roles, exceptions, and repository contracts. · `src/Rafiq.Domain/Entities`
- [Profile access control](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Domain/Entities/User/HealthProfileAccess.cs): ownership authorization · Shares health profiles through invitations, roles, and requests. · `src/Rafiq.Domain/Entities/User/HealthProfileAccess.cs`
- [Persistence and repositories](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Persistence/RafiqDbContext.cs): infrastructure persistence · `src/Rafiq.Infrastructure/Persistence/RafiqDbContext.cs`
- [Upload storage](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/LocalFileStorageService.cs): file storage · Local implementation stores API-hosted uploads. · `src/Rafiq.Infrastructure/Services/LocalFileStorageService.cs`

### Async and integrations

- [Identity and token service](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/auth/IdentityService.cs): authentication integration · Account lifecycle and Google validation. · `src/Rafiq.Infrastructure/Services/auth/IdentityService.cs`
- [Hangfire jobs and scheduler](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/MedicationReminders/MedicationReminderScheduler.cs): background processing · Schedules reminders, analysis, chat work, and missed appointments. · `src/Rafiq.Infrastructure/Services/MedicationReminders/MedicationReminderScheduler.cs`
- [Document analysis job](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/BackgroundJobs/DocumentAnalysisJob.cs): AI pipeline stage · Asynchronously analyzes uploaded clinical documents. · `src/Rafiq.Infrastructure/Services/BackgroundJobs/DocumentAnalysisJob.cs`
- [AI chat and context](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/Ai/InstrumentedAiChatService.cs): AI application service · Profile-aware conversations, telemetry, and request classification. · `src/Rafiq.Infrastructure/Services/Ai/InstrumentedAiChatService.cs`
- [Voice agent and tools](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Application/VoiceAgent/Agent/VoiceAgentLoop.cs): agent workflow · Runs voice sessions and invokes registered domain tools. · `src/Rafiq.Application/VoiceAgent/Agent/VoiceAgentLoop.cs`
- [SignalR notifications](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/Notifications/SignalRNotificationService.cs): realtime delivery · Pushes in-app notification events to clients. · `src/Rafiq.Infrastructure/Services/Notifications/SignalRNotificationService.cs`
- **AWS Bedrock**: external AI provider
- [Email, SMS, WhatsApp](https://github.com/a7med7c/rafiq/blob/main/src/Rafiq.Infrastructure/Services/Notifications/WhatsAppService.cs): external messaging · `src/Rafiq.Infrastructure/Services/Notifications/WhatsAppService.cs`

## Connections

- Angular web client → Client auth and guards: uses
- Capacitor mobile client → Client auth and guards: uses
- Capacitor mobile client → Android native host: packaged by
- Client auth and guards → ASP.NET API host: authenticated API calls
- Angular web client → Profile and UI state: maintains
- ASP.NET API host → HTTP controllers: routes requests
- HTTP controllers → CQRS application layer: dispatches use cases
- CQRS application layer → Validation pipeline: validates
- CQRS application layer → Domain model and contracts: applies domain rules
- CQRS application layer → Profile access control: authorizes profile scope
- CQRS application layer → Persistence and repositories: reads and writes
- CQRS application layer → Upload storage: stores uploads
- ASP.NET API host → Identity and token service: authenticates
- CQRS application layer → Hangfire jobs and scheduler: schedules work
- Hangfire jobs and scheduler → Document analysis job: executes
- Document analysis job → AI chat and context: uses AI extraction
- AI chat and context → AWS Bedrock: invokes
- CQRS application layer → Voice agent and tools: serves voice sessions
- Voice agent and tools → CQRS application layer: executes domain tools
- Hangfire jobs and scheduler → SignalR notifications: emits reminder events
- SignalR notifications → Angular web client: pushes realtime events
- Hangfire jobs and scheduler → Email, SMS, WhatsApp: sends delivery messages
