AndroidCareProvider - Structure Analysis¶
Repository: AndroidCareProvider
Platform: Android (Java + Kotlin)
Analysis Date: November 2025
Audit Version: 1.0
Table of Contents¶
- Executive Summary
- High-Level Architecture
- Package Structure Analysis
- Component Inventory
- Navigation Architecture
- Data Flow Patterns
- Key Business Logic Flows
- Integration Points
- Code Organization Assessment
- Architectural Patterns
Executive Summary¶
The AndroidCareProvider application is a comprehensive mental health telemedicine platform for healthcare providers with 350+ Java classes and growing Kotlin adoption. The codebase demonstrates a hybrid architecture transitioning from traditional Android patterns to modern Jetpack components.
Key Metrics¶
| Metric | Count | Notes |
|---|---|---|
| Total Activities | 84+ | Mix of Java and Kotlin |
| Total Fragments | 60+ | Primary UI components |
| Main Packages | 11 | CareProvider, Client, CommonUser, etc. |
| Navigation Graphs | 8 | Jetpack Navigation |
| Primary Language | Java (85%) | Kotlin growing (15%) |
| Architecture | Hybrid | MVC → MVVM transition |
| Min SDK | 21 | Android 5.0 Lollipop |
| Target SDK | 33 | Android 13 |
Architectural Highlights¶
✅ Strengths:
- Clear package separation by feature domain
- Modern bottom navigation with Jetpack Navigation
- Centralized utility and configuration management
- Robust Firebase and WebSocket integration
- Comprehensive feature coverage
⚠️ Areas for Improvement:
- Inconsistent architectural patterns (MVC vs MVVM)
- Code duplication between Care Provider and Client packages
- Direct API calls in UI layer (no repository pattern)
- Mixed language usage (Java/Kotlin) without clear strategy
- Large Activity/Fragment classes (some >2000 LOC)
High-Level Architecture¶
System Context Diagram¶
┌──────────────────────────────────────────────────────────────┐
│ External Systems │
├──────────────────────────────────────────────────────────────┤
│ • Firebase (FCM, Crashlytics, Auth) │
│ • PsyterAPI (REST Backend) │
│ • NodeServer (WebSocket) │
│ • VideoSDK (Video Calls) │
│ • Payment Gateway (Web redirect) │
│ • MediaAPI (File uploads) │
└──────────────────────────────────────────────────────────────┘
↑
│ HTTPS/WSS/FCM
↓
┌──────────────────────────────────────────────────────────────┐
│ AndroidCareProvider Application │
├──────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Presentation │ │ Navigation │ │ Workers │ │
│ │ Layer │ │ (Jetpack) │ │ (WorkManager)│ │
│ │ Activities/ │ │ │ │ │ │
│ │ Fragments │ │ TabManager │ │ Background │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ ┌──────▼─────────────────▼─────────────────▼───────┐ │
│ │ Business Logic Layer │ │
│ │ • Adapters (RecyclerView) │ │
│ │ • DataModels (DTOs) │ │
│ │ • Event Bus (MessageObservable) │ │
│ └──────────────────┬────────────────────────────────┘ │
│ │ │
│ ┌──────────────────▼────────────────────────────────┐ │
│ │ Network & Data Layer │ │
│ │ • Fast Android Networking │ │
│ │ • WebSocket (nv-websocket-client) │ │
│ │ • SharedPreferences │ │
│ │ • Glide (Image caching) │ │
│ └───────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
Application Flow¶
App Launch
↓
SplashActivity
↓
Check Auth Status (SharedPreferences)
↓
├─→ [Logged Out] → LoginActivity → UserSelectionActivity → RegisterCareProviderActivity
│ ↓
└─→ [Logged In] ──────────────────────────────────────→ BaseClientActivityMain
↓
[Bottom Navigation - 5 Tabs]
↓
┌────────────────────────┬────────────────────────┬───────────────┬───────────────┐
↓ ↓ ↓ ↓ ↓
HomeFragment AppointmentsFragment MyQyestionaireFragment HomeworksFragment MoreTabFragment
↓
OneToOneCallActivity (Video SDK)
ChatMainActivity (Messaging)
ClientHistoryActivity (Patient History)
Package Structure Analysis¶
Root Package: com.psyter.www¶
com.psyter.www/
├── MainApplication.java # Application entry point
├── MyFirebaseMessagingService.java # FCM push notification handler
├── MyFirebaseInstanceIdService.java # FCM token management
├── MessageObservable.java # Event bus for cross-component messaging
├── CustomOnClickListener.java # Custom click handler
├── OnClickPrescriptionList.java # Prescription callback
│
├── CareProvider/ # 🏥 CARE PROVIDER FEATURES (Primary)
│ ├── Activities/ # 21 Activities
│ ├── Fragments/ # 35+ Fragments
│ ├── Adapters/ # RecyclerView adapters
│ ├── DataModels/ # POJOs / DTOs
│ ├── Schedule/ # Scheduling logic
│ └── WorkCancelReceiver.java # Background work cancellation
│
├── Client/ # 👤 CLIENT/PATIENT FEATURES (Shared code)
│ ├── Activities/ # Payment, Diary, PDFs, etc.
│ ├── Fragments/ # Client fragments
│ ├── Adapters/ # Client adapters
│ └── BookSlots/ # Appointment booking
│
├── CommonUser/ # 🔗 SHARED USER FEATURES
│ ├── Activities/ # Auth, Search, Profile
│ ├── Fragments/ # Shared fragments
│ └── Adapters/ # Shared adapters
│
├── Registration/ # 🔐 AUTHENTICATION & ONBOARDING
│ └── Activities/
│ ├── SplashActivity # Launcher activity
│ ├── LoginActivity # Login screen
│ ├── RegisterCareProviderActivity # Provider signup
│ ├── UserSelectionActivity # User type selection
│ ├── VerifyAccountActivity # Email verification
│ └── QuestionaireActivity # Initial assessment
│
├── Collaboration/ # 📹 VIDEO CALLING & WEBRTC
│ ├── Presence/
│ │ ├── CollaborationMain # Legacy WebRTC (deprecated)
│ │ ├── IncomingCall # Incoming call UI
│ │ └── FloatingViewService # Picture-in-picture
│ ├── Common/ # Bluetooth & audio helpers
│ └── NetWorkDetectionHelpers/ # Connectivity monitoring
│
├── Scheduling/ # 📅 APPOINTMENT SCHEDULING
│ ├── WeeklySchedule/
│ │ └── WeeklyScheduleFragment # Weekly calendar view
│ └── Services/
│ └── GetSlotsService # Background slot sync
│
├── Stats/ # 🛠️ UTILITIES & HELPERS
│ ├── Utils.java # Global utilities
│ ├── MySharedPreferences.java # Preferences wrapper
│ ├── LocaleUtils.java # Localization (AR/EN)
│ ├── LangHelper.java # Language switching
│ ├── TransparentProgressDialog # Loading dialogs
│ └── WeekDisplayActivity # Week picker
│
├── navigation/ # 🧭 NAVIGATION (Kotlin)
│ └── TabManager.kt # Bottom nav controller management
│
├── bottomnavbar/ # 📱 CUSTOM BOTTOM NAV
│ └── [Custom navigation component]
│
├── views/ # 🎨 CUSTOM VIEWS & NEWER FEATURES
│ ├── activity/
│ │ ├── AddPrescriptionActivity.kt # Prescription UI (Kotlin)
│ │ ├── RegisterActivity.kt # Registration flow (Kotlin)
│ │ └── OnboardingActivity.kt # First-run (Kotlin)
│ └── fragments/
│ └── [Onboarding fragments]
│
├── workers/ # ⚙️ BACKGROUND WORK (WorkManager)
│ └── [Background sync tasks]
│
└── BranchEvents/ # 🔗 DEEP LINKING
└── [Branch.io integration]
Package Responsibilities¶
| Package | Lines of Code (est.) | Primary Purpose | Key Classes |
|---|---|---|---|
| CareProvider/ | ~40,000 | Provider-specific features | Activities: 21, Fragments: 35+ |
| Client/ | ~15,000 | Patient features (shared with patient app) | BookSlots, Payment, Diary |
| CommonUser/ | ~8,000 | Shared user features | CarePListActivity, Auth |
| Registration/ | ~5,000 | Authentication flows | SplashActivity, LoginActivity |
| Collaboration/ | ~12,000 | Video calls | OneToOneCallActivity (new), CollaborationMain (old) |
| Scheduling/ | ~6,000 | Calendar & slots | WeeklyScheduleFragment |
| Stats/ | ~3,000 | Utilities | Utils, MySharedPreferences |
| navigation/ | ~500 | Tab management | TabManager.kt (Kotlin) |
| views/ | ~4,000 | Modern Kotlin UI | AddPrescriptionActivity.kt |
| workers/ | ~1,500 | Background tasks | WorkManager jobs |
Component Inventory¶
1. Activities (84 total)¶
Care Provider Activities (21)¶
| Activity | Purpose | Complexity | Language |
|---|---|---|---|
BaseClientActivityMain |
Main container with bottom nav (new) | High | Java |
BaseCarePActivityMain |
Legacy main container (deprecated) | High | Java |
OneToOneCallActivity |
Video call UI (VideoSDK) | Very High | Kotlin |
CreateOrJoinActivity |
Video meeting entry | Medium | Kotlin |
ChatMainActivity |
Messaging list | Medium | Java |
ConversationActivity |
Chat conversation | High | Java |
CPHistoryActivity |
Provider session history | Medium | Java |
ClientHistoryActivity |
Patient history timeline | High | Java |
InitialAssessmentAcitivity |
Create assessments | High | Java |
InitialAssessmentViewAcitivity |
View assessment templates | Medium | Java |
FilledAssessmentViewActivity |
Patient assessment responses | Medium | Java |
NewHomeWorkActivity |
Assign homework | High | Java |
HomeWorkCheckActivity |
Review homework submissions | Medium | Java |
HomeworkFeedbackHistoryActivity |
Homework history | Low | Java |
PrescriptionActivity |
Prescription management | High | Java |
PaymentsDetailActivity |
Payment history | Medium | Java |
ReferralActivity |
Patient referrals | Low | Java |
ReserveSlotActivity |
Reserve appointment slots | Medium | Java |
MarkAvailabiltyActivity |
Set schedule availability | High | Java |
AddPromoCodeActivity |
Promo code management | Low | Java |
CarePListingFiltersActivity |
Filter care providers | Medium | Java |
Shared/Common Activities (30+)¶
| Activity | Purpose | Package |
|---|---|---|
SplashActivity |
App launcher | Registration |
LoginActivity |
User login | Registration |
RegisterCareProviderActivity |
Provider signup | Registration |
UserSelectionActivity |
Select user type | Registration |
VerifyAccountActivity |
Email verification | Registration |
QuestionaireActivity |
Initial assessment | Registration |
ForgotPasswordActivity |
Password reset | CommonUser |
ResetPasswordActivity |
Set new password | CommonUser |
VerifyEmailActivity |
Email confirmation | CommonUser |
CarePListActivity |
Search providers | CommonUser |
CarePDetailActivity |
Provider profile | CommonUser |
ScheduleSessionActivity |
Schedule appointment | CommonUser |
LoginRegisterActivity |
Auth switcher | CommonUser |
RateCareProviderActivity |
Rate provider | CommonUser |
MedicalSourcesActivity |
Educational resources | CommonUser |
PaymentWebActivity |
Payment processing (WebView) | Client |
AddWalletAmountWebActivity |
Wallet top-up (WebView) | Client |
PDFviewerActivity |
PDF viewer | Client |
ViewDocWebActivity |
Document viewer | Client |
HomeWrokSubmitActivity |
Submit homework | Client |
BookSlotActivity |
Book appointment | Client/Fragments |
SelectSlotActivity |
Select time slot | Client/BookSlots |
SlotPaymentSuggestActivity |
Payment suggestions | Client/BookSlots |
BookingConfirmation1Activity |
Booking confirmation | Client/BookSlots |
AddUpdateDiaryActivity |
Manage diary | Client |
NotificationsActivity |
Notification list | Client |
BlogsActivity |
Blog listing | Client |
BlogDetailsActivity |
Blog details | Client |
Modern Kotlin Activities (5+)¶
| Activity | Purpose | Notes |
|---|---|---|
AddPrescriptionActivity.kt |
Digital prescription | Navigation component |
RegisterActivity.kt |
Registration flow | Modern UI |
OnboardingActivity.kt |
First-run experience | ViewPager2 |
AppointmentBookingSuccessActivity.kt |
Success screen | Material Design |
SampleCustomActivity.kt |
Demo/test activity | Development |
2. Fragments (60+)¶
Care Provider Fragments (35+)¶
| Fragment | Tab/Section | Purpose |
|---|---|---|
| Main Navigation | ||
HomeFragment |
Home Tab | Dashboard |
AppointmentsFragment |
Appointments Tab | Appointment list |
MyQyestionaireFragment |
Assessment Tab | Assessment list |
HomeworksFragment |
Homework Tab | Homework list |
MoreTabFragment |
More Tab | Settings & more |
| Profile Management | ||
MyProfileCarePFragment |
Profile | Provider profile |
PersonalInfoFragment |
Profile | Personal info |
ContactInfoFragment |
Profile | Contact details |
EducationInfoFragment |
Profile | Education/credentials |
VideoBioFragment |
Profile | Video bio |
CurrentJobFragment |
Profile | Employment info |
PaymentInfoFragment |
Profile | Payment settings |
PaymentMethodFragment |
Profile | Payment methods |
SaudiCommesionFragment |
Profile | Saudi Commission docs |
| Appointments | ||
MyAppointCarePFragment |
Appointments | Provider appointments |
MyAppointFragment |
Appointments | Alternative view |
ReservationCarePFragment |
Appointments | Reservations |
ReservationFragment |
Appointments | Alternative reservations |
| Schedule | ||
MonthViewFragment |
Schedule | Month calendar |
ManageSessionDurationFragment |
Schedule | Session duration |
| Prescription | ||
PrescriptionListFragment |
Prescription | Prescription list |
PrescriptionCPAddFragment |
Prescription | Add prescription (CP) |
PrescriptionClientAddFragment |
Prescription | Add prescription (Client) |
| Settings | ||
ManageServicesFragment |
Settings | Service management |
ManageAccessFragment |
Settings | Access control |
MyPreferFragment |
Settings | Preferences |
PromoCodeFragment |
Settings | Promo codes |
PrivacyPolicyFragment |
Settings | Privacy policy |
WebviewFragment |
Settings | Web content |
| Clients | ||
MyClientsFragment |
Clients | Client list |
| Other | ||
MedicalSourceFragment |
Resources | Medical resources |
MainFragment |
Legacy | Deprecated main |
Client/Shared Fragments (25+)¶
| Fragment | Purpose | Package |
|---|---|---|
FindCPFragment |
Find care providers | Client |
MyCPFragment |
My providers | Client |
QuestionnaireFragment |
Fill assessment | Client |
MyHomeWorkFragment |
View homework | Client |
MyDiaryFragment |
Diary entries | Client |
WalletBalanceFragment |
Wallet balance | Client |
ReferralsFragment |
Referral list | Client |
FAQFragment |
FAQ | Client |
ContactUsFragment |
Contact support | Client |
OurStoryFragment |
About app | Client |
DisordersFragment |
Mental disorders info | Client |
MainFragmentClient |
Client dashboard | Client |
MyProfileFragmentClient |
Client profile | Client |
PreferencesListFragment |
Preferences dialog | Client |
ToogleTherapyDialog |
Therapy toggle | Client |
RefundChoiceDialog |
Refund options | Client |
RamadanOfferDialog |
Promotional dialog | Client |
MyQyestionaireFragmentRedirect |
Assessment redirect | Client |
Scheduling Fragments¶
| Fragment | Purpose |
|---|---|
WeeklyScheduleFragment |
Weekly schedule view |
MonthViewFragment |
Monthly calendar |
Onboarding Fragments (Kotlin)¶
| Fragment | Purpose |
|---|---|
OnboardingFragmentA |
Onboarding page 1 |
OnboardingFragmentB |
Onboarding page 2 |
OnboardingFragmentC |
Onboarding page 3 |
3. Adapters (50+)¶
Purpose: RecyclerView data binding and view management
| Adapter | Data Type | Location |
|---|---|---|
MyAppointmentsCarePAdapter |
Appointments | CareProvider/Adapters |
ConversationListAdapter |
Chat conversations | CareProvider/Adapters |
MyClientsAdapter |
Client list | CareProvider/Adapters |
PrescriptionAdapter |
Prescriptions | CareProvider/Adapters |
HomeworkAdapter |
Homework | CareProvider/Adapters |
CPTitleAdapter |
Professional titles | CareProvider/Adapters |
CareProvidersListAdapter |
Provider search | CommonUser/Adapters |
DiaryAdapter |
Diary entries | Client/Adapters |
NotificationAdapter |
Notifications | Client/Adapters |
4. Data Models (100+)¶
Purpose: POJOs for API request/response mapping
| Package | Model Examples |
|---|---|
CareProvider/DataModels/ |
AppointmentHeaderModel, ConversationListModel, DialogType, HwDocDataModel, CPTitleModel |
Client/DataModels/ |
DiaryModel, BookingModel, WalletModel |
CommonUser/DataModels/ |
UserModel, CareProviderModel, RatingModel |
Navigation Architecture¶
Bottom Navigation Structure (Jetpack Navigation)¶
Implementation: navigation/TabManager.kt (Kotlin)
// 5 Tabs with dedicated NavControllers
┌─────────────────────────────────────────────────────────┐
│ BaseClientActivityMain (Main Container) │
├─────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┬──────────┬──────────┬──────────┬────────┐│
│ │ Home │ Appts │ Tests │Homework │ More ││
│ └────┬─────┴────┬─────┴────┬─────┴────┬─────┴───┬────┘│
│ │ │ │ │ │ │
│ ┌────▼────┬─────▼────┬─────▼────┬─────▼────┬────▼───┐│
│ │ nav_home│nav_appts │nav_assess│nav_hw │nav_more││
│ │ .xml │ .xml │ .xml │ .xml │ .xml ││
│ └─────────┴──────────┴──────────┴──────────┴────────┘│
└─────────────────────────────────────────────────────────┘
Navigation Graphs¶
| Graph File | Start Destination | Fragments |
|---|---|---|
nav_home.xml |
homeFragment |
Home, Chat List, Profile |
nav_appointments.xml |
appointmentsFragment |
Appointments, Appointment Details |
nav_assessment.xml |
myQyestionaireFragment |
Assessment List, Create, View |
nav_homeworks.xml |
homeworksFragment |
Homework List, Assign, Review |
nav_more.xml |
moreTabFragment |
Settings, About, Help |
nav_graph_prescription.xml |
- | Prescription flows |
register_nav_graph.xml |
- | Registration flow |
Tab Switching Logic¶
// navigation/TabManager.kt
fun switchTab(tabId: Int) {
currentController = when (tabId) {
R.id.navigation_home -> navHomeController
R.id.navigation_appointments -> navAppointmentsController
R.id.navigation_assessment -> navAssessmentController
R.id.navigation_homeworks -> navHomeworksController
R.id.navigation_more -> navMoreController
else -> navHomeController
}
tabHistory.push(tabId)
showTab(tabId)
}
Back Stack Management: Custom tab history for back button navigation.
Data Flow Patterns¶
1. API Call Pattern (Current)¶
┌─────────────────┐
│ Activity/ │
│ Fragment │
└────────┬────────┘
│ 1. User action
↓
┌─────────────────┐
│ Fast Android │
│ Networking │ 2. HTTP Request
│ (Direct call) │ .addHeaders("Authorization", "Bearer " + token)
└────────┬────────┘
│
↓
┌─────────────────┐
│ Backend API │ 3. JSON Response
└────────┬────────┘
│
↓
┌─────────────────┐
│ JSONObject │ 4. Manual parsing
│ Response │ response.getJSONObject("data")
└────────┬────────┘
│
↓
┌─────────────────┐
│ Update UI │ 5. adapter.notifyDataSetChanged()
└─────────────────┘
Example:
// Direct API call in Fragment
AndroidNetworking.get(Utils.BaseURL + "api/CareProvider/GetAppointments")
.addHeaders("Authorization", "Bearer " + mpref.GetUserToken())
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// Parse and update UI directly
appointmentList.clear();
JSONArray data = response.getJSONArray("data");
// ... manual parsing
adapter.notifyDataSetChanged();
}
@Override
public void onError(ANError error) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
});
Issues:
- ❌ No separation of concerns
- ❌ No caching layer
- ❌ Difficult to test
- ❌ Code duplication across components
2. WebSocket Communication Pattern¶
┌──────────────────┐
│ Activities │
│ (Video call, │
│ Chat) │
└────────┬─────────┘
│ 1. Connect WebSocket
↓
┌──────────────────┐
│ WebSocketClient │ 2. Send command (JSON)
│ (nv-websocket) │ { "command": "JOIN_CALL", "meetingId": "..." }
└────────┬─────────┘
│
↓
┌──────────────────┐
│ NodeServer │ 3. Process & broadcast
└────────┬─────────┘
│
↓
┌──────────────────┐
│ WebSocket │ 4. Receive message
│ onMessageReceived│
└────────┬─────────┘
│
↓
┌──────────────────┐
│ MessageObservable│ 5. Notify observers
│ (Event Bus) │ messageObservable.notify(message)
└────────┬─────────┘
│
↓
┌──────────────────┐
│ Update UI │ 6. Handle in Activity
└──────────────────┘
3. Firebase Push Notification Flow¶
┌──────────────────┐
│ Backend API │ 1. Trigger event (new message, appointment)
└────────┬─────────┘
│
↓
┌──────────────────┐
│ Firebase FCM │ 2. Send push notification
└────────┬─────────┘
│
↓
┌──────────────────┐
│ MyFirebase │ 3. Receive notification
│ MessagingService │ onMessageReceived(RemoteMessage)
└────────┬─────────┘
│
↓
┌──────────────────┐
│ Parse payload │ 4. Extract notificationType, data
│ & route │
└────────┬─────────┘
│
├──→ Type 1: Open ChatMainActivity
├──→ Type 2: Open MyAppointCarePFragment
├──→ Type 3: Open OneToOneCallActivity
└──→ Type 4: Open MyQyestionaireFragment
4. Event Bus Pattern (MessageObservable)¶
// MessageObservable.java (Observer Pattern)
public class MessageObservable extends Observable {
private static MessageObservable instance;
public static MessageObservable getInstance() {
if (instance == null) instance = new MessageObservable();
return instance;
}
public void updateValue(Object data) {
setChanged();
notifyObservers(data);
}
}
// Fragment observes changes
MessageObservable.getInstance().addObserver(this);
@Override
public void update(Observable o, Object arg) {
// Handle message
if (arg instanceof NewMessageModel) {
refreshChatList();
}
}
Used for:
- New messages
- Appointment updates
- Call state changes
- Profile updates
Key Business Logic Flows¶
1. Video Call Flow (VideoSDK)¶
┌─────────────────────────────────────────────────────────────┐
│ VIDEO CALL SEQUENCE │
└─────────────────────────────────────────────────────────────┘
1. Appointment scheduled
└─→ Backend creates meeting ID (VideoSDK API)
2. Call time arrives
└─→ FCM notification sent to patient & provider
Payload: { "notificationType": 3, "meetingId": "xxx", ... }
3. User taps notification
└─→ Opens OneToOneCallActivity.kt
4. Initialize VideoSDK
└─→ VideoSDK.initialize(context)
└─→ VideoSDK.initMeeting(
context,
meetingId,
participantName,
micEnabled = true,
webcamEnabled = true,
...
)
5. Join meeting
└─→ meeting.join()
└─→ WebRTC connection established
└─→ onMeetingJoined() callback
6. Remote participant joins
└─→ onParticipantJoined(participant)
└─→ Setup remote video view
└─→ participant.onStreamEnabled() → render video
7. During call
├─→ meeting.muteMic() / unmuteMic()
├─→ meeting.disableWebcam() / enableWebcam()
├─→ meeting.changeWebcam() (switch camera)
└─→ meeting.enableScreenShare()
8. End call
└─→ meeting.leave()
└─→ onMeetingLeft() callback
└─→ finish() activity
└─→ Backend API: UpdateAppointmentStatus("Completed")
2. Appointment Booking Flow¶
┌─────────────────────────────────────────────────────────────┐
│ APPOINTMENT BOOKING SEQUENCE │
└─────────────────────────────────────────────────────────────┘
[Patient Side - Shared code in Client package]
1. FindCPFragment
└─→ Search care providers
└─→ API: GET /api/CareProvider/Search
Filters: specialty, availability, rating
2. CarePDetailActivity
└─→ View provider profile
└─→ API: GET /api/CareProvider/GetProfile?id=xxx
3. ScheduleSessionActivity
└─→ Select appointment type
└─→ Navigate to WeeklyScheduleFragment
4. WeeklyScheduleFragment
└─→ API: GET /api/CareProvider/GetAvailableSlots?date=xxx
└─→ Display available slots
└─→ User selects slot
5. SelectSlotActivity
└─→ Confirm slot selection
└─→ Choose payment method
6. SlotPaymentSuggestActivity
└─→ Show payment options:
├─→ Wallet
├─→ Credit card (redirect to PaymentWebActivity)
└─→ Insurance
7. PaymentWebActivity (WebView)
└─→ Load payment gateway URL
└─→ Process payment
└─→ Return with payment status
8. BookingConfirmation1Activity
└─→ API: POST /api/Appointment/CreateAppointment
{ careProviderId, slotId, paymentId, ... }
└─→ Show confirmation
└─→ Send FCM notification to provider
[Provider Side]
9. FCM notification received (MyFirebaseMessagingService)
└─→ Type 2: New appointment
└─→ Update badge count
10. MyAppointCarePFragment
└─→ Refresh appointment list
└─→ API: GET /api/CareProvider/GetAppointments
└─→ New appointment appears
3. Assessment Creation & Assignment Flow¶
┌─────────────────────────────────────────────────────────────┐
│ ASSESSMENT MANAGEMENT SEQUENCE │
└─────────────────────────────────────────────────────────────┘
[Provider Creates Assessment]
1. InitialAssessmentAcitivity
└─→ Select assessment template
API: GET /api/Assessment/GetTemplates
└─→ Customize questions
└─→ Add/remove questions
└─→ Set scoring logic
2. Save assessment
└─→ API: POST /api/Assessment/CreateTemplate
{ name, questions: [...], ... }
3. Assign to patient
└─→ From ClientHistoryActivity
└─→ Select patient
└─→ Select assessment
└─→ API: POST /api/Assessment/AssignToPatient
{ patientId, assessmentId, dueDate, ... }
└─→ FCM notification to patient
[Patient Completes Assessment]
4. Patient receives notification
└─→ Opens MyQyestionaireFragment
└─→ API: GET /api/Assessment/GetAssigned
└─→ List of pending assessments
5. Start assessment
└─→ QuestionnaireFragment
└─→ Display questions one by one
└─→ Collect responses
6. Submit assessment
└─→ API: POST /api/Assessment/Submit
{ assessmentId, responses: [...], ... }
└─→ FCM notification to provider
[Provider Reviews Response]
7. Provider receives notification
└─→ Opens MyQyestionaireFragment
└─→ API: GET /api/Assessment/GetCompleted
8. View patient response
└─→ FilledAssessmentViewActivity
└─→ API: GET /api/Assessment/GetResponse?id=xxx
└─→ Display answers with scoring
└─→ Provider adds feedback
9. Save feedback
└─→ API: POST /api/Assessment/SubmitFeedback
{ assessmentId, patientId, feedback, ... }
4. Messaging Flow¶
┌─────────────────────────────────────────────────────────────┐
│ MESSAGING SEQUENCE │
└─────────────────────────────────────────────────────────────┘
1. Open conversations list
└─→ ChatMainActivity
└─→ API: GET /api/Messaging/GetConversations
└─→ Display list (ConversationListAdapter)
2. Select conversation
└─→ ConversationActivity
└─→ API: GET /api/Messaging/GetMessages?conversationId=xxx
└─→ Display messages (RecyclerView)
3. Send message
└─→ User types message
└─→ API: POST /api/Messaging/SendMessage
{ conversationId, message, type: "text", ... }
└─→ Optimistically add to UI
└─→ Backend sends FCM to recipient
4. Receive message (real-time)
└─→ MyFirebaseMessagingService
└─→ Type 1: New message
└─→ If ConversationActivity open for this conversation:
└─→ MessageObservable.notify(message)
└─→ ConversationActivity.update() → append message
└─→ Else:
└─→ Show notification
└─→ Update badge count
5. Send attachment
└─→ Select image/file
└─→ Upload to MediaAPI first
POST /api/Media/Upload
└─→ Get file URL
└─→ Send message with attachment URL
POST /api/Messaging/SendMessage
{ message: "Photo", type: "image", attachmentUrl: "..." }
6. Mark as read
└─→ onResume() in ConversationActivity
└─→ API: POST /api/Messaging/MarkAsRead
{ conversationId, ... }
└─→ Clear notification
5. Schedule Management Flow¶
┌─────────────────────────────────────────────────────────────┐
│ SCHEDULE MANAGEMENT SEQUENCE │
└─────────────────────────────────────────────────────────────┘
1. View current schedule
└─→ MarkAvailabiltyActivity
└─→ API: GET /api/CareProvider/GetSchedule
└─→ Display weekly availability
2. Set recurring availability
└─→ Select day (e.g., Monday)
└─→ Add time slot (9:00 AM - 5:00 PM)
└─→ Set session duration (30/45/60 min)
└─→ API: POST /api/CareProvider/SetRecurringAvailability
{ dayOfWeek: 1, startTime: "09:00", endTime: "17:00", sessionDuration: 45, ... }
3. Block specific dates
└─→ Select date (e.g., vacation)
└─→ API: POST /api/CareProvider/BlockDate
{ date: "2025-12-25", reason: "Holiday", ... }
4. Override availability
└─→ For specific date, change hours
└─→ API: POST /api/CareProvider/SetCustomAvailability
{ date: "2025-11-15", startTime: "10:00", endTime: "14:00", ... }
5. Availability affects booking
└─→ WeeklyScheduleFragment (patient side)
└─→ API: GET /api/CareProvider/GetAvailableSlots?providerId=xxx&date=yyy
└─→ Only shows available slots based on provider schedule
Integration Points¶
1. Backend API Integration¶
Base URL Configuration: Stats/Utils.java
public static String BaseURL = "https://dev2.innotech-sa.com/Psyter/Master/APIs/";
public static String BaseURLDocument = "https://dev2.innotech-sa.com/Psyter/Master/APIs/";
public static String BaseURLVideo = "https://dev2.innotech-sa.com/Psyter/Master/APIs/";
Authentication:
.addHeaders("Authorization", "Bearer " + mpref.GetUserToken())
Key Endpoints Used:
| Category | Endpoints |
|---|---|
| Auth | /api/Auth/Login, /api/Auth/Register, /api/Auth/RefreshToken |
| CareProvider | /api/CareProvider/GetAppointments, /api/CareProvider/GetProfile, /api/CareProvider/UpdateProfile |
| Messaging | /api/Messaging/GetConversations, /api/Messaging/SendMessage |
| Assessment | /api/Assessment/GetTemplates, /api/Assessment/AssignToPatient |
| Scheduling | /api/CareProvider/GetSchedule, /api/CareProvider/SetAvailability |
| Payment | /api/Payment/GetHistory, /api/Payment/RequestRefund |
2. Firebase Integration¶
Configuration: app/google-services.json
Services Used:
- FCM (Firebase Cloud Messaging): Push notifications
- Crashlytics: Crash reporting
- Analytics: User behavior tracking
FCM Handler: MyFirebaseMessagingService.java
Notification Types:
switch (notificationType) {
case "1": // New message
openChatActivity(conversationId);
break;
case "2": // Appointment reminder
openAppointmentsFragment();
break;
case "3": // Incoming call
openVideoCallActivity(meetingId);
break;
case "4": // Assessment assigned
openAssessmentsFragment();
break;
// ...
}
3. WebSocket Integration (NodeServer)¶
Library: nv-websocket-client 2.3
Connection: Legacy WebRTC implementation (Collaboration/Presence/CollaborationMain.java)
Commands Sent:
{
"command": "JOIN_CALL",
"meetingId": "abc123",
"userId": "user123",
"userType": "CareProvider"
}
Note: Being phased out in favor of VideoSDK’s managed WebRTC.
4. VideoSDK Integration¶
Library: live.videosdk:rtc-android-sdk:0.1.31
Initialization: MainApplication.java
@Override
public void onCreate() {
super.onCreate();
VideoSDK.initialize(this);
}
Usage: OneToOneCallActivity.kt
5. Payment Gateway Integration¶
Method: WebView redirect
Flow:
App → PaymentWebActivity (WebView)
→ Load payment URL (Smart Routing payment gateway)
→ User completes payment in browser
→ Redirect back to app with payment status
→ Parse URL parameters
→ Update appointment status
URL Construction:
String paymentUrl = Utils.BaseURLPayment +
"serviceProviderId=" + providerId +
"&serviceConsumerId=" + userId +
"&amount=" + amount +
"&bookingId=" + bookingId;
webView.loadUrl(paymentUrl);
Code Organization Assessment¶
Strengths ✅¶
-
Clear package separation by feature domain
- CareProvider vs Client vs CommonUser
- Easy to locate feature-specific code -
Centralized utilities
-Stats/Utils.javafor global methods
-Stats/MySharedPreferences.javafor preference management -
Modern navigation
- Jetpack Navigation Component with bottom nav
- Kotlin-based TabManager for type safety -
Localization support
- RTL support for Arabic
-LocaleUtils.javafor language management -
Firebase integration
- Proper FCM setup with structured notification handling
Weaknesses ⚠️¶
-
Code Duplication
- CareProvider and Client packages have overlapping code
- Adapters duplicated (MyAppointmentsAdapter vs MyAppointmentsCarePAdapter)
- Recommendation: Extract shared code to CommonUser package -
No Repository Pattern
- Direct API calls in Activities/Fragments
- Difficult to test and mock
- No caching layer
- Recommendation: Implement Repository + ViewModel pattern -
Large Classes
- Some Activities exceed 2000 LOC (e.g.,WeeklyScheduleFragment.java~2600 LOC)
- God classes with too many responsibilities
- Recommendation: Extract to smaller, focused classes -
Mixed Architecture
- Old code: MVC pattern
- New code: MVVM with LiveData
- No consistent pattern
- Recommendation: Gradual migration to MVVM -
Language Inconsistency
- Mostly Java with growing Kotlin adoption
- No clear strategy for which language to use
- Recommendation: Define Kotlin-first policy for new code -
Hard-Coded Strings
- Some UI strings not instrings.xml
- URL configurations in code
- Recommendation: Externalize all strings and configs -
Deep Nesting
- Some callbacks nested 4-5 levels deep
- Recommendation: Use RxJava or Kotlin Coroutines
Complexity Metrics (Estimated)¶
| Metric | Value | Industry Standard | Status |
|---|---|---|---|
| Average Activity Size | 600 LOC | 300-400 LOC | ⚠️ High |
| Largest Activity | 2600 LOC | <500 LOC | ❌ Too Large |
| Cyclomatic Complexity (avg) | 15 | <10 | ⚠️ High |
| Package Coupling | Medium | Low | ⚠️ Medium |
| Test Coverage | <10% | >70% | ❌ Very Low |
Architectural Patterns¶
Current Patterns¶
1. MVC (Legacy Pattern)¶
┌──────────────┐
│ Activity │ ← Controller
│ (Fragment) │
└──────┬───────┘
│
↓
┌──────────────┐
│ Adapter │ ← View
│ (RecyclerView)│
└──────┬───────┘
│
↓
┌──────────────┐
│ DataModel │ ← Model (POJO)
└──────────────┘
Used in: Most Java Activities/Fragments
2. MVVM (Modern Pattern - Partial)¶
┌──────────────┐
│ Activity │ ← View
│ (Fragment) │ observes LiveData
└──────┬───────┘
│
↓
┌──────────────┐
│ ViewModel │ ← (Not yet implemented)
│ (missing) │
└──────┬───────┘
│
↓
┌──────────────┐
│ Repository │ ← (Not yet implemented)
│ (missing) │
└──────┬───────┘
│
↓
┌──────────────┐
│ DataModel │ ← Model
└──────────────┘
Used in: Some newer Kotlin activities, but incomplete
3. Observer Pattern¶
MessageObservable (Event Bus)
↓
Fragments register as observers
↓
Events broadcast to all observers
Used in: Cross-component messaging
4. Singleton Pattern¶
// Utils.java
public class Utils {
private static Utils instance;
public static Utils getInstance() {
if (instance == null) instance = new Utils();
return instance;
}
}
Used in: Utilities, SharedPreferences wrapper
Recommended Pattern (Target Architecture)¶
┌─────────────────────────────────────────────────────────────┐
│ RECOMMENDED ARCHITECTURE │
└─────────────────────────────────────────────────────────────┘
┌──────────────┐
│ Activity │ ← View (only UI logic)
│ (Fragment) │ observes LiveData/StateFlow
└──────┬───────┘
│
↓
┌──────────────┐
│ ViewModel │ ← Presentation logic
│ + LiveData │ exposes UI state
└──────┬───────┘
│
↓
┌──────────────┐
│ Repository │ ← Data source coordination
│ │ (API + Cache + Database)
└──────┬───────┘
│
├──→ API (Retrofit)
├──→ LocalDatabase (Room)
└──→ SharedPreferences
Conclusion¶
The AndroidCareProvider codebase is a feature-rich, functional application with strong domain separation but suffering from technical debt and inconsistent architectural patterns. The transition from Java to Kotlin and from MVC to MVVM is underway but incomplete.
Priority Recommendations¶
Do Now (0-2 weeks):
1. Extract common code from CareProvider/Client packages to reduce duplication
2. Implement basic ViewModel + Repository for new features
3. Reduce size of largest Activities (break into smaller classes)
4. Add comprehensive logging for debugging
Do Next (1-2 months):
5. Gradual migration to MVVM for existing features
6. Implement offline caching with Room database
7. Add unit tests (target 30% coverage)
8. Standardize error handling
Plan (3-6 months):
9. Complete Kotlin migration for all new code
10. Implement dependency injection (Hilt/Koin)
11. Refactor to Clean Architecture
12. Achieve 70%+ test coverage
Document Status: Complete
Next Steps: Feature Inventory and Dependency Analysis
Maintained By: Audit Team
Version: 1.0