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

Project: Psyter REST API Backend
Technology: ASP.NET Web API 2 (.NET Framework 4.7.2)
Platform: IIS / Azure App Service
Authentication: OAuth 2.0 (Bearer Token)
Last Updated: November 5, 2025


📁 Root Structure

APIs/
├── PsyterAPI/                     # Main API project
│   ├── App_Start/                 # Application startup configuration
│   ├── Common/                    # Shared utilities and helpers
│   ├── Controllers/               # API endpoint controllers
│   ├── Models/                    # Data models (Request/Response/Entities)
│   ├── Providers/                 # OAuth providers
│   ├── Repositories/              # Data access layer
│   ├── Properties/                # Assembly info
│   ├── bin/                       # Compiled binaries
│   ├── obj/                       # Build objects
│   ├── firebase-adminsdk.json     # Firebase service account (dev)
│   ├── firebase-adminsdk-live.json # Firebase service account (prod)
│   ├── Global.asax                # Application entry point
│   ├── Web.config                 # Configuration file
│   ├── log4net.config             # Logging configuration
│   ├── MerchantCertificates.p12   # Payment gateway certificate
│   ├── packages.config            # NuGet packages
│   └── PsyterAPI.csproj           # Project file
├── packages/                      # NuGet packages cache
├── PsyterAPI.sln                  # Solution file
└── azure-pipelines.yml            # CI/CD pipeline configuration

🎯 Project Overview

Purpose

Central REST API backend serving all Psyter client applications:
- Android Client app
- Android Care Provider app
- iOS apps
- Web portal
- Administrative systems

Architecture Pattern

  • Pattern: Repository Pattern with Service Layer
  • Data Access: ADO.NET with Stored Procedures
  • Authentication: OAuth 2.0 with JWT Bearer Tokens
  • Authorization: Custom claims-based authorization
  • Logging: Log4Net
  • Error Handling: Global exception handler middleware
  • Security: Anti-XSS validation, CORS, secure headers

⚙️ Configuration (Web.config)

Application Settings

Key Configurations:

<appSettings>
    <add key="commandTimeout" value="600"/>
    <add key="SchedulerApiUri" value="https://dvx.innotech-sa.com/Scheduling/SchedulingAPI/authenticate"/>
    <add key="MaxFileSize" value="104857600"/> <!-- 100 MB -->
    <add key="origins" value="https://dvx.innotech-sa.com,http://localhost:37113"/>
    <add key="applyCORS" value="true"/>
</appSettings>

Purpose:
- commandTimeout: SQL command timeout (10 minutes for complex queries)
- SchedulerApiUri: External scheduling API endpoint
- MaxFileSize: Maximum upload size (100 MB for documents, videos)
- origins: CORS allowed origins
- applyCORS: Enable/disable CORS globally

Connection Strings

Databases:
1. PsyterDatabase: Main application database (encrypted)
- User accounts
- Profiles
- Appointments
- Content
- Payments

  1. SchedulingDatabase: Scheduling system database (encrypted)
    - Provider availability
    - Time slots
    - Bookings
    - Calendar events

Environments:
- Dev/Staging: dvx.innotech-sa.com
- Production: psyter.com (commented out, switchable)

Note: Connection strings are encrypted using machine keys for security

Security Configuration

Machine Key:

<machineKey 
    decryption="AES" 
    validation="HMACSHA256"
    decryptionKey="[ENCRYPTED]"
    validationKey="[ENCRYPTED]"/>

Purpose:
- Encrypt/decrypt connection strings
- Validate authentication cookies
- Secure view state
- Token generation/validation

Request Limits:

<httpRuntime maxRequestLength="104857600" targetFramework="4.5"/>

- Max request size: 100 MB (for file uploads)

Custom Errors:

<customErrors mode="Off"/>

- Disabled for detailed error messages (should be “On” in production)


📦 Dependencies (NuGet Packages)

Core Framework

  • ASP.NET Web API: 5.2.7
  • ASP.NET MVC: 5.2.3
  • .NET Framework: 4.7.2

Authentication & Security

  • Microsoft.Owin: 3.1.0 (OWIN middleware)
  • Microsoft.Owin.Security.OAuth: 3.1.0 (OAuth 2.0)
  • JWT: 10.1.1 (JSON Web Tokens)

Firebase Integration

  • FirebaseAdmin: 3.0.0 (Admin SDK)
  • Google.Apis.Auth: 1.68.0 (Google authentication)
  • Google.Apis.FirebaseCloudMessaging.v1: 1.68.0.3431 (FCM)

Data & Serialization

  • Newtonsoft.Json: 13.0.3 (JSON serialization)
  • AutoMapper: 7.0.1 (Object mapping)
  • System.Data.SqlClient: Built-in (ADO.NET)

Document Generation

  • iTextSharp: 5.5.13.3 (PDF generation)
  • itextsharp.xmlworker: 5.5.13.3 (HTML to PDF)

Utilities

  • log4net: 2.0.8 (Logging)
  • QRCoder: 1.4.3 (QR code generation)
  • BouncyCastle: 1.8.9 (Cryptography)

Google Services

  • Google.Api.Gax: 4.8.0 (Google API extensions)
  • Google.Apis.Core: 1.68.0 (Google APIs core)

🚀 Application Startup

Global.asax.cs

File: Global.asax.cs

Purpose: Application lifecycle management

Initialization:

void Application_Start(object sender, EventArgs e)
{
    // Enable TLS 1.2 for email sending
    ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

    // Configure Web API routes
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // Register MVC areas
    AreaRegistration.RegisterAllAreas();

    // Register MVC routes
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Key Functions:
1. Enable TLS 1.2 for secure email communication
2. Register Web API routes and configuration
3. Register MVC areas (if any)
4. Configure MVC routing (for documentation/admin views)


🛣️ App_Start Configuration

1. WebApiConfig.cs

File: App_Start/WebApiConfig.cs

Purpose: Web API configuration and route setup

Key Configurations:
- Routing: Attribute-based routing enabled
- JSON Serialization: Camel case, ignore null values
- CORS: Cross-origin resource sharing setup
- Filters: Global exception handler, validation filters
- Formatters: Remove XML formatter, keep JSON only
- Dependency Injection: Setup if using IoC container

Typical Setup:

public static void Register(HttpConfiguration config)
{
    // Enable attribute routing
    config.MapHttpAttributeRoutes();

    // JSON serialization settings
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

    // Remove XML formatter
    config.Formatters.Remove(config.Formatters.XmlFormatter);

    // Global filters
    config.Filters.Add(new GlobalExceptionHandler());
    config.Filters.Add(new ValidateModelStateFilter());

    // CORS
    if (ConfigurationManager.AppSettings["applyCORS"] == "true")
    {
        var cors = new EnableCorsAttribute(
            origins: ConfigurationManager.AppSettings["origins"],
            headers: "*",
            methods: "*"
        );
        config.EnableCors(cors);
    }
}

2. Startup.cs (OWIN)

File: App_Start/Startup.cs

Purpose: OWIN middleware configuration for OAuth 2.0

Configuration:
- OAuth Server: Token generation endpoint
- Token Expiration: Access token lifetime
- Refresh Tokens: Refresh token support
- Providers: Custom authorization server provider
- CORS: Cross-domain authentication

OAuth Setup:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true, // HTTPS only in production
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
            Provider = new MyAuthorizationServerProvider(),
            RefreshTokenProvider = new RefreshTokenProvider()
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

3. RouteConfig.cs

File: App_Start/RouteConfig.cs

Purpose: MVC route configuration (for admin/documentation views)


🔐 Authentication & Authorization

OAuth 2.0 Implementation

1. MyAuthorizationServerProvider.cs

File: Providers/MyAuthorizationServerProvider.cs

Purpose: Custom OAuth authorization server

Key Methods:

ValidateClientAuthentication:

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    // Validate client credentials
    context.Validated();
}

GrantResourceOwnerCredentials:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    // Validate user credentials
    var userRepository = new UserRepository();
    var user = userRepository.ValidateUser(context.UserName, context.Password);

    if (user == null)
    {
        context.SetError("invalid_grant", "Invalid username or password");
        return;
    }

    // Create claims identity
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim("sub", user.UserId));
    identity.AddClaim(new Claim("userLoginInfoId", user.UserLoginInfoId.ToString()));
    identity.AddClaim(new Claim("userType", user.UserType.ToString()));
    identity.AddClaim(new Claim("email", user.Email));

    context.Validated(identity);
}

Purpose:
- Validate username/password
- Generate access token
- Create claims for authorization
- Return token to client

2. RefreshTokenProvider.cs

File: Providers/RefreshTokenProvider.cs

Purpose: Refresh token management

Functionality:
- Generate refresh tokens
- Store refresh tokens in database
- Validate refresh tokens
- Revoke expired tokens
- Refresh access tokens without re-login

3. Custom Authorization Attributes

AuthorizeAttribute.cs

File: Common/AuthorizeAttribute.cs

Purpose: Base authorization attribute

Usage:

[Common.Authorize]
[Route("User/GetProfile")]
public IHttpActionResult GetProfile()
{
    // Requires valid bearer token
}

ValidateCareProviderOrClientClaim

File: Common/ValidateUserClaimFilter.cs

Purpose: Role-based authorization

Usage:

[ValidateCareProviderOrClientClaim]
[Route("ServiceProvider/GetProfile/{userLoginInfoId}")]
public IHttpActionResult GetProfile(long userLoginInfoId)
{
    // Requires user to be care provider OR client
    // Validates user can only access their own data
}

Claims Validated:
- userType: Client (1) or CareProvider (2)
- userLoginInfoId: Must match requested resource
- Token expiration
- Token revocation status


📊 Data Access Layer

Repository Pattern

BaseRepository.cs

File: Repositories/BaseRepository.cs

Purpose: Base repository with common database operations

Key Methods:

ExecuteStoredProcedure:

protected DataTable ExecuteStoredProcedure(string procedureName, params SqlParameter[] parameters)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand(procedureName, connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandTimeout = commandTimeout;
            command.Parameters.AddRange(parameters);

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

            return dataTable;
        }
    }
}

ExecuteNonQuery:

protected int ExecuteNonQuery(string procedureName, params SqlParameter[] parameters)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand(procedureName, connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandTimeout = commandTimeout;
            command.Parameters.AddRange(parameters);

            connection.Open();
            int rowsAffected = command.ExecuteNonQuery();
            connection.Close();

            return rowsAffected;
        }
    }
}

ExecuteScalar:

protected object ExecuteScalar(string procedureName, params SqlParameter[] parameters)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand command = new SqlCommand(procedureName, connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandTimeout = commandTimeout;
            command.Parameters.AddRange(parameters);

            connection.Open();
            object result = command.ExecuteScalar();
            connection.Close();

            return result;
        }
    }
}

Common Features:
- Connection string decryption
- Command timeout configuration
- Parameter binding
- Exception handling
- Connection disposal
- Transaction support

DBConstant.cs

File: Repositories/DBConstant.cs

Purpose: Stored procedure name constants

Structure:

public class DbConstant
{
    // User Management
    public const string USER_AUTHENTICATE = "User_Authenticate";
    public const string USER_REGISTER = "User_Register";
    public const string USER_UPDATE_PROFILE = "User_UpdateProfile";

    // Service Provider
    public const string SP_GET_PERSONAL_INFO = "SP_GetPersonalInfo";
    public const string SP_UPDATE_PERSONAL_INFO = "SP_UpdatePersonalInfo";
    public const string SP_GET_GENERAL_ACCESS_DETAILS = "SP_GetGeneralAccessDetails";

    // Patient/Client
    public const string PATIENT_GET_SCREENING_QUESTIONS = "Patient_GetScreeningQuestionAndOption";
    public const string PATIENT_SAVE_SCREENING_ANSWERS = "Patient_SaveScreeningQuestionAnswers";

    // Scheduling
    public const string SCHEDULING_GET_SLOTS = "Scheduling_GetAvailableSlots";
    public const string SCHEDULING_BOOK_APPOINTMENT = "Scheduling_BookAppointment";

    // Messaging
    public const string MESSAGE_SEND = "Message_Send";
    public const string MESSAGE_GET_CONVERSATIONS = "Message_GetConversations";

    // Payments
    public const string PAYMENT_PROCESS = "Payment_Process";
    public const string PAYMENT_REFUND = "Payment_Refund";

    // And 400+ more stored procedure constants...
}

Benefits:
- Type safety (compile-time checking)
- Centralized maintenance
- Easy refactoring
- Prevents typos
- IntelliSense support


🎮 Controllers Overview

Structure

All controllers inherit from BaseController and follow RESTful conventions:
- Route Prefix: Controller-specific ([RoutePrefix("User")])
- HTTP Verbs: GET, POST, PUT, DELETE
- Authorization: [Common.Authorize] attribute
- Validation: [ValidateAntiXSS] attribute
- Claims Validation: [ValidateCareProviderOrClientClaim]

1. UserController.cs

File: Controllers/UserController.cs
Route Prefix: /User
Lines of Code: 2,184

Purpose: User account management

Key Endpoints:

Authentication

POST /User/UserLogin
- Purpose: Authenticate user with username/password
- Request: UserAuthRequest (username, password, recaptcha)
- Response: UserLoginResponse (token, user info, status)
- Security: reCAPTCHA validation, rate limiting
- Authorization: Basic (no bearer token required)

POST /User/UserSocialLogin
- Purpose: Authenticate via social providers (Google, Facebook)
- Request: UserSocialLoginRequest (social token, provider type)
- Response: UserLoginResponse
- Providers: Google, Facebook, Apple

GET /User/GetUserLoginDetails/{userLoginInfoId}
- Purpose: Get detailed user login information
- Authorization: Bearer token required
- Claims: Must match userLoginInfoId in token

Registration

POST /User/RegisterUser
- Purpose: Register new user (client or provider)
- Request: UserRegistrationRequest
- Response: UserRegistrationResponse
- Steps:
1. Validate email/phone
2. Check existing account
3. Send verification code
4. Create account (pending verification)
5. Return user ID

POST /User/VerifyAccount
- Purpose: Verify phone/email with OTP code
- Request: VerificationRequest (userId, code)
- Response: BaseResponse (success/failure)

Profile Management

GET /User/GetUserProfile/{userLoginInfoId}
- Purpose: Get complete user profile
- Response: UserProfileInfoResponse
- Includes:
- Personal information
- Contact details
- Profile photo
- Preferences
- Settings

PUT /User/UpdateUserProfile
- Purpose: Update user profile
- Request: UserProfile object
- Validation: Field validation, file size limits
- Response: Success/failure status

POST /User/UploadProfileImage
- Purpose: Upload profile photo
- Request: Multipart form data
- Max Size: 5 MB
- Formats: JPG, PNG, GIF
- Processing:
- Resize to multiple sizes (thumbnail, medium, large)
- Upload to FTP server
- Update database with URLs

Password Management

POST /User/ForgotPassword
- Purpose: Request password reset
- Request: ForgotPasswordRequest (email/phone)
- Process:
1. Validate user exists
2. Generate reset code
3. Send email/SMS
4. Store code with expiration

POST /User/ResetPassword
- Purpose: Reset password with code
- Request: ResetPasswordRequest (code, new password)
- Validation: Code validity, password strength
- Security: Code expires after 15 minutes

POST /User/ChangePassword
- Purpose: Change password (authenticated)
- Request: ChangePasswordRequest (old password, new password)
- Validation: Old password verification

Preferences & Settings

GET /User/GetUserPreferences/{userLoginInfoId}
- Purpose: Get user preferences
- Response: UserPreference object
- Settings:
- Notifications
- Language
- Time zone
- Privacy

PUT /User/UpdateUserPreferences
- Purpose: Update preferences
- Request: UserPreference object

Device Management

POST /User/RegisterDevice
- Purpose: Register device for push notifications
- Request: DeviceRegistrationRequest (FCM token, device info)
- Storage: Links FCM token to user account

POST /User/UnregisterDevice
- Purpose: Remove device registration
- Request: Device ID or FCM token

Account Actions

DELETE /User/DeleteAccount/{userLoginInfoId}
- Purpose: Soft delete user account
- Process:
1. Mark account as deleted
2. Anonymize personal data
3. Cancel active appointments
4. Revoke tokens
- Note: Data retained for legal compliance (30 days)

POST /User/ReportUser
- Purpose: Report inappropriate user behavior
- Request: ReportRequest (reported user ID, reason, description)
- Admin Review: Flags account for review

GET /User/GetUserStatistics/{userLoginInfoId}
- Purpose: Get user activity statistics
- For Clients:
- Total sessions
- Upcoming appointments
- Homework completion rate
- For Providers:
- Total clients
- Sessions this month
- Revenue statistics
- Average rating


2. ServiceProviderController.cs

File: Controllers/ServiceProviderController.cs
Route Prefix: /ServiceProvider
Lines of Code: 2,833

Purpose: Care provider profile and service management

Key Endpoints:

General Access & Profile

GET /ServiceProvider/GetGeneralAccessDetails/{userLoginInfoId}
- Purpose: Get provider public profile
- Response: GeneralAccessDetailsResponse
- Includes:
- Display name
- Specialization
- Bio
- Years of experience
- Languages spoken
- Available for appointments

PUT /ServiceProvider/UpdateGeneralAccessDetails
- Purpose: Update general access information
- Request: GeneralAccessDetails object

GET /ServiceProvider/GetPersonalInfo/{userLoginInfoId}
- Purpose: Get provider personal information
- Response: PersonalInformationResponse
- Includes:
- Full name
- Date of birth
- Gender
- Contact information
- Address

PUT /ServiceProvider/UpdatePersonalInfo
- Purpose: Update personal information
- Request: PersonalInformation object

Contact Information

GET /ServiceProvider/GetContactInformation/{userLoginInfoId}
- Purpose: Get contact details
- Response: ContactInformationResponse
- Includes:
- Email addresses
- Phone numbers
- Clinic address
- Website
- Social media

PUT /ServiceProvider/UpdateContactInformation
- Purpose: Update contact information
- Request: ContactInformation object

Professional Credentials

GET /ServiceProvider/GetWorkExperience/{userLoginInfoId}
- Purpose: Get work history
- Response: List of WorkExperienceResponse
- Each Entry:
- Organization name
- Position title
- Start/end date
- Description

POST /ServiceProvider/InsertWorkExperience
- Purpose: Add work experience entry
- Request: WorkExperience object

PUT /ServiceProvider/UpdateWorkExperience
- Purpose: Update existing entry
- Request: WorkExperience object with ID

DELETE /ServiceProvider/DeleteWorkExperience/{workExperienceId}
- Purpose: Remove work experience entry

GET /ServiceProvider/GetEducationHistory/{userLoginInfoId}
- Purpose: Get education credentials
- Response: List of EducationHistoryResponse
- Each Entry:
- Degree type
- Institution name
- Field of study
- Graduation year
- Certificate/diploma

POST /ServiceProvider/InsertEducationHistory
PUT /ServiceProvider/UpdateEducationHistory
DELETE /ServiceProvider/DeleteEducationHistory/{educationId}

Documents & Certifications

GET /ServiceProvider/GetCvDetails/{userLoginInfoId}
- Purpose: Get CV and certification files
- Response: CvResponse
- Includes:
- CV file URL
- License certificates
- Certifications
- Training certificates

POST /ServiceProvider/UploadCV
- Purpose: Upload CV file
- Request: Multipart file upload
- Formats: PDF, DOC, DOCX
- Max Size: 10 MB

POST /ServiceProvider/UploadCertificate
- Purpose: Upload certification
- Request: Multipart file upload + metadata
- Metadata:
- Certificate type
- Issuing organization
- Issue date
- Expiry date (if applicable)

DELETE /ServiceProvider/DeleteDocument
- Purpose: Remove uploaded document
- Request: DeleteDocument (document ID)

Services Offered

GET /ServiceProvider/GetUserServices/{userLoginInfoId}
- Purpose: Get services offered by provider
- Response: List of UserServices
- Each Service:
- Service name (e.g., “Individual Therapy”)
- Session duration
- Price
- Currency
- Description
- Active status

POST /ServiceProvider/AddService
- Purpose: Add new service offering
- Request: UserServices object

PUT /ServiceProvider/UpdateService
- Purpose: Update service details
- Request: UserServices object with ID

DELETE /ServiceProvider/DeleteService/{serviceId}
- Purpose: Deactivate service

GET /ServiceProvider/GetServiceCategories
- Purpose: Get available service categories
- Response: List of predefined categories
- Categories:
- Individual Therapy
- Couples Therapy
- Family Therapy
- Group Therapy
- Psychiatric Evaluation
- Medication Management

Availability & Schedule

GET /ServiceProvider/GetProviderAvailability/{userLoginInfoId}
- Purpose: Get provider availability schedule
- Response: Weekly schedule with time slots
- Format:
- Day of week
- Start time
- End time
- Session duration
- Price (if varies by time)

POST /ServiceProvider/SetAvailability
- Purpose: Set recurring availability
- Request: AvailabilityRequest
- Options:
- Recurring weekly pattern
- Specific date ranges
- Different rates for different times

POST /ServiceProvider/BlockTimeSlot
- Purpose: Block specific time for personal use
- Request: Date, start time, end time, reason
- Use Cases:
- Vacation
- Conference
- Personal appointment
- Lunch break

DELETE /ServiceProvider/UnblockTimeSlot/{slotId}
- Purpose: Remove blocked slot

Client Management

GET /ServiceProvider/GetMyClients/{userLoginInfoId}
- Purpose: Get provider’s client list
- Response: List of ClientInfoResponse
- Each Client:
- Client ID
- Name
- Photo
- First session date
- Last session date
- Total sessions
- Next appointment
- Status (Active/Inactive)

GET /ServiceProvider/GetClientProfile/{clientId}
- Purpose: Get detailed client profile
- Authorization: Must be client’s provider
- Response: Complete client information
- Includes:
- Personal info
- Session history
- Diagnoses
- Medications
- Homework status
- Diary entries (if shared)

GET /ServiceProvider/GetClientSessionHistory/{clientId}
- Purpose: Get all sessions with specific client
- Response: List of SessionInfoResponse
- Each Session:
- Date and time
- Duration
- Session type
- Notes available
- Recording available
- Payment status

Appointments

GET /ServiceProvider/GetProviderAppointments/{userLoginInfoId}
- Purpose: Get provider’s appointments
- Query Params:
- startDate, endDate: Date range filter
- status: Filter by status (scheduled, completed, cancelled)
- Response: List of AppointmentResponse

GET /ServiceProvider/GetAppointmentDetails/{appointmentId}
- Purpose: Get specific appointment details
- Authorization: Must be appointment provider

PUT /ServiceProvider/UpdateAppointmentStatus
- Purpose: Update appointment status
- Request: UpdateAppointmentRequest
- Allowed Transitions:
- Scheduled → Completed
- Scheduled → Cancelled
- Scheduled → No-Show

POST /ServiceProvider/CancelAppointment
- Purpose: Cancel appointment
- Request: Appointment ID, reason, refund flag
- Process:
1. Validate cancellation policy
2. Calculate refund (if applicable)
3. Send notifications
4. Free up time slot

Reviews & Ratings

GET /ServiceProvider/GetProviderReviews/{userLoginInfoId}
- Purpose: Get provider reviews
- Query Params: Page, page size, rating filter
- Response: Paginated ReviewResponse
- Each Review:
- Client name (or anonymous)
- Rating (1-5)
- Review text
- Date
- Response (if provider replied)

POST /ServiceProvider/RespondToReview
- Purpose: Respond to client review
- Request: Review ID, response text
- Rules: One response per review, cannot edit after posting

GET /ServiceProvider/GetProviderRating/{userLoginInfoId}
- Purpose: Get aggregate rating statistics
- Response:
- Average rating
- Total reviews
- Rating distribution (5-star, 4-star, etc.)
- Recent reviews

Revenue & Earnings

GET /ServiceProvider/GetProviderRevenue/{userLoginInfoId}
- Purpose: Get revenue statistics
- Query Params: Start date, end date
- Response: RevenueResponse
- Includes:
- Total earnings (period)
- Platform fees
- Net earnings
- Payment breakdown by method
- Session count
- Average session rate

GET /ServiceProvider/GetRevenueByPeriod/{userLoginInfoId}
- Purpose: Get revenue grouped by period
- Query Params: Period type (daily, weekly, monthly)
- Response: Time series data for charts

GET /ServiceProvider/GetPaymentHistory/{userLoginInfoId}
- Purpose: Get payout history
- Response: List of PayoutResponse
- Each Payout:
- Date
- Amount
- Payment method
- Status
- Transaction ID

POST /ServiceProvider/RequestPayout
- Purpose: Request withdrawal of earnings
- Request: Amount, payment method
- Validation:
- Minimum payout threshold
- Available balance
- Payment method on file

Provider Search & Discovery

GET /ServiceProvider/SearchProviders
- Purpose: Search for care providers
- Query Params:
- specialty: Filter by specialty
- language: Spoken languages
- gender: Provider gender
- minPrice, maxPrice: Price range
- availability: Available times
- rating: Minimum rating
- insuranceAccepted: Insurance provider
- location: City/country
- Response: List of ServiceProviderResponse
- Sorting: Relevance, rating, price, experience

GET /ServiceProvider/GetProviderById/{userLoginInfoId}
- Purpose: Get provider public profile
- Response: Complete public profile
- Includes:
- All public information
- Services offered
- Availability
- Reviews
- Rating

GET /ServiceProvider/GetFeaturedProviders
- Purpose: Get featured/promoted providers
- Response: List of featured providers
- Criteria: Admin selection, performance, rating

Status Management

GET /ServiceProvider/GetServiceProviderStatus/{userLoginInfoId}
- Purpose: Get provider account status
- Response: ServiceProviderStatusResponse
- Status Types:
- Pending Approval
- Active
- Suspended
- Deactivated
- Additional Info:
- Approval status
- Rejection reason (if applicable)
- Missing information
- Verification status

PUT /ServiceProvider/UpdateProviderStatus
- Purpose: Provider sets online/offline status
- Request: Status (Online, Busy, Away, Offline)
- Affects:
- Search visibility
- Instant booking availability
- Client notifications

Statistics & Analytics

GET /ServiceProvider/GetProviderStatistics/{userLoginInfoId}
- Purpose: Get provider dashboard statistics
- Response: ProviderStatisticsResponse
- Metrics:
- Total clients served
- Sessions this month
- Upcoming appointments
- Revenue this month
- Average rating
- Profile views
- Booking conversion rate
- Cancellation rate


3. PatientController.cs

File: Controllers/PatientController.cs
Route Prefix: /Patient

Purpose: Client/patient-specific functionality

Key Endpoints:

Screening Questionnaires

GET /Patient/GetScreeningQuestions
- Purpose: Get mental health screening questions
- Response: List of questions with options
- Question Types:
- Multiple choice
- Rating scale (1-10)
- Yes/No
- Text input

POST /Patient/SaveScreeningAnswers
- Purpose: Submit screening questionnaire answers
- Request: ScreeningAnswersRequest
- Processing:
1. Calculate scores
2. Generate risk assessment
3. Recommend provider type
4. Store results
- Response: Score, recommendations, risk level

GET /Patient/GetScreeningHistory/{userLoginInfoId}
- Purpose: Get previous screening attempts
- Response: List of past screenings with scores

GET /Patient/GetScreeningResults/{attemptId}
- Purpose: Get specific screening results
- Response: Detailed results, scores, recommendations

Diary & Mood Tracking

POST /Patient/SaveDiaryEntry
- Purpose: Save daily diary entry
- Request: DiaryEntryRequest
- Fields:
- Date
- Mood rating (1-10)
- Activities
- Thoughts
- Feelings
- Sleep quality
- Medication taken
- Notes

GET /Patient/GetDiaryEntries/{userLoginInfoId}
- Purpose: Get client’s diary entries
- Query Params: Start date, end date
- Response: List of diary entries

GET /Patient/GetMoodChart/{userLoginInfoId}
- Purpose: Get mood trend data
- Query Params: Period (week, month, year)
- Response: Time series data for mood chart

Homework & Assignments

GET /Patient/GetMyHomework/{userLoginInfoId}
- Purpose: Get assigned homework
- Response: List of HomeworkResponse
- Filters:
- Pending
- Submitted
- Graded
- Overdue

POST /Patient/SubmitHomework
- Purpose: Submit completed homework
- Request: HomeworkSubmissionRequest
- Fields:
- Homework ID
- Submission text
- Attachments
- Completion notes

GET /Patient/GetHomeworkDetails/{homeworkId}
- Purpose: Get homework details
- Response: Assignment details, instructions, attachments

GET /Patient/GetHomeworkFeedback/{homeworkId}
- Purpose: Get provider feedback on submitted homework
- Response: Feedback text, score, comments


🗂️ Models Structure

Request Models (Models/Request/)

Purpose: DTOs for incoming API requests

Key Request Models:

UserAuthRequest.cs

public class UserAuthRequest
{
    public string UserName { get; set; } // Email or phone
    public string Password { get; set; }
    public int? UserType { get; set; } // Client or Provider
    public string LastLoginFromOS { get; set; } // Android, iOS, Web
    public string RecaptchaToken { get; set; }
    public string ReCaptchaCode { get; set; }
    public bool TestInvalidRecaptcha { get; set; } // For testing
}

UserRegistrationRequest.cs

public class UserRegistrationRequest
{
    public int UserType { get; set; } // 1=Client, 2=Provider
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
    public int? CountryId { get; set; }
    public int? CityId { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public int? Gender { get; set; }
    public int? SalutationId { get; set; }
    public string ReferralCode { get; set; }
    public bool AgreeToTerms { get; set; }
    public string RecaptchaToken { get; set; }
}

ServiceProviderRequest.cs

public class ServiceProviderRequest
{
    public long UserLoginInfoId { get; set; }
    public int SpecialityId { get; set; }
    public string Bio { get; set; }
    public int YearsOfExperience { get; set; }
    public List<int> LanguageIds { get; set; }
    public List<int> SubSpecialityIds { get; set; }
    public bool AcceptsInsurance { get; set; }
    public List<string> InsuranceProviders { get; set; }
}

Response Models (Models/Response/)

Purpose: DTOs for outgoing API responses

Key Response Models:

UserLoginResponse.cs

public class UserLoginResponse : BaseResponse
{
    public UserLoginInfo UserLoginInfo { get; set; }
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
    public DateTime TokenExpiry { get; set; }
}

public class UserLoginInfo
{
    public long UserLoginInfoId { get; set; }
    public long UserId { get; set; }
    public int UserType { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string ProfileImageUrl { get; set; }
    public bool IsEmailVerified { get; set; }
    public bool IsPhoneVerified { get; set; }
    public bool IsProfileComplete { get; set; }
}

BaseResponse.cs

public class BaseResponse
{
    public int Status { get; set; } // 1=Success, 0=Failure
    public string Message { get; set; }
    public ResponseReason Reason { get; set; }
    public object Data { get; set; }
}

public enum ResponseReason
{
    Success = 0,
    InvalidCredentials = 1,
    UserNotFound = 2,
    AccountLocked = 3,
    EmailNotVerified = 4,
    InvalidToken = 5,
    NotAllowed = 6,
    EmptyParameter = 7,
    DatabaseError = 8,
    ExternalServiceError = 9
}

ServiceProviderResponse.cs

public class ServiceProviderResponse : BaseResponse
{
    public long UserLoginInfoId { get; set; }
    public string DisplayName { get; set; }
    public string SpecialityName { get; set; }
    public string Bio { get; set; }
    public int YearsOfExperience { get; set; }
    public List<string> Languages { get; set; }
    public List<string> SubSpecialities { get; set; }
    public string ProfileImageUrl { get; set; }
    public decimal? AverageRating { get; set; }
    public int TotalReviews { get; set; }
    public decimal? StartingPrice { get; set; }
    public string Currency { get; set; }
    public bool IsAvailable { get; set; }
    public string NextAvailableSlot { get; set; }
    public List<UserServices> Services { get; set; }
}


🔧 Common Utilities (Common/)

Security & Validation

SecurityHelper.cs
- Purpose: Encryption, hashing, token generation
- Methods:
- EncryptString(string text): AES encryption
- DecryptString(string encrypted): AES decryption
- HashPassword(string password): PBKDF2 hashing
- VerifyPassword(string password, string hash): Password verification
- GenerateToken(): Random token generation
- GenerateOTP(): 6-digit OTP generation

AntiXssValidationFilter.cs
- Purpose: Prevent XSS attacks
- Validation:
- HTML tag detection
- Script tag detection
- SQL injection patterns
- Special character encoding

ValidateUserClaimFilter.cs
- Purpose: Claims-based authorization
- Validates:
- User type matches endpoint requirements
- UserLoginInfoId matches token
- Token not expired/revoked

Communication

EmailManager.cs
- Purpose: Email sending functionality
- Methods:
- SendEmail(to, subject, body): Send email
- SendTemplateEmail(template, data): Send from template
- SendVerificationEmail(user): Account verification
- SendPasswordResetEmail(user, code): Password reset
- SendAppointmentConfirmation(appointment): Booking confirmation
- SMTP Configuration: From Web.config
- Templates: HTML email templates

SendSMSHelper.cs
- Purpose: SMS sending (via SMS gateway)
- Methods:
- SendSMS(phoneNumber, message): Send SMS
- SendOTP(phoneNumber, code): Send OTP
- SendAppointmentReminder(appointment): SMS reminder

FCMNotification.cs
- Purpose: Firebase Cloud Messaging (push notifications)
- Methods:
- SendNotification(userId, title, body, data): Send to user
- SendMultipleNotifications(userIds, notification): Bulk send
- SendToTopic(topic, notification): Topic-based
- Firebase Setup: Uses firebase-adminsdk.json credentials

Document Generation

iTextSharpHelper.cs
- Purpose: PDF generation
- Use Cases:
- Prescriptions
- Session notes
- Invoices
- Reports
- Certificates
- Methods:
- GeneratePrescriptionPDF(prescription): Create prescription PDF
- GenerateInvoicePDF(booking): Create invoice
- GenerateReportPDF(data): Custom reports
- HTMLToPDF(html): Convert HTML to PDF

GenerateQRCodeHelper.cs
- Purpose: QR code generation
- Use Cases:
- Appointment check-in
- Payment verification
- Document validation
- Method:
- GenerateQRCode(data): Generate QR code image

Video Integration

VideoSDKHelper.cs
- Purpose: VideoSDK API integration
- Methods:
- CreateMeeting(): Create video meeting room
- GetMeetingDetails(meetingId): Get meeting info
- GetRecordings(meetingId): Get session recordings
- DeleteRecording(recordingId): Remove recording
- API: VideoSDK REST API
- Used For: Video consultation sessions


END OF PART 1


📝 Summary of Part 1

Covered:
✅ Project structure and configuration
✅ Dependencies and frameworks
✅ Authentication & authorization (OAuth 2.0)
✅ Data access layer (repositories)
✅ Controllers: User, ServiceProvider, Patient
✅ Models: Request/Response DTOs
✅ Common utilities (Security, Communication, Documents)

Coming in Part 2:
⏭️ Remaining controllers (Admin, Messaging, Payment, etc.)
⏭️ Additional repositories
⏭️ Models: Entity models, enumerations
⏭️ Scheduling integration
⏭️ Payment gateway integration
⏭️ Error handling & logging
⏭️ Deployment & CI/CD