WindowsService - Feature Inventory¶
Overview¶
This document provides a comprehensive inventory of all features implemented in the Psyter Payment Inquiry Windows Service, including dependencies, integration points, and technical details.
Core Features¶
1. Payment Inquiry Processing¶
Feature ID: F-001
Category: Payment Processing
Status: Active
Priority: Critical
Description:
Automated verification of pending payment transactions with the payment gateway to confirm successful payment completion for booking appointments.
Technical Implementation:
- Timer Interval: 10 minutes (600,000ms)
- Thread: RefundAndInquiryThread
- Entry Point: GetPendingPayment()
- Stored Procedure: ws_GetPendingPaymentsList_AppConfigSetting
Process Flow:
1. Fetch pending payments from database
2. Retrieve payment gateway configuration
3. Generate SHA256 secure hash
4. POST inquiry to Smart Routing payment gateway
5. Parse response and extract status codes
6. Update PayForData table with payment status
7. If successful (StatusCode=00000):
- Authenticate with Scheduling API
- Update booking status to “Booked” (status 1)
8. If failed after 3 inquiry attempts:
- Cancel booking (status 8)
Dependencies:
- SQL Server database
- Smart Routing payment gateway
- Scheduling API
- Payment gateway configuration in database
Related Models:
- PendingPayment
- UpdateBookingOrderPayForData
- RequestSecureHash
- RequestProcessInquiry
Success Criteria:
- Payment status updated in database
- Booking status synchronized with payment result
- Transaction logged
Error Handling:
- Exception logging to ServiceLog_Inquiry_[Date].txt
- Automatic retry on next timer interval
- Booking cancellation after 3 failed attempts
2. Refund Processing¶
Feature ID: F-002
Category: Payment Processing
Status: Active
Priority: Critical
Description:
Automated processing of refund requests for cancelled or refunded bookings, including status tracking and notification delivery.
Technical Implementation:
- Timer Interval: 10 minutes (600,000ms)
- Thread: RefundAndInquiryThread
- Entry Point: GetPendingRefundPayment()
- Stored Procedure: ws_GetPendingPaymentsListForRefund_AppConfigSetting
Process Flow:
1. Fetch pending refund requests from database
2. Generate new transaction ID (format: PSY{timestamp})
3. Convert amount to smallest currency unit (cents)
4. Generate secure hash with refund parameters
5. POST refund request to payment gateway
6. Parse gateway response
7. Update refund status in database
8. If successful (StatusCode=00000):
- Authenticate with Psyter API
- Send refund notification to patient and provider
Refund Types Supported:
- Full Refund: Complete booking refund
- Partial Refund: Not currently implemented
- Inquiry-Based Refund: Check refund status (MessageID=2)
Dependencies:
- SQL Server database
- Smart Routing payment gateway
- Psyter API (for notifications)
- Original transaction details
Related Models:
- RequestRefund
- UpdateBookingRefundRequestData
- RefundBookingNotificationRequest
Success Criteria:
- Refund transaction submitted to gateway
- Refund status updated in database
- Notification sent to affected parties
Error Handling:
- Exception logging to ServiceLog_Refund_[Date].txt
- Status tracking for failed refunds
- Automatic retry on next cycle
3. Wallet Purchase Payment Inquiry¶
Feature ID: F-003
Category: Payment Processing
Status: Active
Priority: High
Description:
Verification of wallet recharge payments to ensure funds are properly credited to user accounts.
Technical Implementation:
- Timer Interval: 10 minutes (600,000ms)
- Entry Point: GetPendingWalletPurchasedPayment()
- Stored Procedure: ws_GetPendingWalletPurchasesList_AppConfigSetting
Process Flow:
1. Fetch pending wallet purchase transactions
2. Generate inquiry secure hash
3. Query payment gateway for transaction status
4. Update wallet purchase status
5. Credit wallet if payment successful
Data Elements:
- UserWalletId
- TransactionId
- PayForDataId
- Purchase amount
- Payment status
Dependencies:
- SQL Server database
- Smart Routing payment gateway
- User wallet system
Related Models:
- PendingPayment (with UserWalletId)
- UpdateBookingOrderPayForData
Success Criteria:
- Wallet purchase status confirmed
- Funds credited to user wallet
- Transaction recorded
4. Package Purchase Payment Inquiry¶
Feature ID: F-004
Category: Payment Processing
Status: Active
Priority: High
Description:
Verification of subscription package purchases to activate user packages and grant access to services.
Technical Implementation:
- Timer Interval: 10 minutes (600,000ms)
- Entry Point: GetPendingPackagePurchasedPayment()
- Stored Procedure: ws_GetPendingPackagePaymentsList_AppConfigSetting
Process Flow:
1. Fetch pending package purchase transactions
2. Generate inquiry secure hash
3. Query payment gateway for transaction status
4. Update package purchase status
5. Activate package if payment successful
Data Elements:
- ClientPackageMainId
- TransactionId
- PayForDataId
- Package details
- Payment status
Dependencies:
- SQL Server database
- Smart Routing payment gateway
- Package management system
Related Models:
- PendingPayment (with ClientPackageMainId)
- UpdateBookingOrderPayForData
Success Criteria:
- Package purchase confirmed
- Package activated for user
- Access granted to package features
5. FCM Notification Delivery¶
Feature ID: F-005
Category: Notifications
Status: Active
Priority: High
Description:
Sends Firebase Cloud Messaging (FCM) push notifications for general user notifications.
Technical Implementation:
- Timer Interval: 10 minutes (600,000ms)
- Thread: SendFCMNotifications
- Entry Point: GetPendingFCMNotificationsAndReminders()
- Stored Procedure: Notification_GetNotificationsListToSentUsingFCM
Process Flow:
1. Fetch pending notifications from database
2. Build FCM notification payload
3. Call Psyter API to send notification
4. Mark notification as sent in database
Notification Types:
- General notifications (NotificationType=11)
- System announcements
- User alerts
Data Elements:
- NotificationTitle
- NotificationBody
- FCMTopic (user-specific topic)
- ForUserLoginInfoId
Dependencies:
- SQL Server database
- Psyter API
- FCM (via Psyter API)
Related Models:
- UserNotification
- SendCustomFCMNotification
- FCMConfiguration
Success Criteria:
- Notification delivered via FCM
- Notification marked as sent
- Delivery logged
6. Appointment Reminder System¶
Feature ID: F-006
Category: Notifications
Status: Active
Priority: Critical
Description:
Sends automated appointment reminders to patients and healthcare providers before scheduled appointments.
Technical Implementation:
- Timer Interval: 10 minutes (600,000ms)
- Thread: SendFCMNotifications
- Entry Point: GetPendingFCMNotificationsAndReminders()
- Stored Procedure: Notification_GetNotificationsListToSentUsingFCM
Process Flow:
1. Fetch due reminders from database
2. Determine user type (Patient=1, Provider=0)
3. Fetch complete reminder list for booking
4. Build rich FCM payload with:
- User/Provider details
- Booking information
- Video meeting ID
- Slot datetime
- Communication type
- All reminder times for this booking
5. Authenticate with Psyter API
6. POST notification to Psyter API
7. Mark reminder as sent
8. Create notification log entry
Reminder Data Included:
For Patient Reminders (UserType=1):
{
ClientUserLoginInfoId,
ClientFirstNamePLang, ClientLastNamePLang,
ClientFirstNameSLang, ClientLastNameSLang,
NotificationType: 12,
Message (PLang), MessageSLang,
VideoSDKMeetingId,
SlotBookingId,
ReminderBeforeMinutes,
SlotDateTimeUTC,
UserType: 1,
CatCommunicationTypeId,
RemindersList: [Array of all reminders]
}
For Provider Reminders (UserType=0):
{
ProviderUserLoginInfoId,
ProviderFirstNamePLang, ProviderLastNamePLang,
ProviderFirstNameSLang, ProviderLastNameSLang,
NotificationType: 12,
Message (PLang), MessageSLang,
VideoSDKMeetingId,
SlotBookingId,
ReminderBeforeMinutes,
SlotDateTimeUTC,
UserType: 0,
CatCommunicationTypeId,
RemindersList: [Array of all reminders]
}
Reminder Timing Options:
- Custom minutes before appointment
- Multiple reminders per booking
- Bilingual support (Primary/Secondary language)
Dependencies:
- SQL Server database
- Psyter API
- FCM (via Psyter API)
- Video SDK integration
Related Models:
- UserReminder
- UserReminderForFCMPayLoad
- SendCustomFCMNotification
Success Criteria:
- Reminder delivered before appointment time
- Both patient and provider notified
- Reminder marked as sent
- Notification log created
7. SCHFS Card Expiry Notifications¶
Feature ID: F-007
Category: Notifications
Status: Active
Priority: Medium
Description:
Daily check and notification for users with expiring Saudi Council for Health Insurance (SCHFS) insurance cards.
Technical Implementation:
- Timer Interval: 24 hours (86,400,000ms)
- Thread: NotifySCHFSCardExpiryThread
- Entry Point: CallNotifySCHFSExpiryAPI()
- API Endpoint: /Notification/NotifySCHFSCardExpiry
Process Flow:
1. Timer triggers daily
2. Retrieve Psyter API application token
3. Authenticate with Psyter API
4. GET request to SCHFS expiry endpoint
5. Psyter API handles notification logic
6. Log response
Data Elements:
- SCHFS card expiry dates
- User contact information
- Notification preferences
Dependencies:
- SQL Server database (for API token)
- Psyter API
- SCHFS card data in database
Related Models:
- APIAuthTokenResponse
Success Criteria:
- Daily execution confirmed
- Users notified of expiring cards
- Notification logged
Error Handling:
- Exception logging to ServiceLog_NotifySCHFSCardExpiry_[Date].txt
- Automatic retry next day
8. Log File Management¶
Feature ID: F-008
Category: System Maintenance
Status: Active
Priority: Low
Description:
Automated cleanup of old log files to prevent disk space issues and maintain system performance.
Technical Implementation:
- Timer Interval: 15 days (1,296,000,000ms)
- Thread: DeleteLogFilesThread
- Entry Point: DeleteLogFilesOfPreviousMonth()
Process Flow:
1. Timer triggers every 15 days
2. Scan Logs\ directory
3. Identify files older than 30 days
4. Delete old files (except DeleteFileLog itself)
5. Log each deletion
Retention Policy:
- Retention Period: 30 days
- Cleanup Frequency: Every 15 days
- Protected Files: ServiceLog_DeleteFileLog_*.txt
Log File Types:
- ServiceLog_Inquiry_[Date].txt
- ServiceLog_Refund_[Date].txt
- ServiceLog_NotifySCHFSCardExpiry_[Date].txt
- ServiceLog_DeleteFileLog_[Date].txt
- ServiceLog_SendFCMNotificationAndReminders_[Date].txt
Dependencies:
- File system access
- Logs directory
Success Criteria:
- Old logs deleted
- Disk space freed
- Deletion logged
Error Handling:
- Exception logging
- Non-critical failures ignored
9. Secure Hash Generation¶
Feature ID: F-009
Category: Security
Status: Active
Priority: Critical
Description:
SHA256-based secure hash generation for payment gateway authentication and request verification.
Technical Implementation:
- Algorithm: SHA256
- Entry Point: GenerateSecureHash()
- Usage: All payment gateway requests
Hash Components:
For Inquiry (MessageID=2):
SecretKey + MessageID + OriginalTransactionID + MerchantID + Version
For Refund (MessageID=4):
SecretKey + MessageID + TransactionID + Amount + CurrencyISOCode + OriginalTransactionID + MerchantID + Version
Implementation:
1. Create SortedDictionary with parameters
2. Build ordered string: SecretKey + sorted values
3. Convert to UTF-8 bytes
4. Compute SHA256 hash
5. Convert to hexadecimal string
6. Return as SECURE_HASH
Dependencies:
- Payment gateway secret key
- Transaction parameters
- Merchant configuration
Related Models:
- RequestSecureHash
- SecureHashResponse
Success Criteria:
- Hash matches gateway expectations
- Request authenticated by gateway
- Tamper-proof request data
10. API Authentication Management¶
Feature ID: F-010
Category: Integration
Status: Active
Priority: Critical
Description:
OAuth2-style token-based authentication for Psyter and Scheduling APIs with automatic token refresh.
Technical Implementation:
- Entry Points:
- PsyterApiAuthenticationToken()
- SchedulingApiAuthenticationToken()
- Token Storage: In-memory (service properties)
- Refresh Strategy: On each service cycle
Authentication Flow:
1. Retrieve application token from database
2. POST to /Authenticate endpoint
- applicationtoken: {token}
- grant_type: password
3. Parse JSON response
4. Extract: access_token, refresh_token, expires_in
5. Store in service property
6. Use in Authorization header: Bearer {access_token}
Token Lifecycle:
- Acquisition: On first API call in cycle
- Storage: Service class properties
- Usage: Authorization header for API requests
- Refresh: Every 10 minutes (new token acquired)
- Expiration: Not tracked (refreshed before expiry)
APIs Using Authentication:
Psyter API:
- /Notification/SendRefundBookingNotification
- /Notification/SendNotificationWithCustomData
- /Notification/NotifySCHFSCardExpiry
Scheduling API:
- /api/Schedule/UpdateBookingStatus
Dependencies:
- Application tokens in database
- API availability
- Network connectivity
Related Models:
- APIAuthTokenResponse
Success Criteria:
- Token acquired successfully
- API calls authenticated
- No 401 errors
Error Handling:
- Exception logging
- Retry on next cycle
- API calls fail gracefully
11. Booking Status Synchronization¶
Feature ID: F-011
Category: Integration
Status: Active
Priority: Critical
Description:
Synchronizes booking status with Scheduling API based on payment verification results.
Technical Implementation:
- Entry Point: UpdateBookingStatusInScheduling()
- API Endpoint: /api/Schedule/UpdateBookingStatus
- Method: POST with JSON payload
Status Update Scenarios:
Payment Successful (StatusCode=00000):
NewBookingStatusId: 1 (Booked)
StatusUpdateAuthority: 2
UpdatedBy: ConsumerId
Payment Failed (InquiryCount >= 3):
NewBookingStatusId: 8 (Cancelled)
StatusUpdateAuthority: 2
UpdatedBy: ConsumerId
CancelledBy: ConsumerId
Request Payload:
{
"BookingStatusUpdateInfoList": [
{
"BookingId": 123,
"NewBookingStatusId": 1,
"StatusUpdateDateTime": "2025-11-10T10:00:00Z",
"StatusUpdateAuthority": 2,
"UpdatedBy": 456,
"CancelledBy": null
}
]
}
Response Handling:
{
"reason": 1, // Success
"data": {
"BookingStatusUpdateInfoList": [
{
"BookingId": 123,
"NewBookingStatusId": 1,
"RejectCode": null,
"RejectReason": null
}
]
}
}
Special Cases:
- RejectCode=7: Status already “Booked” → Proceed with payment update
- Other RejectCodes: Log and skip payment update
Dependencies:
- Scheduling API
- Valid booking IDs
- Authentication token
Related Models:
- UpdateScheduleBookingStatusRequest
- UpdateBookingStatus
- BookingStatusUpdateResponseWrapper
Success Criteria:
- Booking status updated in Scheduling system
- Payment status synchronized
- Audit trail maintained
12. Refund Notification Distribution¶
Feature ID: F-012
Category: Notifications
Status: Active
Priority: High
Description:
Sends notifications to patients and healthcare providers when refunds are processed successfully.
Technical Implementation:
- Entry Point: CallRefundNotificationAPI()
- API Endpoint: /Notification/SendRefundBookingNotification
- Method: POST with JSON payload
Notification Payload:
{
"BookingId": 123,
"CareProviderId": 456,
"PatientId": 789,
"NoNeedToCreateLog": true
}
Notification Recipients:
- Patient who made the booking
- Healthcare provider for the appointment
Notification Content (handled by Psyter API):
- Refund amount
- Original booking details
- Refund transaction ID
- Refund status
Dependencies:
- Psyter API
- Valid booking details
- User contact information
- Authentication token
Related Models:
- RefundBookingNotificationRequest
Success Criteria:
- Both parties notified
- Notification delivered via configured channels
- Log created (if not suppressed)
13. Multi-Language Support¶
Feature ID: F-013
Category: Localization
Status: Active
Priority: Medium
Description:
Bilingual notification support for Primary Language (PLang) and Secondary Language (SLang).
Implementation Areas:
Reminder Notifications:
- ReminderTitle / ReminderTitleSLang
- ReminderTextPLang / ReminderTextSLang
User Names:
- FirstNamePLang / FirstNameSLang
- LastNamePLang / LastNameSLang
Application Configuration:
- TitlePLang / TitleSLang for settings
Language Pairs Supported:
- Likely Arabic (Primary) and English (Secondary)
- Or English (Primary) and Arabic (Secondary)
Dependencies:
- Database schema with PLang/SLang columns
- Client applications supporting bilingual display
Success Criteria:
- Both languages included in notifications
- Client can display appropriate language
- Consistent language usage
Feature Dependencies Matrix¶
| Feature | SQL Server | Payment Gateway | Psyter API | Scheduling API | FCM |
|---|---|---|---|---|---|
| Payment Inquiry (F-001) | ✓ | ✓ | ✗ | ✓ | ✗ |
| Refund Processing (F-002) | ✓ | ✓ | ✓ | ✗ | ✗ |
| Wallet Inquiry (F-003) | ✓ | ✓ | ✗ | ✗ | ✗ |
| Package Inquiry (F-004) | ✓ | ✓ | ✗ | ✗ | ✗ |
| FCM Notifications (F-005) | ✓ | ✗ | ✓ | ✗ | ✓ |
| Appointment Reminders (F-006) | ✓ | ✗ | ✓ | ✗ | ✓ |
| SCHFS Notifications (F-007) | ✓ | ✗ | ✓ | ✗ | ✓ |
| Log Management (F-008) | ✗ | ✗ | ✗ | ✗ | ✗ |
| Secure Hash (F-009) | ✗ | ✓ | ✗ | ✗ | ✗ |
| API Auth (F-010) | ✓ | ✗ | ✓ | ✓ | ✗ |
| Booking Sync (F-011) | ✗ | ✗ | ✗ | ✓ | ✗ |
| Refund Notifications (F-012) | ✗ | ✗ | ✓ | ✗ | ✓ |
| Multi-Language (F-013) | ✓ | ✗ | ✗ | ✗ | ✗ |
Integration Points¶
1. SQL Server Database¶
Connection: Enterprise Library Database Factory
Connection String: PsyterDatabase
Stored Procedures Used:
1. ws_GetPendingPaymentsList_AppConfigSetting
2. ws_GetPendingPaymentsListForRefund_AppConfigSetting
3. ws_GetPendingWalletPurchasesList_AppConfigSetting
4. ws_GetPendingPackagePaymentsList_AppConfigSetting
5. ws_UpdatePaymentInquiryStatus
6. ws_UpdatePendingPaymentRefundStatus
7. ws_UpdateWalletPurchasePaymentInquiryStatus
8. ws_UpdatePackagePaymentInquiryStatus
9. AppConfig_GetAppConfigSettingsByGroupId
10. Notification_GetNotificationsListToSentUsingFCM
11. Notification_UpdateNotificationSentStatus
12. Reminder_UpdateReminderSentStatus
13. Reminder_GetUserReminderList
Data Operations:
- SELECT: Fetch pending items, configuration
- UPDATE: Payment status, notification status
- INSERT: Notification logs (via stored procedures)
2. Smart Routing Payment Gateway¶
Endpoint: Retrieved from database (SmartRoutingRefundInquiryUrl)
Authentication: Secure hash (SHA256)
Protocol: HTTPS POST
Request Types:
- Inquiry (MessageID=2): Check payment status
- Refund (MessageID=4): Process refund
Request Format: Form-encoded (NameValueCollection)
Response Format: Query string
Response.StatusCode=00000&Response.StatusDescription=Success&Response.CardHolderName=...
Configuration Parameters:
- SmartRoutingSecretKey
- SmartRoutingMerchantId
- SmartRoutingCurrencyISOCode
- SmartRoutingVersion
- SmartRoutingRefundInquiryUrl
3. Psyter API¶
Base URL: Configured in App.config
Authentication: OAuth2 Bearer token
Protocol: HTTPS
Data Format: JSON
Endpoints Used:
- POST /Authenticate - Get access token
- POST /Notification/SendRefundBookingNotification - Refund notifications
- POST /Notification/SendNotificationWithCustomData - FCM notifications
- GET /Notification/NotifySCHFSCardExpiry - SCHFS notifications
Token Management:
- Application token stored in database
- Access token refreshed every 10 minutes
- Bearer token in Authorization header
4. Scheduling API¶
Base URL: Configured in App.config
Authentication: OAuth2 Bearer token
Protocol: HTTPS
Data Format: JSON
Endpoints Used:
- POST /Authenticate - Get access token
- POST /api/Schedule/UpdateBookingStatus - Update booking status
Token Management:
- Application token stored in database
- Access token refreshed every 10 minutes
- Bearer token in Authorization header
5. Firebase Cloud Messaging (FCM)¶
Access: Via Psyter API (indirect)
Configuration: Retrieved from database
Notification Types:
- Type 11: General notifications
- Type 12: Appointment reminders
Delivery Method:
- Topic-based messaging
- User-specific topics
Configuration Dependencies¶
Database Configuration (AppConfigSettings table)¶
Required settings retrieved at runtime:
| Setting | Purpose | Used By |
|---|---|---|
| SmartRoutingSecretKey | Gateway authentication | F-001, F-002, F-003, F-004, F-009 |
| SmartRoutingMerchantId | Merchant identification | F-001, F-002, F-003, F-004 |
| SmartRoutingRefundInquiryUrl | Gateway endpoint | F-001, F-002, F-003, F-004 |
| SmartRoutingCurrencyISOCode | Currency code | F-002 |
| SmartRoutingVersion | API version | F-001, F-002, F-003, F-004 |
| Application API Token (GroupId=2) | API authentication | F-010 |
App.config Dependencies¶
API Base URLs:
<add key="PsyterAPIBaseURL" value="..." />
<add key="SchedulingAPIBaseURL" value="..." />
Database Connection:
<add name="PsyterDatabase" connectionString="..." />
Technical Debt & Missing Features¶
Current Limitations¶
-
No Partial Refund Support
- Only full refunds implemented
- Partial refund logic not present -
Single-Threaded Processing
- One thread per operation type
- Sequential processing of items
- No parallelization -
No Retry Logic for Failed API Calls
- Failed calls rely on next timer cycle
- No exponential backoff
- No immediate retry mechanism -
No Notification Delivery Confirmation
- Assumes FCM delivery successful
- No delivery receipt tracking
- No failed notification retry -
No Health Monitoring
- No service health endpoint
- No metrics collection
- No alerting mechanism -
No Circuit Breaker Pattern
- No protection against cascading failures
- No automatic service degradation
- Continuous retry even if service down -
Hardcoded SSL Certificate Bypass
-AllwaysGoodCertificatereturns true for all certificates
- Security risk in production
- Should validate certificates
Potential Enhancements¶
-
Batch Processing
- Process multiple payments in parallel
- Batch database updates
- Improve throughput -
Dead Letter Queue
- Store failed operations for manual review
- Separate handling for different failure types
- Administrative interface for retry -
Metrics & Monitoring
- Performance counters
- Success/failure rates
- Processing time tracking
- Dashboard integration -
Configuration Management
- Encrypted configuration
- External configuration provider
- Dynamic configuration reload -
Advanced Logging
- Structured logging (JSON)
- Log aggregation support
- Log levels (Debug, Info, Warn, Error)
- Correlation IDs
Feature Roadmap¶
Implemented ✓¶
- Payment inquiry for bookings
- Refund processing
- Wallet purchase inquiry
- Package purchase inquiry
- FCM notifications
- Appointment reminders
- SCHFS expiry notifications
- Log file management
- Secure hash generation
- API authentication
- Booking status sync
- Multi-language support
In Scope (Not Implemented)¶
- Partial refunds
- Parallel processing
- Advanced error handling
- Health monitoring
- Metrics collection
Out of Scope¶
- User interface
- Direct FCM integration
- Email notifications
- SMS notifications
- Report generation
Document Version: 1.0
Last Updated: November 10, 2025
Total Features Documented: 13 core features
Integration Points: 5 external systems
Dependencies: 13 stored procedures, 4 APIs