User Module
The User module is a comprehensive user management system for the Comdeall platform that handles the complete lifecycle of users including parents, therapists, children, and administrators. It manages user registration, onboarding, profile management, role-based access control, child management, therapist verification, financial operations, and integrates with Hasura database functions for core child management operations.
Table of Contents
- Module Structure
- User Endpoints
- Core Features
- User Management Workflows
- Hasura Functions & Database Logic
- Child Management System
- Therapist Management System
- Financial Integration
- Security & Authorization
- Technical Implementation
Module Structure
@Module({
imports: [
forwardRef(() => AppointmentsModule),
forwardRef(() => PaymentModule),
forwardRef(() => BackgroundModule),
forwardRef(() => SubscriptionModule),
DBModule,
],
controllers: [UserController],
providers: [
UserService,
Requests,
{ provide: 'EmailProvider', useClass: SendgridProvider },
{ provide: 'FirebaseProvider', useClass: FirebaseProvider },
],
exports: [UserService],
})
export class UserModule {}
Architecture Components
- UserController - REST API endpoints (
/api/user-management) - UserService - Business logic and workflow orchestration
- UserDBService - Database operation abstraction layer
- UserRepository - Raw database queries and data access
- Hasura Functions - Direct database functions for child operations
- Background Integration - Email, SMS, and notification services
- Payment Integration - Financial operations and wallet management
User Endpoints
| Method | Endpoint | Auth | Roles | Description |
|---|---|---|---|---|
| POST | /create-parent | JWT | ADMIN | Create new parent account |
| POST | /assign-child-therapist | JWT | ADMIN | Assign therapist to child |
| POST | /inactive-childs | JWT | ADMIN | Get inactive children list |
| POST | /delete-childs | JWT | ADMIN, PARENT | Delete multiple children |
| POST | /delete-child | JWT | ADMIN, PARENT | Delete single child |
| POST | /edit-consultation-fees | JWT | ADMIN | Update therapist fees |
| POST | /remove-assigned-child | JWT | ADMIN | Unassign child from therapist |
| POST | /inactive-therapists | JWT | ADMIN | Get inactive therapists list |
| POST | /therapist-verification | None | Webhook | Verify therapist documents |
| POST | /delete-therapists | JWT | ADMIN | Delete multiple therapists |
| POST | /delete-user | JWT | PARENT, THERAPIST | Self-delete user account |
| POST | /add-bank-account | JWT | THERAPIST | Add bank account details |
| POST | /delete-bank-account | JWT | THERAPIST | Remove bank account |
| POST | /withdraw-request | JWT | THERAPIST | Request earnings withdrawal |
Core Features
1. User Management
- Multi-role Support - Parents, therapists, children, and administrators
- Registration Workflows - Role-specific onboarding processes
- Profile Management - Comprehensive user profile editing
- Account Lifecycle - Creation, activation, suspension, and deletion
- Relationship Management - Parent-child and child-therapist mappings
2. Child Management (Hasura-driven)
- Direct Frontend Integration - Frontend calls Hasura functions directly
- Age-based Validation - Supports children aged 0-18 years
- Unique Identification - Auto-generated unique codes (CD2024001 format)
- Media Integration - Profile images and evaluation documents
- No Immediate Subscription - Subscription handled after screening assessment
3. Therapist Management
- Verification System - Document verification and approval workflow
- Fee Management - Customizable consultation fee structures
- Bank Account Integration - Multiple bank account support
- Withdrawal System - Automated earnings withdrawal processing
- Performance Tracking - Appointment and earnings analytics
4. Financial Operations
- Wallet Management - Individual user wallet systems
- Payment Processing - Integration with payment providers
- Payout Management - Automated therapist payment processing
- Refund Handling - Comprehensive refund workflow
- Transaction Tracking - Detailed financial audit trails
User Management Workflows
Parent Creation Process
Admin Creates Parent → Email Verification → Parent Profile Created → Ready for Child Addition (via Hasura)
Key Steps:
- Admin Creation - Administrator creates parent account with basic details
- Validation - Email and phone number uniqueness verification
- Account Creation - Parent account created with registered status
- Ready State - Parent can now add children through frontend Hasura calls
Child Addition Workflow (Frontend → Hasura)
Frontend Form → Hasura add_child Function → Validation → Unique Code Generation → Child Created → Screening Assessment
Important Note:
- Frontend directly calls Hasura
add_childfunction - No subscription is activated during child creation
- Subscription is handled after screening assessment completion
Subscription Activation Process
Child Created → Screening Assessment → Assessment Completion → Subscription Required → Payment → Subscription Active
Subscription Logic:
- Children can be added without immediate subscription
- Screening assessment is always available
- Subscription becomes required for advanced features
- Payment is processed after screening assessment completion
Therapist Verification Process
Registration → Document Upload → Admin Review → Verification API → Approval/Rejection → Account Activation → Assignment Eligibility
Hasura Functions & Database Logic
Function: add_child (Frontend Direct Call)
Comprehensive child addition with validation and unique code generation.
CREATE OR REPLACE FUNCTION add_child(
hasura_session JSON,
input_parent_id UUID,
input_child_name TEXT,
input_concerns TEXT,
input_dob DATE,
input_gender TEXT,
input_age INTEGER,
input_profile_img UUID DEFAULT NULL,
input_previous_evaluations_json JSON DEFAULT NULL
) RETURNS SETOF child
Function Features:
- Direct Frontend Access - Called directly from frontend via GraphQL
- Session-based Authorization - JWT token validation with role checking
- Parent Validation - Ensures parent exists and is properly onboarded
- Child Count Limits - Enforces maximum children per parent (default: 4)
- Age Calculation - Validates age against date of birth
- Unique Code Generation - Creates country-year-sequence format codes
- Media Handling - Associates profile images and evaluation documents
- No Subscription Logic - Child creation doesn't trigger subscription
Key Differences from Backend Endpoint:
- Frontend calls this function directly through Hasura GraphQL
- No immediate subscription activation
- Simplified workflow focused on child creation only
Function: edit_child (Frontend Direct Call)
Sophisticated child profile editing with media management.
CREATE OR REPLACE FUNCTION edit_child(
hasura_session JSON,
input_child_id UUID,
input_alternate_phone TEXT,
input_concerns TEXT,
input_profile_img UUID,
input_previous_evaluations UUID[]
) RETURNS SETOF child
Edit Capabilities:
- Direct Frontend Integration - No backend endpoint involvement
- Profile Updates - Modify child information while preserving history
- Media Replacement - Handle profile image and document updates
- Validation - Ensure data integrity during updates
- Audit Tracking - Maintain change history for compliance
Function: parent_onboarding
Complete parent profile setup with media and preference management.
CREATE OR REPLACE FUNCTION parent_onboarding(
hasura_session JSON,
input_parent_name TEXT,
input_child_relation TEXT,
input_alternate_phone TEXT,
input_concerns TEXT,
input_location TEXT,
input_profile_img UUID,
input_preferred_languages UUID[]
) RETURNS SETOF parent
Onboarding Process:
- Profile Completion - Updates parent with comprehensive information
- Language Preferences - Associates multiple preferred languages
- Media Management - Links profile images and sets usage flags
- Location Tracking - Records geographical preferences
- Validation - Ensures all required fields are properly formatted
Function: update_therapist_profile
Comprehensive therapist profile management with verification handling.
CREATE OR REPLACE FUNCTION update_therapist_profile(
user_id UUID,
gender TEXT,
date_of_birth DATE,
state_id UUID,
city_id UUID,
consultation_fee INTEGER,
aadhaar_card TEXT,
pan_card TEXT,
social_security TEXT,
degree_name TEXT,
university_name TEXT,
profile_description TEXT
) RETURNS JSON
Child Management System
Frontend-Driven Architecture
Frontend Form → Hasura GraphQL → Database Function → Response → UI Update
Benefits:
- Direct Database Access - Eliminates backend API layer for child operations
- Real-time Validation - Immediate feedback on data validation
- Reduced Latency - Direct database function calls
- Simplified Architecture - Fewer moving parts for core operations
Unique Code Generation
Each child receives a unique identifier following the pattern: CD{YEAR}{SEQUENCE}
// Generation Logic (in Hasura function)
const generateUniqueCode = (countryCode: string, year: string, sequence: number): string => {
const paddedSequence = sequence.toString().padStart(3, '0');
return `${countryCode}${year}${paddedSequence}`;
};
// Example: CD2024001, CD2024002, etc.
Age-based Features
- Monthly Tracking - Age stored in months for precise developmental tracking
- Assessment Eligibility - Age-appropriate assessment assignments
- Progress Monitoring - Developmental milestone tracking
- Educational Content - Age-specific lesson plan recommendations
Subscription Integration Logic
Child Created → Screening Assessment Available → Assessment Completed → Subscription Required for Advanced Features
Subscription Workflow:
- Child Creation - No subscription required
- Screening Access - Always available regardless of subscription
- Assessment Completion - Triggers subscription requirement
- Feature Access - Advanced features require active subscription
- Payment Processing - Handled after assessment completion
Therapist Management System
Verification Workflow
Registration → Document Collection → Identity Verification → Professional Validation → Manual Review → Approval → Active Status
Document Types:
- Identity Proof - Aadhaar Card, PAN Card, Social Security Number
- Professional Credentials - Degree certificates, license documents
- Background Checks - Automated verification through external APIs
Fee Management
- Individual Rates - Custom consultation fees per therapist
- Dynamic Pricing - Admin-configurable fee structures
- Payment Integration - Automated fee collection and distribution
- Performance Incentives - Rating-based fee adjustments
Bank Account System
// Multiple bank account support
{
accountHolder: "Therapist Name",
accountNumber: "1234567890",
ifscCode: "BANK0001234",
accountType: "SAVINGS",
bankName: "Example Bank"
}
Withdrawal Management
- Automated Processing - Scheduled withdrawal processing
- Minimum Thresholds - Configurable minimum withdrawal amounts
- Status Tracking - Real-time withdrawal status updates
- Audit Trails - Comprehensive transaction logging
Financial Integration
Wallet System
Each user (parent/therapist) maintains individual wallet balances:
- Credit Management - Automatic credits from payments/earnings
- Debit Processing - Service charges and withdrawal debits
- Balance Tracking - Real-time balance calculations
- Transaction History - Detailed transaction logs
Payment Processing
- Razorpay Integration - Primary payment gateway
- Webhook Handling - Automated payment status updates
- Refund Management - Automated and manual refund processing
- Multi-currency Support - International payment handling
Therapist Payouts
// Payout workflow
{
earnings: "Session fees - platform commission",
schedule: "Weekly automated payouts",
methods: ["Bank transfer", "Digital wallet"],
tracking: "Real-time payout status"
}
Security & Authorization
Role-based Access Control
| Resource | ADMIN | PARENT | THERAPIST | CHILD |
|---|---|---|---|---|
| Create Parent | ✓ | ✗ | ✗ | ✗ |
| Add Child (Hasura) | ✓ | ✓ | ✗ | ✗ |
| Edit Child (Hasura) | ✓ | ✓ (own) | ✗ | ✗ |
| Assign Therapist | ✓ | ✗ | ✗ | ✗ |
| Manage Fees | ✓ | ✗ | ✗ | ✗ |
| Bank Operations | ✗ | ✗ | ✓ | ✗ |
| View Reports | ✓ | ✓ (own) | ✓ (assigned) | ✗ |
Hasura Security
- Row Level Security - Database-level access control
- Session Variables - JWT claims used for authorization
- Function Permissions - Role-based function access
- Input Validation - Comprehensive validation in database functions
Data Protection
- PII Encryption - Sensitive data encrypted at rest
- Access Logging - All data access logged for audit
- Session Management - JWT-based secure session handling
- Input Validation - Comprehensive server-side validation
- SQL Injection Protection - Parameterized queries throughout
Technical Implementation
Hybrid Architecture
// Backend endpoints for admin operations
@Injectable()
export class UserService {
async createParent(parentData: CreateParentDto) {
// Validate unique email/phone
const existingUser = await this.userDBService.findUser(parentData.contact, parentData.email);
if (existingUser.length > 0) {
throw new BadRequestException('Parent already exists');
}
// Create parent - child addition handled by Hasura
await this.userDBService.createParent({
...parentData,
is_registered: true
});
}
}
// Frontend directly calls Hasura for child operations
// No backend endpoint involvement for add_child/edit_child
Frontend Integration Pattern
// Frontend GraphQL call to Hasura
const ADD_CHILD_MUTATION = gql`
mutation AddChild($input: AddChildInput!) {
add_child(
input_parent_id: $input.parent_id
input_child_name: $input.child_name
input_concerns: $input.concerns
input_dob: $input.dob
input_gender: $input.gender
input_age: $input.age
input_profile_img: $input.profile_img
input_previous_evaluations_json: $input.previous_evaluations
) {
id
name
unique_code
created_at
}
}
`;
Subscription Logic Integration
// Subscription activation after screening
const handleScreeningCompletion = async (assessmentId: string, childId: string) => {
// Check if assessment is screening type
const assessment = await getAssessment(assessmentId);
if (assessment.type === 'SCREENING') {
// Trigger subscription requirement
await triggerSubscriptionFlow(childId);
}
};
Error Handling Strategy
- Hasura Function Errors - Structured error responses from database functions
- Business Logic Errors - Contextual error responses with suggested actions
- Database Errors - Sanitized error messages preventing information disclosure
- External API Errors - Graceful degradation with fallback mechanisms
- Audit Logging - All errors logged with user context and request details
This User module provides a robust, scalable foundation for user management across the Comdeall platform, leveraging Hasura's direct database functions for efficient child management while maintaining backend API endpoints for administrative operations and complex business logic.