Psyter APIs (ASP.NET Web API) - Detailed Structure - Part 2 of 2

Continuation from Part 1


๐ŸŽฎ Controllers (Continued)

4. MessagingController.cs

File: Controllers/MessagingController.cs
Route Prefix: /ChatMessaging
Lines of Code: 271

Purpose: Real-time chat messaging between clients and providers

Key Endpoints:

Send Messages

POST /ChatMessaging/SendMessage
- Purpose: Send chat message
- Request: SendMessage

{
    SenderId: long,
    RecieverId: long,
    TextMessage: string,
    MessageType: int, // 1=Text, 2=Image, 3=File, 4=Voice
    AttachmentUrl: string,
    IsSystemMessage: bool
}

- Process:
1. Validate sender authorization
2. Save message to database
3. Get sender name
4. Send FCM push notification to receiver
5. Return message details
- Response: MessageResponse
- Real-time: FCM notification triggers real-time update in app

Get Conversations

POST /ChatMessaging/GetConversationsList
- Purpose: Get list of all conversations for a user
- Request: GetConversationList

{
    UserLoginInfoId: long,
    PageNumber: int,
    PageSize: int
}

- Response: List of ConversationResponse
- Each Conversation:
- Other user info (name, photo)
- Last message
- Last message time
- Unread count
- Online status
- Sorting: Most recent first

POST /ChatMessaging/GetConversationMessagesList
- Purpose: Get all messages in a conversation
- Request: GetConversationMessagesList

{
    UserLoginInfoId: long,
    UserLoginInfoId_Other: long,
    PageNumber: int,
    PageSize: int
}

- Response: List of MessageResponse
- Each Message:
- Message ID
- Sender ID
- Text/attachment
- Timestamp
- Read status
- Message type
- Features:
- Pagination support
- Marks messages as read
- Descending order (newest first)

Message Actions

POST /ChatMessaging/MarkMessagesAsRead
- Purpose: Mark messages as read
- Request: List of message IDs
- Process: Update read status in database
- Effect: Update unread count badge

POST /ChatMessaging/DeleteMessage
- Purpose: Delete message
- Request: Message ID, delete for both flag
- Options:
- Delete for self only
- Delete for both users
- Note: Cannot delete after 24 hours

POST /ChatMessaging/SendTypingStatus
- Purpose: Send typing indicator
- Request: Sender ID, Receiver ID, is typing flag
- Real-time: Via WebSocket (NodeServer handles this)

Media Messages

POST /ChatMessaging/UploadChatMedia
- Purpose: Upload image/file for chat
- Request: Multipart file upload
- Max Size: 25 MB
- Formats: Images (JPG, PNG, GIF), Documents (PDF, DOC), Voice (MP3, M4A)
- Process:
1. Validate file type and size
2. Upload to FTP/cloud storage
3. Generate thumbnail (for images)
4. Return file URL
- Response: File URL, thumbnail URL

Block/Report

POST /ChatMessaging/BlockUser
- Purpose: Block user from messaging
- Request: User ID to block
- Effect:
- Cannot send messages
- Cannot see online status
- Existing conversation hidden

POST /ChatMessaging/ReportMessage
- Purpose: Report inappropriate message
- Request: Message ID, reason
- Admin Review: Flagged for moderation


5. PaymentController.cs

File: Controllers/PaymentController.cs
Route Prefix: /BookingPayment
Lines of Code: 1,959

Purpose: Payment processing, booking, and financial transactions

Key Endpoints:

Booking & Payment

POST /BookingPayment/InsertBookingOrder
- Purpose: Create booking order (appointment booking)
- Authorization: Client only ([ValidateClientClaim])
- Request: BookingOrder

{
    UserLoginInfoConsumer: long, // Client ID
    UserLoginInfoProvider: long, // Provider ID
    SlotIds: List<long>,
    ServiceId: long,
    TotalAmount: decimal,
    Currency: string,
    PromotionCode: string,
    PaymentMethod: int,
    BookingDate: DateTime,
    Notes: string
}

- Process:
1. Validate slot availability
2. Apply promotion code (if any)
3. Calculate final amount
4. Create order record
5. Reserve slots temporarily
- Response: BookingOrderResponse with Order ID

POST /BookingPayment/InsertBookingOrderPayForData
- Purpose: Complete booking with payment
- Request: BookingOrderPayForData

{
    UserLoginInfoConsumer: long,
    ProceedBookingAsWell: bool,
    BookingData: SchedulingRequest,
    OrderMainId: long,
    PaymentMethod: int,
    PaymentDetails: object
}

- Process:
1. Validate booking data
2. Call Scheduling API to book slots
3. Process payment
4. Confirm booking if payment successful
5. Send confirmation notifications
6. Send email/SMS confirmations
- Payment Methods:
- Credit Card (via payment gateway)
- Wallet balance
- Promotion credit
- Package credit

Payment Gateway Integration

POST /BookingPayment/ProcessPayment
- Purpose: Process credit card payment
- Gateway: SmartRouting Payment Gateway
- Request: PaymentRequest

{
    OrderMainId: long,
    Amount: decimal,
    Currency: string,
    CardNumber: string, // Encrypted
    ExpiryDate: string,
    CVV: string, // Encrypted
    CardHolderName: string
}

- Process:
1. Encrypt sensitive data
2. Generate secure hash
3. Call payment gateway API
4. Validate response
5. Update order status
6. Log transaction
- Response: Transaction ID, status, receipt URL
- Security:
- PCI DSS compliance
- Certificate-based authentication
- SHA-256 secure hash

POST /BookingPayment/VerifyPayment
- Purpose: Verify payment status (callback from gateway)
- Request: Payment gateway callback data
- Process:
1. Validate secure hash
2. Check transaction status
3. Update order in database
4. Send confirmation if successful
5. Release slots if failed
- Response: Success/failure status

Refunds

POST /BookingPayment/RequestRefund
- Purpose: Initiate refund for cancelled appointment
- Authorization: Admin or system
- Request: RefundRequest

{
    OrderMainId: long,
    TransactionId: string,
    RefundAmount: decimal,
    RefundReason: string,
    CancellationPolicy: int
}

- Process:
1. Validate refund eligibility
2. Calculate refund amount (based on policy)
3. Call payment gateway refund API
4. Update order status
5. Update wallet if applicable
6. Send refund notification
- Cancellation Policies:
- 24+ hours: Full refund
- 12-24 hours: 50% refund
- <12 hours: No refund (configurable)
- Response: Refund status, amount, expected date

GET /BookingPayment/GetRefundStatus/{refundId}
- Purpose: Check refund processing status
- Response: Refund details, status, timeline

Wallet Management

GET /BookingPayment/GetWalletBalance/{userLoginInfoId}
- Purpose: Get user wallet balance
- Response: WalletResponse

{
    Balance: decimal,
    Currency: string,
    PendingAmount: decimal,
    AvailableAmount: decimal
}

POST /BookingPayment/AddWalletCredit
- Purpose: Add money to wallet
- Request: Amount, payment method
- Process: Similar to payment processing

GET /BookingPayment/GetWalletTransactions/{userLoginInfoId}
- Purpose: Get wallet transaction history
- Response: List of transactions (credits, debits, refunds)

Promotion Codes

POST /BookingPayment/ValidatePromotionCode
- Purpose: Validate and apply promotion code
- Request: PromotionCodeRequest

{
    PromotionCode: string,
    UserLoginInfoId: long,
    ServiceId: long,
    Amount: decimal
}

- Validation:
- Code exists and active
- Not expired
- Usage limit not reached
- Minimum amount met
- Applicable to service
- User not already used (if single-use)
- Response: PromotionCodeResponse
{
    DiscountType: int, // 1=Percentage, 2=Fixed
    DiscountValue: decimal,
    DiscountAmount: decimal,
    FinalAmount: decimal,
    IsValid: bool
}

GET /BookingPayment/GetMyPromotions/{userLoginInfoId}
- Purpose: Get available promotions for user
- Response: List of applicable promotion codes

Order Management

GET /BookingPayment/GetOrderDetails/{orderMainId}
- Purpose: Get complete order information
- Response: OrderDetailsResponse
- Includes:
- Order info
- Appointment details
- Payment details
- Refund info (if any)
- Transaction history

GET /BookingPayment/GetMyOrders/{userLoginInfoId}
- Purpose: Get user’s order history
- Query Params: Status filter, date range
- Response: List of orders

PUT /BookingPayment/UpdateOrderStatus
- Purpose: Update order status
- Authorization: Admin or system
- Request: Order ID, new status
- Statuses:
- Pending Payment
- Payment Successful
- Payment Failed
- Completed
- Cancelled
- Refunded

Revenue & Payouts (for Providers)

GET /BookingPayment/GetProviderEarnings/{userLoginInfoId}
- Purpose: Get provider earnings summary
- Authorization: Provider only
- Response: ProviderEarningsResponse

{
    TotalEarnings: decimal,
    AvailableBalance: decimal,
    PendingBalance: decimal,
    PlatformFee: decimal,
    NetEarnings: decimal,
    LastPayoutDate: DateTime,
    NextPayoutDate: DateTime
}

POST /BookingPayment/RequestPayout
- Purpose: Provider requests payout
- Request: PayoutRequest

{
    UserLoginInfoId: long,
    Amount: decimal,
    PaymentMethod: string, // BankTransfer, PayPal, etc.
    BankDetails: BankAccount
}

- Validation:
- Minimum payout amount (e.g., $100)
- Available balance sufficient
- Bank details verified
- Process:
1. Lock payout amount
2. Create payout record
3. Admin approval (manual or automatic)
4. Process bank transfer
5. Update provider balance

GET /BookingPayment/GetPayoutHistory/{userLoginInfoId}
- Purpose: Get payout history
- Response: List of payouts with status

Packages (Session Bundles)

GET /BookingPayment/GetAvailablePackages
- Purpose: Get session packages/bundles
- Response: List of packages
- Package Types:
- 5 sessions - 10% discount
- 10 sessions - 20% discount
- Monthly unlimited - Fixed price

POST /BookingPayment/PurchasePackage
- Purpose: Purchase session package
- Request: Package ID, payment method
- Process: Similar to booking order

GET /BookingPayment/GetMyPackages/{userLoginInfoId}
- Purpose: Get user’s purchased packages
- Response: List of packages with remaining sessions


6. NotificationController.cs

File: Controllers/NotificationController.cs
Route Prefix: /Notification
Lines of Code: 1,555

Purpose: Push notification management and delivery

Key Endpoints:

System Notifications

GET /Notification/SendStatusUpdationNotification/{userLoginInfoId}
- Purpose: Send profile status update notification
- Triggered: When admin approves/rejects provider profile
- Notification Data:

{
    UserLoginInfoId: long,
    ProfileStatus: int,
    NotificationType: int,
    Message: string
}

- Channel: FCM push notification

GET /Notification/SendBookingNotification/{orderMainId}
- Purpose: Send appointment booking notification
- Recipients: Provider (new booking notification)
- Notification:
- Title: “New Appointment Booked”
- Body: “{Client Name} has booked an appointment on {Date} at {Time}”
- Action: Open appointment details

POST /Notification/SendBookingConfirmation
- Purpose: Send booking confirmation to client
- Channels: Push notification + Email + SMS
- Content: Appointment details, payment receipt, cancellation policy

POST /Notification/SendAppointmentReminder
- Purpose: Send reminder before appointment
- Timing: 24 hours before, 1 hour before
- Channels: Push + SMS
- Content: Appointment time, provider name, join meeting link

POST /Notification/SendCancellationNotification
- Purpose: Notify about appointment cancellation
- Recipients: Both provider and client
- Content: Cancellation reason, refund info

Custom Notifications

POST /Notification/SendCustomNotification
- Purpose: Send custom notification to user
- Authorization: Admin only
- Request: CustomNotificationRequest

{
    UserIds: List<long>,
    Title: string,
    Message: string,
    NotificationType: int,
    ActionUrl: string,
    ScheduledTime: DateTime?
}

- Features:
- Single or bulk send
- Immediate or scheduled
- Deep linking support

POST /Notification/SendBulkNotification
- Purpose: Send to user segments
- Segments:
- All users
- All providers
- All clients
- Inactive users
- Custom segment (by filter)

Notification Management

GET /Notification/GetNotifications/{userLoginInfoId}
- Purpose: Get user’s notifications
- Query Params: Page, page size, unread only
- Response: List of NotificationResponse
- Each Notification:
- ID
- Title
- Message
- Type
- Timestamp
- Read status
- Action URL

POST /Notification/MarkAsRead
- Purpose: Mark notifications as read
- Request: Notification IDs
- Response: Success status

POST /Notification/MarkAllAsRead/{userLoginInfoId}
- Purpose: Mark all notifications as read
- Response: Count of marked notifications

DELETE /Notification/DeleteNotification/{notificationId}
- Purpose: Delete notification
- Authorization: Owner only

GET /Notification/GetUnreadCount/{userLoginInfoId}
- Purpose: Get unread notification count
- Response: Count
- Use: Update badge number

Notification Settings

GET /Notification/GetNotificationSettings/{userLoginInfoId}
- Purpose: Get user notification preferences
- Response: NotificationSettings

{
    EnablePushNotifications: bool,
    EnableEmailNotifications: bool,
    EnableSMSNotifications: bool,
    BookingNotifications: bool,
    MessageNotifications: bool,
    ReminderNotifications: bool,
    MarketingNotifications: bool,
    QuietHoursEnabled: bool,
    QuietHoursStart: string,
    QuietHoursEnd: string
}

PUT /Notification/UpdateNotificationSettings
- Purpose: Update preferences
- Request: NotificationSettings object

FCM Topic Management

POST /Notification/SubscribeToTopic
- Purpose: Subscribe device to topic
- Request: FCM token, topic name
- Topics:
- doctor_{userLoginInfoId}~
- client_{userLoginInfoId}~
- all_providers
- all_clients
- announcements

POST /Notification/UnsubscribeFromTopic
- Purpose: Unsubscribe from topic
- Request: FCM token, topic name


7. HomeWorkController.cs

File: Controllers/HomeWorkController.cs
Route Prefix: /HomeWork
Lines of Code: 331

Purpose: Therapeutic homework assignment management

Key Endpoints:

Provider - Assign Homework

POST /HomeWork/SaveHomeWork
- Authorization: Provider only ([ValidateCareProviderClaim])
- Purpose: Create or update homework assignment
- Request: HomeWorkRequest

{
    HomeWorkId: long?, // Null for new, ID for update
    CareProviderId: long,
    ClientId: long,
    Title: string,
    Description: string,
    Instructions: string,
    DueDate: DateTime,
    AttachmentUrls: List<string>,
    Points: int?,
    HomeworkType: string // CBT worksheet, journal, etc.
}

- Process:
1. Validate authorization
2. Save homework to database
3. Send notification to client
4. Return homework details
- Response: HomeWorkResponse with homework ID

GET /HomeWork/GetHomeWorkForCareProvider
- Purpose: Get all homework assigned by provider
- Request: GetHomeWorkRequest

{
    CareProviderId: long,
    ClientId: long?, // Filter by client
    Status: int?, // Filter by status
    PageNumber: int,
    PageSize: int
}

- Response: List of HomeWorkResponse
- Filters:
- All homework
- By specific client
- By status (pending, submitted, graded)
- By date range

Client - Submit Homework

POST /HomeWork/SubmitHomeWork
- Authorization: Client only
- Purpose: Submit completed homework
- Request: SubmitHomeWorkRequest

{
    HomeWorkId: long,
    ClientId: long,
    SubmissionText: string,
    AttachmentUrls: List<string>,
    CompletionNotes: string,
    TimeSpent: int? // In minutes
}

- Process:
1. Validate homework exists
2. Save submission
3. Update homework status to “Submitted”
4. Send notification to provider
- Response: Submission details

GET /HomeWork/GetHomeWorkForClient
- Purpose: Get client’s homework assignments
- Request: Client ID, filters
- Response: List of homework with submission status

Feedback & Grading

POST /HomeWork/SaveHomeWorkFeedback
- Authorization: Provider only
- Purpose: Provide feedback on submitted homework
- Request: HomeWorkFeedbackRequest

{
    HomeWorkId: long,
    FeedbackText: string,
    Score: decimal?,
    Status: int // Approved, NeedsRevision, Rejected
}

- Process:
1. Validate provider is homework owner
2. Save feedback
3. Update status
4. Send notification to client
- Response: Success status

GET /HomeWork/GetHomeWorkFeedback/{homeWorkId}
- Purpose: Get feedback for specific homework
- Response: Feedback text, score, comments

Homework History

GET /HomeWork/GetHomeWorkHistory/{clientId}
- Purpose: Get client’s homework completion history
- Response: List of all homework with statuses
- Statistics:
- Total assigned
- Total completed
- Completion rate
- Average score

GET /HomeWork/GetHomeWorkStatistics/{userLoginInfoId}
- Purpose: Get homework statistics
- For Providers:
- Total assignments created
- Submissions received
- Average completion rate
- For Clients:
- Assignments received
- Completed assignments
- Pending assignments
- Average score

Templates

GET /HomeWork/GetHomeWorkTemplates
- Purpose: Get pre-made homework templates
- Response: List of templates
- Categories:
- CBT worksheets
- Mood tracking
- Thought records
- Activity scheduling
- Relaxation exercises

POST /HomeWork/CreateTemplateFromHomeWork
- Purpose: Save homework as reusable template
- Request: Homework ID
- Response: Template ID


8. UserPrescriptionController.cs

File: Controllers/UserPrescriptionController.cs
Route Prefix: /UserPrescription
Lines of Code: 1,539

Purpose: Electronic prescription management

Key Endpoints:

Medicine Database

POST /UserPrescription/GetMedicineList
- Authorization: Provider only
- Purpose: Search medicine database
- Request: UserPrescriptionRequest

{
    SearchTerm: string,
    PageNumber: int,
    PageSize: int,
    MedicineType: int?, // Tablet, Syrup, etc.
}

- Response: List of CatMedicine
- Each Medicine:
- Medicine ID
- Generic name
- Brand names
- Forms available
- Strengths
- Manufacturer

GET /UserPrescription/GetMedicineUnits
- Purpose: Get dosage units for medicine
- Params: Medicine ID, Dose ID
- Response: List of units (mg, ml, tablet, capsule, etc.)

POST /UserPrescription/GetDiagnosisList
- Purpose: Search diagnosis codes (ICD-10/DSM-5)
- Request: Search term
- Response: List of diagnosis codes with descriptions

POST /UserPrescription/GetAllergyList
- Purpose: Search allergy database
- Request: Search term
- Response: List of known allergies

Create Prescription

POST /UserPrescription/SavePrescription
- Authorization: Provider only
- Purpose: Create electronic prescription
- Request: PrescriptionRequest

{
    PrescriptionId: long?, // Null for new
    CareProviderId: long,
    ClientId: long,
    AppointmentId: long?,
    PrescriptionDate: DateTime,
    DiagnosisCodes: List<string>,
    Medications: List<MedicationItem>,
    AdditionalInstructions: string,
    PharmacyName: string?,
    ValidUntil: DateTime
}

- MedicationItem:
{
    MedicineId: long,
    MedicineName: string,
    Form: string, // Tablet, Syrup, etc.
    Strength: string, // 500mg, 10ml, etc.
    Dosage: string, // 1 tablet
    Frequency: string, // Twice daily
    Duration: int, // Days
    Route: string, // Oral, Topical, etc.
    Instructions: string
}

- Validation:
- Check drug interactions
- Check client allergies
- Verify dosage safety
- Validate provider license
- Process:
1. Save prescription to database
2. Generate PDF
3. Send to client (notification + email)
4. Log in client medical record
- Response: Prescription ID, PDF URL

POST /UserPrescription/CheckDrugInteractions
- Purpose: Check for drug interactions
- Request: List of medicine IDs
- Response: Interaction warnings, severity levels

POST /UserPrescription/CheckAllergies
- Purpose: Check medications against client allergies
- Request: Client ID, medicine IDs
- Response: Allergy alerts

Manage Prescriptions

GET /UserPrescription/GetPrescriptionDetails/{prescriptionId}
- Purpose: Get prescription details
- Authorization: Provider or client (owner)
- Response: Complete prescription information

GET /UserPrescription/GetClientPrescriptions/{clientId}
- Purpose: Get all prescriptions for client
- Authorization: Provider (if treating) or client (own)
- Response: List of prescriptions

GET /UserPrescription/GetProviderPrescriptions/{providerId}
- Purpose: Get prescriptions issued by provider
- Response: List of prescriptions

POST /UserPrescription/UpdatePrescription
- Purpose: Modify existing prescription
- Restrictions: Cannot modify after 24 hours
- Process: Creates new version, maintains history

DELETE /UserPrescription/CancelPrescription/{prescriptionId}
- Purpose: Cancel prescription
- Request: Prescription ID, reason
- Process: Marks as cancelled, notifies client

Prescription Actions

POST /UserPrescription/SendPrescriptionToPharmacy
- Purpose: Send prescription to pharmacy
- Request: Prescription ID, pharmacy details
- Process:
- Generate PDF
- Send via email/fax to pharmacy
- Log transmission

POST /UserPrescription/DownloadPrescriptionPDF/{prescriptionId}
- Purpose: Download prescription as PDF
- Response: PDF file
- Features:
- Provider letterhead
- QR code for verification
- Watermark
- Digital signature (if configured)

POST /UserPrescription/PrintPrescription/{prescriptionId}
- Purpose: Get print-ready version
- Response: Formatted HTML for printing

POST /UserPrescription/SharePrescription
- Purpose: Share prescription with another provider
- Request: Prescription ID, target provider ID
- Authorization: Client consent required

Medication Management

GET /UserPrescription/GetClientCurrentMedications/{clientId}
- Purpose: Get active medications for client
- Response: List of current prescriptions
- Includes:
- Medication details
- Prescribing provider
- Start date
- Refills remaining

POST /UserPrescription/AddClientAllergy
- Purpose: Add allergy to client profile
- Request: Client ID, allergy details
- Process: Updates client medical record

GET /UserPrescription/GetClientAllergies/{clientId}
- Purpose: Get client’s allergies
- Response: List of known allergies


9. AdminController.cs

File: Controllers/AdminController.cs
Route Prefix: /Admin
Lines of Code: 1,113

Purpose: Administrative functions and provider approval

Key Endpoints:

Provider Management

POST /Admin/GetPhysicianListForFilterCriteria
- Authorization: Admin only ([ValidateAdminClaim])
- Purpose: Get list of providers for admin review
- Request: AdminRequest with FilterCriteria

{
    FilterCriteriaObject: {
        ProfileStatus: int?,
        SpecialityId: int?,
        CountryId: int?,
        SearchTerm: string,
        PageNumber: int,
        PageSize: int,
        SortBy: string,
        SortOrder: string
    }
}

- Response: List of providers with pagination
- Filters:
- By profile status (pending, approved, rejected)
- By specialty
- By location
- Search by name/email

POST /Admin/UpdatePhysicianProfileStatus
- Purpose: Approve/reject provider profile
- Request: AdminRequest

{
    UserLoginInfoId: long,
    CurrentProfileStatus: int,
    TargetProfileStatus: int, // Approved, Rejected
    RejectCode: int?,
    RejectionReason: string?,
    AgreementURL: string?
}

- Status Transitions:
- Incomplete โ†’ Complete: Profile submitted
- Complete โ†’ Approved: Admin approves
- Complete โ†’ Rejected: Admin rejects
- Rejected โ†’ Approved: Re-review and approve
- Approved โ†’ Rejected: Suspend provider
- Process:
1. Validate status transition
2. Update profile status
3. Send email notification
4. If approved: Send agreement link
5. If rejected: Send rejection reason
- Response: Updated profile status

User Management

GET /Admin/GetUserDetails/{userLoginInfoId}
- Purpose: Get complete user information
- Response: Full user profile with admin view

POST /Admin/SearchUsers
- Purpose: Search users
- Request: Search criteria
- Response: Matching users

PUT /Admin/SuspendUser
- Purpose: Suspend user account
- Request: User ID, reason, duration
- Effects:
- Account locked
- Cannot login
- Active sessions terminated
- Appointments cancelled (optionally)

PUT /Admin/UnsuspendUser
- Purpose: Reactivate suspended account
- Request: User ID

DELETE /Admin/DeleteUser
- Purpose: Permanently delete user (GDPR)
- Request: User ID
- Process:
- Anonymize personal data
- Remove from search indexes
- Cancel active appointments
- Process refunds
- Maintain audit trail

Content Moderation

POST /Admin/GetReportedContent
- Purpose: Get flagged content for review
- Filters: Content type, status
- Response: List of reports

POST /Admin/ModerateContent
- Purpose: Take action on reported content
- Request: Report ID, action
- Actions:
- Approve (no violation)
- Remove content
- Warn user
- Suspend user

Financial Management

POST /Admin/GetPendingPayouts
- Purpose: Get pending provider payouts
- Response: List of payout requests

POST /Admin/ApprovePayouts
- Purpose: Approve multiple payouts
- Request: List of payout IDs
- Process: Marks for processing by finance team

GET /Admin/GetTransactionDetails/{transactionId}
- Purpose: View transaction details
- Response: Complete transaction info

POST /Admin/ProcessRefund
- Purpose: Manually process refund
- Request: Order ID, amount, reason
- Response: Refund status

Analytics & Reports

GET /Admin/GetDashboardStatistics
- Purpose: Admin dashboard metrics
- Response: AdminDashboardResponse

{
    TotalUsers: int,
    TotalProviders: int,
    TotalClients: int,
    ActiveUsers: int,
    PendingProviderApprovals: int,
    TotalAppointments: int,
    TotalRevenue: decimal,
    ReportedContent: int,
    PendingPayouts: int
}

POST /Admin/GenerateReport
- Purpose: Generate custom reports
- Request: ReportRequest

{
    ReportType: string, // Users, Revenue, Appointments
    StartDate: DateTime,
    EndDate: DateTime,
    Filters: object,
    Format: string // PDF, Excel, CSV
}

- Response: Report file URL

GET /Admin/GetRevenueReport
- Purpose: Revenue and financial report
- Params: Date range
- Response: Revenue breakdown

GET /Admin/GetUserGrowthReport
- Purpose: User acquisition and growth
- Response: User registration trends

System Configuration

GET /Admin/GetSystemSettings
- Purpose: Get system configuration
- Response: All system settings

PUT /Admin/UpdateSystemSettings
- Purpose: Update system configuration
- Request: Settings object
- Settings:
- Platform fees
- Cancellation policies
- Minimum payout amount
- Promotion code rules
- Email templates


10. Additional Controllers (Brief Overview)

CatalogueController.cs

Route: /Catalogue
Purpose: Master data management
- Get countries, cities
- Get specializations
- Get languages
- Get time zones
- Get service categories
- Get education types

CommonController.cs

Route: /Common
Purpose: Common utility endpoints
- Upload files
- Get app configuration
- Get app version
- Health check endpoint

ContentManagerController.cs

Route: /ContentManager
Purpose: Content management (blogs, articles)
- Create/update blog posts
- Get published content
- Manage categories

ClientDiaryController.cs

Route: /ClientDiary
Purpose: Client diary/mood tracking
- Save diary entry
- Get diary entries
- Get mood trends

ReferralSystemController.cs

Route: /ReferralSystem
Purpose: Provider referrals
- Create referral
- Get referrals
- Accept/decline referral

GroupSessionController.cs

Route: /GroupSession
Purpose: Group therapy sessions
- Create group session
- Get sessions
- Enroll clients
- Manage slots

ConferenceEventController.cs

Route: /ConferenceEvent
Purpose: Professional events
- Create events
- Register for events
- Get event list

SEOManagerController.cs

Route: /SEOManager
Purpose: SEO and page management
- Manage page metadata
- Update SEO settings


๐Ÿ—„๏ธ Repositories (Data Access Layer)

Key Repositories

1. UserRepository.cs

Purpose: User account operations
Key Methods:
- AuthenticateUserLogin() - Validate credentials
- UserSocialLogin() - Social authentication
- RegisterUser() - Create account
- GetUserLoginDetails() - Get user info
- UpdateUserProfile() - Update profile
- ChangePassword() - Password management
- GetUserPreferences() - Get settings
- UpdateUserPreferences() - Save settings

2. ServiceProviderRepository.cs

Purpose: Provider profile and services
Key Methods:
- GetGeneralAccessDetails() - Public profile
- UpdateGeneralAccessDetails() - Update profile
- GetPersonalInfo() - Personal information
- UpdatePersonalInfo() - Update personal info
- GetWorkExperience() - Work history
- InsertWorkExperience() - Add work entry
- GetEducationHistory() - Education credentials
- GetUserServices() - Services offered
- SearchProviders() - Provider search

3. BookingPaymentRepository.cs

Purpose: Payments and bookings
Key Methods:
- SaveBookingOrder() - Create booking
- ProcessPayment() - Payment processing
- RefundPayment() - Process refund
- GetOrderMainInformation() - Order details
- GetWalletBalance() - Wallet operations
- ValidatePromotionCode() - Promotion validation
- GetProviderEarnings() - Revenue tracking

4. SchedulingRepository.cs

Purpose: Scheduling and availability
Key Methods:
- SaveServiceProviderSchedule() - Set availability
- ValidateScheduleBooking() - Check slot availability
- SaveScheduleBooking() - Confirm booking
- GetAvailableSlots() - Get open slots
- BlockTimeSlot() - Block time
- GetProviderSchedule() - Get schedule

5. MessagingRepository.cs

Purpose: Chat messages
Key Methods:
- SaveMessage() - Send message
- GetConversationsList() - Get conversations
- GetConversationMessagesList() - Get messages
- MarkAsRead() - Update read status
- DeleteMessage() - Remove message

6. NotificationRepository.cs

Purpose: Notifications
Key Methods:
- SaveNotification() - Create notification
- GetNotifications() - Get user notifications
- MarkAsRead() - Update status
- DeleteNotification() - Remove notification
- GetUnreadCount() - Count unread

7. PatientRepository.cs

Purpose: Client/patient operations
Key Methods:
- GetScreeningQuestions() - Get questionnaire
- SaveScreeningAnswers() - Save answers
- SaveDiaryEntry() - Mood tracking
- GetDiaryEntries() - Get diary
- GetClientProfile() - Client information

8. HomeWorkRepository.cs

Purpose: Homework management
Key Methods:
- SaveHomeWork() - Create assignment
- GetHomeWorkForCareProvider() - Provider view
- GetHomeWorkForClient() - Client view
- SubmitHomeWork() - Submit assignment
- SaveHomeWorkFeedback() - Provider feedback

9. UserPrescriptionRepository.cs

Purpose: Prescription management
Key Methods:
- GetMedicineList() - Search medicines
- GetDiagnosisList() - Search diagnoses
- SavePrescription() - Create prescription
- GetPrescriptionDetails() - Get prescription
- GetClientPrescriptions() - Client prescriptions
- CheckDrugInteractions() - Safety check

10. AdminRepository.cs

Purpose: Admin operations
Key Methods:
- GetPhysicianListForFilterCriteria() - Provider list
- UpdatePhysicianProfileStatus() - Approve/reject
- GetUserDetails() - User info
- SuspendUser() - Account suspension
- GetDashboardStatistics() - Admin metrics


๐Ÿ“ Models

Entity Models

Key Entities:

UserProfile.cs

public class UserProfile
{
    public long UserProfileId { get; set; }
    public long UserLoginInfoId { get; set; }
    public string FirstNamePLang { get; set; }
    public string LastNamePLang { get; set; }
    public string FirstNameSLang { get; set; }
    public string LastNameSLang { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public int? Gender { get; set; }
    public string ProfileImageUrl { get; set; }
    public int? CountryId { get; set; }
    public int? CityId { get; set; }
    public int? SpecialityId { get; set; }
    public int ProfileStatus { get; set; }
    public DateTime CreatedDate { get; set; }
}

UserServices.cs

public class UserServices
{
    public long UserServiceId { get; set; }
    public long UserLoginInfoId { get; set; }
    public string ServiceName { get; set; }
    public string Description { get; set; }
    public int DurationMinutes { get; set; }
    public decimal Price { get; set; }
    public string Currency { get; set; }
    public int SessionType { get; set; } // Video, Audio, In-person
    public bool IsActive { get; set; }
}

BookingPayment.cs

public class BookingPayment
{
    public long OrderMainId { get; set; }
    public long UserLoginInfoConsumer { get; set; }
    public long UserLoginInfoProvider { get; set; }
    public DateTime BookingDate { get; set; }
    public DateTime SlotDate { get; set; }
    public string SlotTime { get; set; }
    public decimal TotalAmount { get; set; }
    public decimal DiscountAmount { get; set; }
    public decimal FinalAmount { get; set; }
    public string Currency { get; set; }
    public int PaymentMethod { get; set; }
    public int PaymentStatus { get; set; }
    public string TransactionId { get; set; }
    public int OrderStatus { get; set; }
    public string CancellationReason { get; set; }
    public decimal RefundAmount { get; set; }
}

UserPrescription.cs

public class UserPrescription
{
    public long PrescriptionId { get; set; }
    public long CareProviderId { get; set; }
    public long ClientId { get; set; }
    public long? AppointmentId { get; set; }
    public DateTime PrescriptionDate { get; set; }
    public string DiagnosisCodes { get; set; }
    public string Medications { get; set; } // JSON array
    public string AdditionalInstructions { get; set; }
    public string PrescriptionPDFUrl { get; set; }
    public bool IsSent { get; set; }
    public DateTime? ValidUntil { get; set; }
}

Enumeration.cs

Key Enumerations:

public enum UserType
{
    Client = 1,
    Physician = 2,
    Admin = 3,
    ContentManager = 4
}

public enum ProfileStatus
{
    Incomplete = 0,
    Complete = 1,
    Approved = 2,
    Rejected = 3,
    Suspended = 4
}

public enum PaymentMethod
{
    CreditCard = 1,
    Wallet = 2,
    PromotionCode = 3,
    PackageCredit = 4
}

public enum PaymentStatus
{
    Pending = 0,
    Success = 1,
    Failed = 2,
    Refunded = 3
}

public enum OrderStatus
{
    Pending = 0,
    Confirmed = 1,
    Completed = 2,
    Cancelled = 3,
    NoShow = 4
}

public enum NotificationType
{
    Appointment = 1,
    Message = 2,
    Payment = 3,
    ProfileUpdate = 4,
    Reminder = 5,
    Review = 6,
    Homework = 7,
    Prescription = 8,
    System = 9
}

public enum SessionType
{
    Video = 1,
    Audio = 2,
    InPerson = 3,
    Chat = 4
}

public enum ResponseReason
{
    Success = 0,
    Error = 1,
    InvalidCredentials = 2,
    UserNotFound = 3,
    NotAllowed = 4,
    EmptyParameter = 5,
    AlreadyExists = 6,
    InvalidToken = 7,
    ExpiredToken = 8
}

๐Ÿ”ง Common Utilities (Continued)

Payment Integration

SmartRoutingPaymentInquiryRefund.cs
- Purpose: Payment gateway integration
- Gateway: SmartRouting (Saudi payment processor)
- Key Methods:
- RefundPayment() - Process refund
- GenerateSecureHash() - Security hash generation
- ProcessInquiryOrRefund() - API call to gateway
- Security:
- SHA-256 hashing
- Certificate-based authentication (MerchantCertificates.p12)
- TLS 1.2 encryption
- Process Flow:
1. Create refund request
2. Generate secure hash (SHA-256)
3. Call gateway API with certificate
4. Validate response
5. Update database
6. Return status

Exception Handling

ExceptionManager.cs
- Purpose: Centralized exception logging
- Methods:
- LogException() - Log exception to database
- LogToFile() - Log to file (Log4Net)
- SendErrorNotification() - Alert admins
- Logged Information:
- Exception message and stack trace
- User ID
- Controller and action
- Request parameters
- Timestamp
- IP address

GlobalExceptionHandler.cs
- Purpose: Global exception filter
- Functionality:
- Catches unhandled exceptions
- Logs to database and file
- Returns standardized error response
- Hides sensitive info in production
- Response Format:

{
    "Status": 0,
    "Message": "An error occurred",
    "Reason": "Error",
    "ErrorId": "ERR-12345"
}

Error Logging

ErrorLogRepository.cs
- Purpose: Log errors to database
- Table: ErrorLog
- Stored Procedure: Log_Errors
- Retention: 90 days

log4net.config
- Purpose: File-based logging configuration
- Log File: C:\PsyterAPILogger.log
- Rolling: Size-based (5 MB max, 5 backups)
- Log Level: ALL (can be changed to ERROR for production)
- Pattern: %date [%thread] %-5level %logger - %message%newline


๐Ÿ”’ Security Features

Authentication Security

  • OAuth 2.0: Industry-standard authentication
  • Bearer Tokens: Secure token-based auth
  • Token Expiration: 30-day expiry
  • Refresh Tokens: Stored securely in database
  • Revocation: Tokens can be revoked

Authorization Security

  • Claims-Based: User type and ID in token
  • Endpoint Protection: Attribute-based authorization
  • Resource Validation: Users can only access own data
  • Role Segregation: Client, Provider, Admin roles

Data Security

  • Encryption: AES encryption for sensitive data
  • Hashing: PBKDF2 for passwords
  • Connection Strings: Encrypted in Web.config
  • SQL Injection: Parameterized queries only
  • XSS Protection: Anti-XSS validation filter

Communication Security

  • HTTPS Only: TLS 1.2+
  • CORS: Restricted origins
  • Security Headers: X-Frame-Options, X-Content-Type-Options
  • Certificate Pinning: For payment gateway

Compliance

  • GDPR: Data deletion, anonymization
  • HIPAA: (If configured) Encrypted storage, audit logs
  • PCI DSS: Payment card data not stored
  • Data Retention: Configurable retention policies

๐Ÿ“Š Database Integration

Database Structure

Two Databases:
1. PsyterDatabase: Main application database
2. SchedulingDatabase: Scheduling system database

Stored Procedure Architecture

Benefits:
- Performance: Compiled and optimized
- Security: No SQL injection risk
- Maintainability: Business logic in database
- Reusability: Called from multiple places
- Versioning: Easier to update without code changes

Naming Convention:
- SP_ prefix for general procedures
- User_ prefix for user-related
- Patient_ prefix for client-related
- Catalogue_ prefix for master data
- Message_ prefix for messaging

Example Stored Procedure Call:

using (SqlCommand command = new SqlCommand("SP_GetUserProfile", connection))
{
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("@UserLoginInfoId", SqlDbType.BigInt).Value = userLoginInfoId;

    SqlDataAdapter adapter = new SqlDataAdapter(command);
    DataTable dataTable = new DataTable();
    adapter.Fill(dataTable);

    // Map DataTable to model
    var profile = MapToUserProfile(dataTable);
}


๐Ÿš€ Deployment & CI/CD

Azure DevOps Pipeline

File: azure-pipelines.yml

Pipeline Steps:

  1. Trigger: On master branch push
  2. Agent Pool: DevWebServerAgentPool (self-hosted)
  3. NuGet Restore: Restore packages
  4. Build: MSBuild with Release configuration
  5. Package: Create deployment package
  6. Publish Artifacts: Store build output
  7. Deploy: Copy to deployment directory

Configuration:

pool: 'DevWebServerAgentPool'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'

Deployment Target:

D:\ROOT\Development\Psyter\Master\APIs

Manual Deployment Steps

  1. Build Solution:

    msbuild PsyterAPI.sln /p:Configuration=Release
    

  2. Publish to Folder:

    msbuild PsyterAPI.csproj /p:DeployOnBuild=true /p:PublishProfile=FolderProfile
    

  3. Update Web.config:
    - Switch connection strings (dev โ†’ prod)
    - Update app settings
    - Enable custom errors

  4. Deploy to IIS:
    - Copy published files to IIS directory
    - Configure application pool (.NET 4.7.2)
    - Set permissions
    - Test endpoints

  5. Post-Deployment:
    - Smoke tests
    - Health check endpoint
    - Monitor logs


๐Ÿงช Testing

Testing Approach

Unit Tests: (Not included in project structure, but recommended)
- Test repositories
- Test business logic
- Mock database calls

Integration Tests:
- Test API endpoints
- Test with test database
- Validate responses

Manual Testing:
- Postman collections
- Swagger/OpenAPI documentation
- Admin testing tools

Test Users

Development Environment:
- Test client accounts
- Test provider accounts
- Test admin accounts
- Test payment cards (sandbox)


๐Ÿ“ˆ Performance Optimization

Implemented Optimizations

  1. Database:
    - Indexed columns
    - Optimized stored procedures
    - Connection pooling
    - Command timeout (10 minutes for complex queries)

  2. Caching:
    - Output caching for master data
    - [CacheFilter] attribute for cacheable endpoints
    - Cache expiration policies

  3. API Response:
    - Pagination for large lists
    - Field filtering
    - Compression (gzip)

  4. File Uploads:
    - Streaming uploads
    - Size limits enforced
    - Background processing for large files


๐Ÿ” Monitoring & Logging

Log4Net Configuration

Log Location: C:\PsyterAPILogger.log
Log Rotation: Size-based (5 MB per file, 5 backups)
Log Level: ALL (configurable)

What’s Logged:
- All exceptions
- Authentication attempts
- Payment transactions
- Admin actions
- API requests (configurable)

Exception Logging

ErrorLog Table:
- Exception details
- User context
- Request information
- Stack trace
- Timestamp

Admin Dashboard:
- View recent errors
- Error statistics
- Error reports


๐Ÿ“š API Documentation

Endpoints Summary

Total Controllers: 18
Total Endpoints: 200+

Main Endpoint Groups:
- Authentication & User Management (30+ endpoints)
- Service Provider Management (50+ endpoints)
- Patient/Client Operations (40+ endpoints)
- Messaging (15 endpoints)
- Payments & Bookings (40+ endpoints)
- Notifications (20 endpoints)
- Prescriptions (25 endpoints)
- Homework (12 endpoints)
- Admin Operations (30+ endpoints)
- Common & Utilities (20+ endpoints)

Request/Response Format

All Requests:
- JSON format
- Authorization header (except public endpoints)
- Content-Type: application/json

Standard Response:

{
    "Status": 1,
    "Message": "Success",
    "Reason": "Success",
    "Data": { ... }
}

Error Response:

{
    "Status": 0,
    "Message": "Error message",
    "Reason": "ErrorCode",
    "Data": null
}


๐Ÿ”— Integration Points

External Services

  1. Firebase:
    - Push notifications (FCM)
    - Authentication (optional)
    - Analytics

  2. VideoSDK:
    - Video call room creation
    - Recording management
    - Meeting details

  3. Payment Gateway:
    - SmartRouting payment processor
    - Transaction processing
    - Refunds

  4. Scheduling API:
    - External scheduling system
    - Slot management
    - Booking validation

  5. SMS Gateway:
    - OTP delivery
    - Appointment reminders
    - Notifications

  6. Email Service:
    - SMTP configuration
    - Template-based emails
    - Transactional emails

Internal Integration

  1. NodeServer (WebSocket):
    - Real-time chat
    - Call signaling
    - Presence status

  2. Media API:
    - File uploads
    - Media processing
    - CDN integration

  3. Shared API (Tahoon_API):
    - Shared services
    - Common utilities


๐Ÿ›ก๏ธ Best Practices Implemented

Code Organization

โœ… Repository pattern for data access
โœ… Dependency injection ready
โœ… Separation of concerns
โœ… DTOs for request/response
โœ… Centralized constants

Security

โœ… OAuth 2.0 authentication
โœ… Claims-based authorization
โœ… Anti-XSS validation
โœ… SQL injection prevention
โœ… Encrypted sensitive data

Performance

โœ… Database indexing
โœ… Connection pooling
โœ… Response caching
โœ… Pagination support
โœ… Async/await pattern

Error Handling

โœ… Global exception handler
โœ… Centralized logging
โœ… Standardized error responses
โœ… Admin error dashboard

Documentation

โœ… XML comments
โœ… README files
โœ… Stored procedure documentation
โœ… API endpoint documentation


๐ŸŽฏ Key Features Summary

Core Functionality

  • โœ… User authentication & registration
  • โœ… Provider profile management
  • โœ… Service offerings & pricing
  • โœ… Availability & scheduling
  • โœ… Appointment booking
  • โœ… Payment processing
  • โœ… Video consultation integration
  • โœ… Real-time messaging
  • โœ… Push notifications
  • โœ… Electronic prescriptions
  • โœ… Homework assignments
  • โœ… Mood tracking & diary
  • โœ… Reviews & ratings
  • โœ… Revenue tracking
  • โœ… Admin panel operations

Advanced Features

  • โœ… Multi-language support
  • โœ… Multiple payment methods
  • โœ… Promotion codes
  • โœ… Session packages
  • โœ… Wallet system
  • โœ… Refund processing
  • โœ… Drug interaction checking
  • โœ… Allergy alerts
  • โœ… Referral system
  • โœ… Group sessions
  • โœ… Content management
  • โœ… SEO management
  • โœ… Analytics & reporting

๐Ÿ“Š Technology Stack Summary

Backend Framework: ASP.NET Web API 2
Language: C# (.NET Framework 4.7.2)
Authentication: OAuth 2.0 + JWT
Database: SQL Server (ADO.NET)
ORM: None (Stored Procedures)
Logging: Log4Net
Document Generation: iTextSharp
JSON: Newtonsoft.Json
Mapping: AutoMapper
Testing: (Manual/Postman)
Deployment: Azure DevOps + IIS


๐Ÿ”„ Data Flow Example

Complete Booking Flow

  1. Client Searches Providers:

    POST /ServiceProvider/SearchProviders
    โ†’ ServiceProviderRepository.SearchProviders()
    โ†’ SP_SearchServiceProviders
    โ†’ Returns list of providers
    

  2. Client Views Availability:

    GET /ServiceProvider/GetProviderAvailability/{providerId}
    โ†’ SchedulingRepository.GetProviderSchedule()
    โ†’ SP_GetProviderSchedule (Scheduling DB)
    โ†’ Returns available slots
    

  3. Client Creates Booking Order:

    POST /BookingPayment/InsertBookingOrder
    โ†’ BookingPaymentRepository.SaveBookingOrder()
    โ†’ SP_SaveBookingOrder
    โ†’ Returns Order ID
    

  4. Client Processes Payment:

    POST /BookingPayment/ProcessPayment
    โ†’ SmartRoutingPaymentInquiryRefund.ProcessPayment()
    โ†’ Payment Gateway API Call
    โ†’ BookingPaymentRepository.UpdatePaymentStatus()
    โ†’ SP_UpdatePaymentStatus
    

  5. Booking Confirmed:

    โ†’ SchedulingRepository.SaveScheduleBooking()
    โ†’ SP_SaveScheduleBooking (Scheduling DB)
    โ†’ NotificationRepository.SaveNotification()
    โ†’ FCMNotification.SendNotification() to Provider
    โ†’ EmailManager.SendBookingConfirmation() to Client
    

  6. Appointment Reminder:

    Background Job (24h before):
    โ†’ NotificationRepository.GetUpcomingAppointments()
    โ†’ FCMNotification.SendReminder()
    โ†’ SendSMSHelper.SendReminder()
    


END OF PART 2 - APIs DOCUMENTATION COMPLETE


๐Ÿ“ Complete Documentation Summary

Part 1 Covered:
- Project structure, configuration, dependencies
- Authentication & authorization
- Data access layer
- Controllers: User, ServiceProvider, Patient
- Request/Response models
- Common utilities

Part 2 Covered:
- Controllers: Messaging, Payment, Notification, Homework, Prescription, Admin
- Additional controllers overview
- Repositories detailed
- Entity models & enumerations
- Security features
- Database integration
- Deployment & CI/CD
- Performance optimization
- Monitoring & logging
- Best practices

Total Documentation: ~50,000 words covering the complete ASP.NET Web API backend


Completion Status:
- โœ… Android Client (COMPLETED)
- โœ… AndroidCareProvider (COMPLETED)
- โœ… APIs - Part 1 (COMPLETED)
- โœ… APIs - Part 2 (COMPLETED)
- โญ๏ธ Media API (NEXT)
- Pending: NodeServer, Tahoon_API, Web, WindowsService, IOSCareProvider