Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Platinum Documentation

Api Documentation

Table Of Contents

Introduction

Integrations

Technical Structure

Flows

Migration

Additional

Integrations

High Level Architecture

Diagram

Integrations

HR Integration

Diagram

HR Integration Diagram

EPC HR Integration API's

HR System API Expectations

Salesforce Integration

Diagram

Salesforce Integration Diagram

EPC Salesforce Integration API's

Salesforce API Expectations

CPG Integration

Diagram

todo: recurring payment and instrument token details will talk

CPG Integration Diagram

CPG API

Partner Integration

Partner Integration

Partner Integration Diagram

EPC Parter Integration API's

Diagram

HR Integration Diagram

EPC HR Integration API's

HR System API Expectations

Employee Detail API (HR System)

The Employee Detail API should return the following fields:

Request

FieldTypeDescriptionOptional
emailstringfalse

Response

FieldTypeDescriptionOptional
employeeIdstringfalse
birthdatedatefalse
emailstringfalse
namestringfalse
surnamestringfalse
phonestringfalse
gradestringfalse
isCabinCrewbooleanfalse
employmentTypestringfalse
companyIdstringfalse
statusstringfalse
lastStatusUpdatedAtdatefalse
addressstringfalse
countrystringfalse
familyarrayList of family membersfalse
family.idstringfalse
family.typestringfalse
family.namestringfalse
family.surnamestringfalse
family.emailstringfalse
family.birthdatedatefalse

Member Id Update API (HR System)

Update the member ID for an employee in the HR system. This API is used to update the member ID of an employee in the HR system when a employee becomes a member of the EPC.

Request

FieldTypeDescriptionOptional
employeeIdstringfalse
memberIdstringfalse

Response

A response indicates whether the operation is successfull or not

Employee Photo Update API - Interface Control Document

1. Document Information

ItemDescription
Document TitleEmployee Photo Update API - Interface Control Document
API NameupdateEmployeePhoto
Interface TypeREST API (Integration Service)
Version0.0.1
Last Updated2025-10-15
StatusActive

2. Overview

2.1 Purpose

The Employee Photo Update API enables HR systems to update employee photos in the EPC (Emirates Platinum Club) system. This integration service allows external HR systems to push employee photo updates when photos are changed in the HR system.

2.2 Integration Context

This API is part of the broader Emirates Employee Photo Update Flow. For complete flow documentation, see:

3. Interface Specification

3.1 Endpoint Details

PropertyValue
HTTP MethodPOST
Endpoint Pattern/:projectId/CALL/Member/updateEmployeePhoto/:instanceId
ProtocolHTTPS
Content-Typeapplication/json
AuthenticationAPI Key (x-api-key header)
AuthorizationuserIdentity.integration_user

3.2 Path Parameters

ParameterTypeRequiredDescriptionExample
projectIdstringYesThe EPC project identifier13ra108se
instanceIdstringYesMember ID or Staff ID with prefixstaffId!EMP001 or MEM12345

Instance ID Format:

  • Member ID: Direct member identifier (e.g., MEM12345)
  • Staff ID: Staff identifier prefixed with staffId! (e.g., staffId!EMP001)

3.3 Request Headers

HeaderTypeRequiredDescription
x-api-keystringYesAPI authentication key
Content-TypestringYesMust be application/json

3.4 Request Body

FieldTypeRequiredConstraintsDescription
photostringYesBase64 encodedBase64 encoded image data
fileExtensionstringYesEnum: jpg, jpeg, png, gif, webpImage file extension

TypeScript Input Schema:

export const UpdateEmployeePhotoInput = z.object({
    photo: z.string(),
    fileExtension: z.nativeEnum(ImageFileExtension),
})

export enum ImageFileExtension {
    JPG = 'jpg',
    JPEG = 'jpeg',
    PNG = 'png',
    GIF = 'gif',
    WEBP = 'webp',
}

MIME Type Mapping:

  • jpgimage/jpeg
  • jpegimage/jpeg
  • pngimage/png
  • gifimage/gif
  • webpimage/webp

3.5 Response Format

Success Response (HTTP 200)

{
  "success": true
}
FieldTypeDescription
successbooleanAlways true on successful upload

Error Response (HTTP 4xx/5xx)

{
  "code": 10000,
  "message": "Error description",
  "details": {}
}
FieldTypeDescription
codenumberError code identifier (e.g., 10018 for EMPLOYEE_PHOTO_UPLOAD_FAILED)
messagestringLocalized human-readable error message
detailsobjectAdditional error context and debugging information (optional)

4. Request/Response Examples

4.1 Request with Staff ID

POST /13ra108se/CALL/Member/updateEmployeePhoto/staffId!EMP001
Content-Type: application/json
x-api-key: your-api-key-here

{
  "photo": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
  "fileExtension": "png"
}

4.2 Request with Member ID

POST /13ra108se/CALL/Member/updateEmployeePhoto/MEM12345
Content-Type: application/json
x-api-key: your-api-key-here

{
  "photo": "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBw...",
  "fileExtension": "jpg"
}

4.3 Success Response

HTTP/1.1 200 OK
Content-Type: application/json

{
  "success": true
}

4.4 Error Response Examples

Validation Error

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "code": 10005,
  "message": "Invalid file extension. File extension must be one of: jpg, jpeg, png, gif, webp"
}

Upload Error

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
  "code": 10018,
  "message": "Failed to upload employee photo.",
  "details": {
    "message": "File upload failed.",
    "code": 6006
  }
}

Instance Not Found Error (Rio Framework)

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
  "message": "There is no instance with id '87LN5X4ZQR8C8G5TMFPTDX402' in '107jif3ja/Member'"
}

Note: Instance not found errors are handled by the Rio framework before the method handler is invoked, so they return a different format.

5. Data Validation Rules

5.1 Photo Field Validation

  • Format: Must be valid Base64 encoded string
  • Content: Must represent a valid image in the specified format

5.2 File Extension Validation

  • Allowed Values: jpg, jpeg, png, gif, webp
  • Case Sensitivity: Lowercase only
  • Validation: Uses Zod enum validation (z.nativeEnum(ImageFileExtension))

5.3 Instance ID Validation

  • Member ID: Direct member identifier (no prefix)
  • Staff ID: Must use staffId! prefix followed by employee identifier

6. Security

6.1 Authentication

  • Method: API Key authentication
  • Header: x-api-key
  • Authorization: Requires userIdentity.integration_user permission

6.2 Data Security

  • All communication must use HTTPS
  • Base64 encoding for image data in transit
  • API keys must be securely stored and rotated periodically
  • Photos stored in secure file storage with access controls
  • File access URLs generated with expiry tokens

7. Error Handling

7.1 Common Error Scenarios

Error CodeHTTP StatusDescriptionResolution
UNAUTHORIZED401Invalid or missing API keyVerify x-api-key header and value
VALIDATION_ERROR400Invalid input dataCheck Zod schema validation errors
N/A (Rio Framework)500Member/Employee instance not foundVerify instanceId exists in system. Response: {"message":"There is no instance with id 'X' in 'projectId/Member'"}
EMPLOYEE_PHOTO_UPLOAD_FAILED400Employee photo upload failedCheck photo format and size, retry request
FILE_UPLOAD_FAILED500File storage error (FileManager)Internal file storage issue, contact support
INVALID_FILE_FORMAT400Invalid file formatEnsure photo is in supported format (jpg, jpeg, png, gif, webp)

Error Handling Flow:

  • File upload errors from FileManager are caught and wrapped in EMPLOYEE_PHOTO_UPLOAD_FAILED error
  • Original FileManager error details are preserved in error response for debugging
  • All errors follow standard ErrorResponse format with localized messages
  • Instance not found errors are handled by Rio framework before reaching the method handler

8. Support and Maintenance

8.1 Monitoring

  • All API calls logged via LogManager
  • State changes tracked via StateManager
  • Workflow events recorded in approval records
  • File uploads tracked in FileManager

8.2 Audit Trail

  • Actor information captured from API key context
  • Photo upload events logged with timestamps
  • Previous photo paths preserved for rollback
  • Approval workflow tracks photo review status

Diagram

Salesforce Integration Diagram

EPC Salesforce Integration API's

Salesforce API Expectations

Diagram

todo: recurring payment and instrument token details will talk

CPG Integration Diagram

CPG API

Partner Integration

Partner Integration Diagram

EPC Parter Integration API's

Architecture

Architecture

Classes

This document provides an overview of all classes in the backend system. Each class represents a specific domain of functionality with its own state management, business logic, and API endpoints.

Core Classes

Core classes provide shared functionality, system services, and infrastructure support across all entity classes.

ApprovalManager

Centralized approval workflow management providing approval processing for all entity types with hybrid storage (MongoDB + RDK file storage) for handling large jsonPatch data, workflow integration, and comprehensive audit trails.

→ View ApprovalManager Documentation


RoleManager

Role and permission management system with dynamic role creation, permission-based access control, and deployment automation.

→ View Role Manager Documentation


LogManager

Centralized logging and audit trail system with hybrid storage (MongoDB + RDK file storage) for handling large log entries, providing entity-specific log management and paginated log retrieval across all classes.

→ View Log Manager Documentation


FileManager

Secure file storage and management system providing entity-based file organization with comprehensive validation, metadata tracking, and token-based security.

→ View File Manager Documentation


Setting

System configuration and reference data management including global settings, company groups, member types, tier types, and streaming capabilities.

→ View Setting Documentation


SystemEmail

Email template management and delivery system with dynamic templates, approval workflows, and AWS SES integration for multi-purpose email delivery.

→ View SystemEmail Documentation


Workflow

Business process automation and workflow configuration providing rule definition and process automation integration.

→ View Workflow Documentation


Otp

OTP record storage and management service providing authentication workflow support with comprehensive audit trails and validation history.

→ View Otp Documentation

Entity Classes

Entity classes manage the core business entities and their lifecycles in the loyalty program system.

Member

Core member profile and lifecycle management with comprehensive profile tabs, photo management, and eligibility rules.

→ View Member Documentation


Company

Management of companies participating in the loyalty program with CRUD operations, approval workflows, and hierarchical structures.

→ View Company Documentation


Tier

Individual membership tier management with eligibility rules, payment configurations, and approval workflows.

→ View Tier Documentation


ProgramManagementUser

Administrative user management for program operators with role-based access, SSO (SAML 2.0) and email/password authentication, and invitation workflows.

→ View Program Management User Documentation

Architecture Overview

Method Types

The classes use four types of Rio methods:

  • READ: Synchronous data retrieval (1-30s)
  • WRITE: Synchronous state mutations (1-30s)
  • QUEUED_WRITE: Asynchronous operations with longer processing times (1-890s)
  • STATIC: Stateless utility methods (no instance required)

Success Response Standardization

All classes implement a unified success response system that provides:

  • Consistent Response Structure: Standardized success response format across all classes
  • Localization Support: Built-in multi-language support with fallback mechanisms
  • Type Safety: Type-safe success definitions with class-specific constants
  • Centralized Management: Success messages defined in classes/*/constants/success.responses.ts

Success Response Architecture

Success Response Pattern:

data.response = new SuccessResponse({
    success: ClassSuccess.OPERATION_TYPE,
    localization: culture,
    body: { responseData }
})

Key Benefits:

  1. Consistency: All methods return standardized success responses
  2. Localization: Automatic message localization based on user culture
  3. Maintenance: Centralized success message management per class
  4. Type Safety: Compile-time validation of success response types

Error Response Standardization

All classes implement a unified error response system that provides:

  • Consistent Error Structure: Standardized error response format with HTTP status codes
  • Unique Error Codes: Class-specific error codes for precise error identification
  • Localization Support: Multi-language error messages with fallback mechanisms
  • Type Safety: Type-safe error definitions with class-specific constants
  • Centralized Management: Error definitions in classes/*/constants/error.responses.ts

Error Response Pattern:

// Throwing specific business logic errors
throw new ErrorResponse({
    error: ClassError.SPECIFIC_ERROR_TYPE,
    details: { additionalContext }
})

// Handling unexpected errors in catch blocks
catch (error) {
    data.response = parseError(error, ClassIdentities.enum.ClassName, culture)
}

Error Response Format:

{
    statusCode: 400 | 403 | 404 | 500 | 502,
    body: {
        code: number,  // Unique error code per class
        message: "Localized error message",
        classId: "ClassName"
    }
}

Error Code Ranges by Class:

  • ProgramManagementUser: 4000-4099
  • Member: 5000-5099
  • Company: 6000-6099
  • Tier: 7000-7099
  • ApprovalManager: 8000-8099
  • RoleManager: 9000-9099
  • Setting: 10000-10099
  • SystemEmail: 11000-11099
  • LogManager: 12000-12099
  • FileManager: 13000-13099
  • Workflow: 14000-14099
  • Otp: 15000-15099

Key Benefits:

  1. Traceability: Unique error codes enable precise error tracking and debugging
  2. Client Handling: Predictable error format simplifies client-side error handling
  3. Localization: Automatic error message translation based on user locale
  4. Maintainability: Centralized error definitions per class
  5. Type Safety: Compile-time validation prevents using non-existent error types

Inter-Class Dependencies

Classes integrate through:

  • ApprovalManager: Used by classes needing approval workflows
  • LogManager: Used across all classes for audit trails
  • RoleManager: Provides authorization for ProgramManagementUser operations
  • Setting: Provides configuration data to various classes
  • SystemEmail: Authorized for use by all classes for email delivery (implementations pending)

API Documentation

Complete API documentation for all classes is available at /api in the live environment and rendered to docs/api directory.

Workflow

Overview

The Workflow class is a service that manages state transitions and approval workflows for various entities in the system. It provides a centralized workflow engine that coordinates status changes based on events, conditions, and approval requirements.

General Purpose:

  • Centralized workflow management for system entities
  • Integration with approval management system
  • Configurable workflow rules for different entity types
  • Automatic status updates based on business rules

Data Structure

State Schema

The Workflow class maintains workflow configurations for different entities:

interface WorkflowState {
  private: {
    workflowConfig: WorkflowConfig<WorkflowRule>
  }
  public: object
}

Workflow Configuration

Each workflow configuration contains:

interface WorkflowConfig {
  id: string                    // Unique identifier (class name)
  classId: WorkflowSupportedClass  // Target entity class
  rules: WorkflowRule[]         // Array of workflow rules
}

Workflow Rules

Individual workflow rules define state transitions:

interface WorkflowRule {
  event: string | number           // Triggering event
  currentStatus: Status | '*'      // Current entity status (* = wildcard)
  targetStatus: Status | '*'       // Target status after transition
  conditions: WorkflowRuleCondition[]  // Conditions to evaluate
  approvers: string[]             // Required approver roles (empty = auto-approve)
}

Conditions

Workflow conditions provide flexible rule evaluation:

interface WorkflowRuleCondition {
  dataSource: 'entity' | 'actor'     // Data source for evaluation
  key: string                         // Field to evaluate
  value: any                          // Expected value
  operator: 'equal' | 'not_equal' | 'in' | 'not_in' |
           'less_than' | 'greater_than' | 'less_than_equal' | 'greater_than_equal'
}

Data Sources:

  • entity: Evaluate fields from the target entity
  • actor: Evaluate fields from the user performing the action

Supported Operators:

  • Equality: equal, not_equal
  • Set operations: in, not_in
  • Comparisons: less_than, greater_than, less_than_equal, greater_than_equal

Core Functionality

Workflow Execution

The workflow engine processes events through these steps:

  1. Event Trigger: An event occurs on an entity (e.g., user creation, status change)
  2. Rule Matching: Find applicable rules based on event and current status
  3. Condition Evaluation: Check if all conditions are satisfied
  4. Status Transition: Update entity status to target status
  5. Approval Creation: Create approval record if required
  6. Auto-Approval: Automatically approve and execute if no manual approval needed

Status Transitions

  • Wildcard Support: Rules can apply to any status using * wildcard
  • Conditional Logic: Multiple conditions can be combined for complex rules
  • Flexible Operators: Support for equality, comparison, and set operations

Condition Evaluation

The workflow engine evaluates conditions to determine if a rule should be applied:

  • Multiple Conditions: All conditions in a rule must be satisfied
  • Data Source Flexibility: Can evaluate both entity and actor properties
  • Type-Aware Operations: Supports different data types with appropriate operators

Approval Integration

The workflow system integrates with ApprovalManager:

  • Auto-Approval: Rules without approvers are automatically approved
  • Manual Approval: Rules with approvers require manual approval
  • Async Processing: Supports both synchronous and asynchronous approval callbacks
  • JSON Patch: Tracks state changes for approval records
  • Simulated Approved State: For auto-approved async operations, returns simulated approved state by applying jsonPatch to current state snapshot

Architecture

Workflow Executer

The WorkflowExecuter class (workflow.executer.ts) is the core engine that processes workflow rules:

Key Features:

  • Rule Matching: Filters rules based on event and current status
  • Condition Evaluation: Processes complex conditional logic
  • State Management: Integrates with WorkflowCompatibleStateManager
  • Approval Coordination: Creates and manages approval records
  • Error Handling: Provides specific error types for different failure scenarios
  • Simulated Approved State Response: Returns simulated approved state for auto-approved async operations

Return Value: The run() method returns:

  • isApproved - Boolean indicating if approval is complete
  • approvalRecord - The created approval record
  • simulatedApprovedState - Optional state snapshot with jsonPatch applied (only for auto-approved async callbacks)

Error Types:

  • WorkflowClassIdDoesNotMatchError - Class ID mismatch between config and state manager
  • WorkflowUnhandledFlow - No matching rules found for event/status combination
  • WorkflowMultipleFlowsMatched - Multiple rules match (should be unique)
  • WorkflowUnexpectedErrorWhileFinalizingApproval - Approval callback execution failed

State Manager Integration

Classes that use workflows must extend WorkflowCompatibleStateManager:

abstract class WorkflowCompatibleStateManager<State> extends StateManager<State> {
  abstract updateStatus<T extends string | number>(id: string, status: T): Promise<void>
  getStateSnapshot(): State  // Returns cloned state for safe external use
}

Integration Examples:

  • Member - Member registration and lifecycle workflows
  • ProgramManagementUser - Administrative user management workflows
  • Company - Company lifecycle and approval workflows
  • Tier - Tier management workflows

Cross-Class Communication

The workflow system facilitates communication between classes:

  • Configuration Storage: Workflow configurations stored in RDK database
  • Utility Access: Classes access workflow configs via getWorkflowConfiguration()
  • Async Callbacks: Support for delayed approval processing via task queues
  • Event Synchronization: Coordinates status changes across related entities

API Methods

Configuration Management

  • updateWorkflowConfiguration (WRITE) - Update workflow rules
    • Updates workflow configuration for a specific entity class
    • Validates class ID matches existing configuration
    • Syncs configuration to RDK database

State Management

  • setState (WRITE) - Set workflow state from Rio console

  • getState (READ) - Retrieve current workflow state

  • init (INIT) - Initialize workflow for a specific class

    • Creates initial workflow configuration structure

Key Features

  1. Event-Driven Architecture: Responds to entity events with configurable rules
  2. Conditional Logic: Supports complex business rules with multiple conditions
  3. Approval Integration: Integrates with approval management system
  4. Wildcard Support: Flexible rule matching with status wildcards
  5. Error Recovery: Comprehensive error handling for edge cases
  6. Cross-Class Coordination: Enables workflow communication between different entity types
  7. Database Persistence: Workflow configurations persisted in RDK database
  8. Type Safety: Full TypeScript support with generic type constraints

Workflow Architecture

ApprovalManager

Overview

The ApprovalManager class provides centralized approval workflow management for all entity types in the system. It serves as the backbone for approval processes across Member, Company, Tier, SystemEmail, and other entities that require approval workflows.

General Purpose:

  • Centralized approval record processing with MongoDB persistence
  • Static approval method for cross-class approval handling
  • Abstract base class for entity-specific approval managers
  • Integration with callback system for post-approval processing
  • Singleton architecture with 'default' instance ID

Data Structure

State Schema

interface ApprovalManagerState {
  private: {}
  public: object
}

The ApprovalManager maintains minimal state, with approval records stored in MongoDB for scalability and persistence across the distributed system.

Enums and Types

enum ApprovalType {
  AUTO = 'auto',
  MANUAL = 'manual'
}

enum ApprovalStatus {
  PENDING = 'pending',
  APPROVED = 'approved',
  REJECTED = 'rejected'
}

enum ApprovalSpecificActors {
  AUTO_APPROVE = 'auto_approve'
}

enum StateManagerActorType {
  PROGRAM_MANAGEMENT_USER = 'program_management_user',
  DEVELOPER = 'developer',
  SYSTEM = 'system',
  MEMBER = 'member'
}

Additional Structures

interface ApprovalRecord {
  id: string
  event: string
  instanceId: string
  entityId: string
  approvalStatus: ApprovalStatus
  entityOldStatus: any
  entityNewStatus: any
  approvalType: ApprovalType
  jsonPatch: ExtendedJSONPatchOperation[]
  isLargeApproval: boolean  // Indicates if jsonPatch is stored externally
  actor: StateManagerActor
  approvers: string[]
  approveCallback?: ApproveCallback
  rejectCallback?: ApproveCallback
  approvedAt?: Date
  approvedBy?: ApprovalActor
  additionalData: any
  createdAt: Date
  updatedAt: Date
}

interface ApprovalRecordInDatabase {
  _id: string
  // ... all ApprovalRecord fields
  largeApprovalPath?: string  // Path to RDK file containing large jsonPatch data
}

interface LargeApprovalData {
  jsonPatch: ExtendedJSONPatchOperation[]
}

interface ApproveCallback {
  event: string
  classId: ClassKey
  instanceId: string
  methodName: string
}

interface ApprovalActor {
  id: string
  type: StateManagerActorType | ApprovalSpecificActors
  name?: string
  roles?: string[]
}

Core Functionality

Main Feature Groups

  • Approval Record Processing: Static approve() method handles approval workflow completion and callback execution
  • Abstract Approval Management: Base ApprovalManager service class extended by entity-specific approval managers
  • Callback System: Configurable approve/reject callbacks for entity-specific post-approval processing
  • Role-based Authorization: Validates approver eligibility based on roles and permissions
  • MongoDB Persistence: Approval records stored in dedicated MongoDB collection for scalability
  • Auto-approval Support: Automatic approval processing for system-driven approval workflows

Large Approval Support

  • Size Management: Automatically handles jsonPatch arrays exceeding the size limit (10KB)
  • Automatic Detection: System automatically detects when jsonPatch size exceeds threshold during approval creation
  • External Storage: Stores large jsonPatch arrays in RDK file storage (separate from MongoDB)
  • Transparent Retrieval: ApprovalFetcher.getCompleteApproval() automatically reconstructs complete approval records
  • Performance Optimization: Keeps MongoDB documents lean while supporting arbitrarily large approval data
  • File Naming: Uses pattern LARGE_APPROVAL_${entityId}_${approvalId}.json for large approval files

API Methods

Approval Operations

  • reviewApproval (WRITE) - Review and process an approval request (approve or reject)
    • Uses ApprovalFetcher to retrieve complete approval record including large jsonPatch data
    • Validates approval record exists and is in PENDING status
    • Checks approver eligibility based on roles and permissions
    • Executes configured approval/rejection callback if defined
    • Updates approval status and records approval metadata
    • Persists changes to MongoDB approval collection

Key Features

  1. Architecture Pattern: Singleton class with 'default' instance ID and static approval processing
  2. Integration Points: Extended by CompanyApprovalManager, MemberApprovalManager, TierApprovalManager, and other entity-specific approval classes
  3. Workflow Support: Integration with WorkflowExecuter for automated approval rule processing
  4. Security Features: Role-based approval authorization with developer bypass capabilities and actor tracking
  5. Data Management: Hybrid storage using MongoDB for metadata and RDK file storage for large jsonPatch arrays (exceeding 10KB)
  6. External Integrations: Callback system enables post-approval integration with originating entity classes
  7. Performance Features: Static method design for efficient cross-class approval processing with automatic large approval handling
  8. Audit/Logging: Complete approval lifecycle tracking with timestamps, actors, status transitions, and JSON patch records
  9. Scalability: ApprovalFetcher service provides centralized retrieval logic for complete approval records including large data

Service Architecture

ApprovalFetcher Service

classes/ApprovalManager/services/approval.fetcher.ts centralizes approval retrieval:

  • getApprovalRecordFromDatabase(approvalId): Fetches approval record from MongoDB
  • getLargeApprovalFile(filename): Retrieves large jsonPatch data from RDK storage
  • getCompleteApproval(approvalId): Reconstructs approval record with large jsonPatch data

Used by reviewApproval method and entity-specific approval callback handlers.

Class Relations

The following diagram illustrates how ApprovalManager integrates with other system components:

ApprovalManager Relations

RoleManager

Overview

The RoleManager class serves as the central authority for role-based access control (RBAC) within the Program Management system, managing role definitions, permissions, and authorization workflows.

General Purpose:

  • Manages role creation, updates, and status changes with workflow approval integration
  • Defines and maintains permission mappings across all system classes
  • Provides centralized authorization services through Layer-based deployment and state management
  • Handles role approval workflows and status transitions
  • Singleton instance with 'default' ID managing all role configurations

Data Structure

State Schema

interface RoleManagerState {
  private: {
    roleHash: string
    roles: Record<string, Role>
    lastDeploymentTime?: number
  }
  public: object
}

interface Role {
  id: string
  name: string
  description?: string
  level: RoleLevel
  createdBy: StateManagerActor
  permissions: Record<ClassKey, string[]>
  status: RoleStatus
  createdAt?: string
  updatedAt?: string
}

Enums and Types

enum RoleLevel {
  SUPER = 1,    // Super Roles can access all methods without permission checks
  NORMAL = 10   // Normal roles require explicit permissions
}

enum RoleStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum RoleEvents {
  ROLE_CREATE = 'role_create',
  ROLE_UPDATE = 'role_update',
  ROLE_STATUS_UPDATE = 'role_status_update'
}

Additional Structures

interface Permission<T extends string = string, K extends ClassKey = ClassKey> {
  key: T
  classId: K
  label: string
  methods: string[]
}

interface StateManagerActor {
  id: string
  // Additional actor properties
}

Core Functionality

Main Feature Groups

  • Role Lifecycle Management: Create, update, and manage roles with workflow approval integration
  • Permission System: Centralized permission definitions mapped to system classes and methods
  • Authorization Services: Layer-based role deployment for high-performance authorization checks
  • Level-Based Hierarchy: Role level system controlling user management capabilities
  • Status Management: Role activation and deactivation through approval workflows
  • Deployment Integration: Automatic role synchronization with system layers

Workflow Integration

The RoleManager extends WorkflowCompatibleStateManager and integrates with the workflow system:

  • Status Transitions: Workflow rules manage role status changes from inactive to active
  • Events: Role creation, updates, and status changes trigger workflow processing
  • Approval Integration: All significant operations go through approval workflows before completion
  • Business Rules: Workflow configuration defines approval requirements and role hierarchy validation

API Methods

Role Management

  • createRole (WRITE) - Create a new role with Normal level and Inactive status
    • Sets initial status to inactive and triggers role creation workflow
  • updateRole (WRITE) - Update existing role information and permissions
    • Requires role existence validation and triggers update workflow
  • updateStatus (WRITE) - Update role status
    • Manages status transitions through workflow rules

Role Information

  • getRole (READ) - Retrieve role details by ID
  • listRoles (READ) - List roles with filtering and pagination
    • Supports filtering by status and search terms with configurable pagination

Permission Management

  • getPermissions (STATIC) - Get list of all available permissions
    • Returns comprehensive permission mappings across all system classes

Approval Operations

  • approve (QUEUED_WRITE) - Process role approval workflows
    • Applies JSON patches from approval records and updates role status

System Operations

  • getRolesForAuthentication (READ) - Get roles for authentication purposes
    • Optimized for authorization service consumption
  • saveRolesToLayerAndTriggerDeployment (QUEUED_WRITE) - Save roles to the layer and trigger deployment
    • Synchronizes role changes with system infrastructure
  • setState (WRITE) - Set the class state from rio console
    • Administrative method for state management

Method Types:

  • WRITE - Sync state mutation (1-30s)
  • READ - Sync state access (1-30s)
  • QUEUED_WRITE - Async state mutation (1-890s)
  • STATIC - Stateless utility

Key Features

  1. Architecture Pattern: Singleton instance with 'default' ID managing all role configurations
  2. Integration Points: Integrates with ApprovalManager, Workflow system, and RDK Layer deployment
  3. Workflow Support: Full workflow integration with approval processes for all major operations
  4. Security Features: Multi-level role hierarchy with super and normal permission levels
  5. Data Management: Extends WorkflowCompatibleStateManager with hash-based change tracking
  6. External Integrations: Layer-based role deployment with RDK dependency system
  7. Performance Features: Role hash validation, Layer-based caching, and efficient permission mapping
  8. Audit/Logging: Complete activity tracking through workflow system and actor-based operations

Layer System Integration

The RoleManager implements a layer-based caching system that improves performance and reduces costs by minimizing state access during authorization checks.

How the Layer System Works

Layer Deployment Process:

  1. Role Serialization: When roles are updated, RoleManager serializes all active roles into a JSON format
  2. Dependency Creation: Creates a zip file containing nodejs/node_modules/roles/roles.json with current role data
  3. RDK Layer Deployment: Uses rdk.upsertDependency() to create/update the 'roles' dependency layer
  4. Project Deployment: Triggers rdk.deployProject() to make the layer available across all class instances
  5. Hash Tracking: Updates role hash to track changes and prevent unnecessary deployments

Performance Optimization:

  • Fast Import: Authorizers use import('roles/roles.json') for immediate role access without state queries
  • Deployment Cooldown: 3-minute cooldown period prevents excessive deployments during frequent updates
  • Fallback Mechanism: If layer import fails, automatically falls back to getRolesForAuthentication() method call
  • Auto-Recovery: Failed imports trigger automatic layer regeneration and deployment

Layer Management Methods

// Deployment with cooldown protection
saveRolesToLayerAndTriggerDeployment(): Promise<{
  isUpdated: boolean
  deploymentScheduled?: boolean
  nextDeploymentAvailable?: number
  hash: string
}>

// Fallback role retrieval
getRolesForAuthentication(): Promise<{
  roles: Role[]
}>

// Utility for getting roles with layer fallback
getRolesFromLayer(): Promise<Role[]>

Layer File Structure

The deployed layer contains roles in the following structure:

{
  "roles": [
    {
      "id": "superadmin",
      "name": "Super Administrator",
      "level": 1,
      "status": "active",
      "permissions": {
        "RoleManager": ["createRole", "updateRole"],
        "ProgramManagementUser": ["createUser", "updateUser"]
      },
      "createdAt": "2025-09-09T04:33:14.939Z",
      "updatedAt": "2025-09-09T04:33:14.939Z"
    }
  ]
}

Class Relations

The following diagram illustrates how RoleManager integrates with other system components:

RoleManager Relations

LogManager

Overview

LogManager is a singleton class responsible for centralized audit logging of entity changes across the entire system. It serves as the primary audit trail mechanism, capturing detailed information about state modifications, actor identities, and field-level updates.

General Purpose:

  • Audit Trail: Creates comprehensive logs for all entity state changes
  • Compliance: Supports regulatory requirements with detailed change tracking
  • Integration: Works with StateManager to automatically log state modifications
  • Centralized Storage: Uses MongoDB for log storage and querying
  • Architectural Pattern: Singleton class with 'default' instanceId for system-wide logging

Data Structure

State Schema

interface LogManagerState {
  private: {}
  public: {}
}

The LogManager uses minimal state as it operates as a stateless logging service, storing all data in MongoDB.

Log Entry Structure

interface Log {
  id: string
  classId: ClassKey
  entityId: string
  entityType: string
  timeStamp: Date
  isLargeLog: boolean
  fieldUpdates: LogFieldUpdate[]
  actor: StateManagerActor
  additionalData?: Record<string, any>
}

interface LogFieldUpdate {
  key: string
  operation: LogFieldUpdateOperation
  oldValue: string  // JSON encoded
  newValue: string  // JSON encoded
  isLarge?: boolean // Indicates if field data is stored in external file
}

interface LogInDatabase {
  _id: string
  classId: ClassKey
  entityId: string
  entityType: string
  timeStamp: Date
  fieldUpdates: LogFieldUpdate[]
  actor: StateManagerActor
  largeLogPath?: string  // Path to RDK file containing large field values
  additionalData?: Record<string, any>
}

Enums and Types

enum LogFieldUpdateOperation {
  ADD = 'add',
  REMOVE = 'remove',
  REPLACE = 'replace',
  OTHER = 'other'
}

Core Functionality

Audit Trail Management

  • Change Tracking: Records detailed information about entity modifications
  • Actor Attribution: Captures who performed each action with full context
  • Timestamp Recording: Maintains precise timing of all changes
  • Field-Level Granularity: Tracks individual field modifications with before/after values

Large Log Support

  • Size Management: Automatically handles field values exceeding the size limit (1KB per field)
  • Field-Level Storage: Each log field value has a size limit; values exceeding this are marked as large logs
  • External Storage: Stores large field values in RDK file storage (separate from MongoDB)
  • Transparent Retrieval: getLog method automatically reconstructs complete logs by fetching large field data
  • Performance Optimization: List operations exclude large fields for faster pagination
  • File Naming: Uses pattern LARGE_LOG_${entityType}_${entityId}_${logId}.json for large log files

Field Masking Support

  • Sensitive Data Protection: Masks sensitive fields (passwords, PII) in logs
  • Configurable Masking: Supports custom field masking configuration per implementation
  • Privacy Compliance: Ensures audit logs don't expose sensitive information

JSON Patch Integration

  • StateManager Integration: Automatically processes JSON Patch operations from state changes
  • Operation Mapping: Converts JSON Patch operations to structured log entries
  • Comprehensive Coverage: Captures add, remove, replace, and custom operations

API Methods

Log Management

  • addLogEntry (STATIC) - Creates a new log entry for entity changes

    • Automatically detects and handles large field values exceeding the size limit
    • Stores large fields in RDK file storage with metadata in MongoDB
    • Validates log data structure using Zod schema
    • Supports additional metadata for enhanced context
    • Authorization: All class identities allowed
  • getLogEntries (STATIC) - Retrieves paginated log entries for specific entities

    • Supports filtering by classId and entityId
    • Includes pagination with configurable limits (1-100 per page)
    • Returns sorted results with total count and page information
    • Large field values are truncated in list view for performance
    • Authorization: All class identities allowed
  • getLog (STATIC) - Retrieves complete log details including large field values

    • Fetches full log entry with all field values reconstructed
    • Automatically retrieves and merges large field data from RDK storage
    • Returns complete field updates with original values
    • Authorization: program_management_user only

Method Types:

  • STATIC - Stateless utility methods that don't require instance state

Key Features

  1. Architecture Pattern: Singleton class with 'default' instanceId
  2. Integration Points: StateManager integration via LogManagerLogger
  3. Authorization: All class identities for internal operations, program_management_user for getLog method
  4. Data Storage: MongoDB for metadata and regular field values, RDK file storage for large field values
  5. Log Retrieval: LogFetcher service centralizes database and file access
  6. Performance: List queries exclude large field contents, fetched on-demand via getLog
  7. Developer Integration: LogManagerLogger class for StateManager, LogFetcher service for log retrieval
  8. Error Handling: Specific error responses for save failures, fetch failures, and file parsing errors

Service Architecture

LogFetcher Service

classes/LogManager/services/log.fetcher.ts centralizes log retrieval:

  • getLogFromDatabase(logId): Fetches log from MongoDB
  • getLargeLogFile(filename): Retrieves large field values from RDK storage
  • getCompleteLog(logId): Reconstructs log with large fields
  • getLogs(filter, pagination): Fetches paginated logs with filtering

Used by LogManager methods and entity history endpoints in Company, Member, ProgramManagementUser classes.

Class Relations

The following diagram illustrates how LogManager integrates with other system components:

LogManager Relations

FileManager

Overview

FileManager is an instance-based class that provides secure file storage and management capabilities for Rio entities. Each FileManager instance is bound to a specific entity (entityType + entityId) to organize file storage by context, supporting comprehensive file operations with validation, metadata tracking, and token-based security.

General Purpose:

  • Secure File Storage: Manages file uploads, downloads, and deletions with comprehensive validation
  • Entity-Based Organization: Each instance manages files for a specific entity (Member, Company, Tier, etc.)
  • Rio Storage Integration: Leverages Rio's native file storage system for Base64-encoded content
  • Token Security: Provides secure download access through token-based authentication
  • Architectural Pattern: Instance-based with unique instanceId format: entityType_entityId

Data Structure

State Schema

interface FileManagerState {
  private: {
    files: { [fileId: string]: FileMetadata }
    entityType: ClassKey
    entityId: string
    createdAt: Date
    updatedAt: Date
  }
  public: {}
}

File Metadata Structure

interface FileActionHistory {
  action: FileAction
  actor: StateManagerActor
  timestamp: Date
}

interface FileMetadata {
  id: string
  filename: string                    // Generated: entityType_entityId_fileId.ext
  originalFilename: string            // User-provided filename
  fileType: FileType
  mimeType: string
  size: number
  actionHistory: FileActionHistory[]  // Complete audit trail of all file actions
  createdAt: Date
  updatedAt: Date
  status: FileStatus
  isPublic: boolean                   // Flag to mark file as publicly accessible
}

Enums and Types

enum FileType {
  IMAGE = 'image',      // Max 5MB: jpeg, jpg, png, gif, webp
  JSON = 'json',        // Max 5MB: application/json, text/json
  DOCUMENT = 'document' // Max 10MB: pdf, doc, docx, xls, xlsx, txt, csv
}

enum FileAction {
  UPLOAD = 'upload',
  DELETE = 'delete'
}

enum FileStatus {
  ACTIVE = 'active',
  DELETED = 'deleted'
}

Core Functionality

File Storage Management

  • Upload Processing: Base64 content validation, MIME type verification, and metadata creation
  • File Retrieval: Secure access to file content with comprehensive metadata
  • Deletion Management: Soft deletion with status tracking and physical removal from storage
  • Download Streaming: Token-based secure downloads with cache headers

Entity-Based Organization

  • Instance Binding: Each FileManager instance is dedicated to a specific entity
  • Filename Generation: Systematic naming convention: {entityType}_{entityId}_{fileId}.{extension}
  • Metadata Tracking: Complete audit trail with actor attribution and timestamp tracking
  • File Identification: Support for both fileId and filename-based operations

Security and Validation

  • Comprehensive Validation: File format, size limits, and MIME type verification
    • IMAGE: Max 5MB - jpeg, jpg, png, gif, webp
    • JSON: Max 5MB - application/json, text/json
    • DOCUMENT: Max 10MB - pdf, doc, docx, xls, xlsx, txt, csv
  • Token Authentication: Secure download access through JWT-based tokens (bypasses standard role authorization)
  • Authorization Integration: Universal class access for upload/get/delete operations through RoleManager
  • Content Verification: Base64 content analysis and format validation

API Methods

Core File Operations

  • uploadFile (WRITE) - Upload files with comprehensive validation and metadata tracking

    • Validates file format, size (5MB for images/JSON, 10MB for documents), and MIME type consistency
    • Supports three file types: IMAGE, JSON, and DOCUMENT
    • Generates unique fileId and systematic filename
    • Stores Base64 content in Rio file storage system
    • Accepts optional isPublic parameter (default: false) to mark files as publicly accessible via getPublicFile endpoint
    • Accepts optional actor parameter for proxied calls (preserves actor when called from other classes)
  • getFile (READ) - Retrieve file content as Base64 with complete metadata

    • Supports lookup by fileId or filename
    • Returns comprehensive file metadata and content
    • Validates file status and existence
  • deleteFile (WRITE) - Permanently delete files from storage and update metadata

    • Supports deletion by fileId or filename
    • Updates metadata status and removes from Rio storage
    • Provides deletion confirmation with timestamp
    • Accepts optional actor parameter for proxied calls (preserves actor when called from other classes)
  • downloadFile (READ) - Download files with cache headers using access tokens

    • Requires valid access token for authentication (no role-based authorization)
    • Token validation includes filename verification for security
    • Optimized delivery with cache control headers
  • getPublicFile (READ) - Serve files publicly without authentication

    • Only accessible for files marked as public (isPublic: true) during upload
    • Returns 403 error for non-public files
    • Optimized delivery with 30-minute cache headers
    • No authentication required

Instance Management

  • init (INIT) - Initialize FileManager instance for entity-specific file management

    • Binds instance to entityType and entityId
    • Sets up file storage structure and metadata tracking
  • getState (INTERNAL) - Retrieve complete instance state for debugging

  • getInstanceId (INTERNAL) - Generate instanceId from entity information

Method Types:

  • WRITE - Sync state mutation (1-30s) - File operations with immediate metadata updates
  • READ - Sync state access (1-30s) - File retrieval and content access
  • INIT - Instance initialization with entity binding

Key Features

  1. Architecture Pattern: Instance-based class with entity-specific file management using entityType_entityId instanceId format
  2. Integration Points: Deep integration with Rio file storage system, RoleManager for authorization, and StateManager for metadata tracking
  3. Security Features: Token-based download authentication (bypasses role authorization), public file access control with isPublic flag, comprehensive file validation, universal class access for upload/get/delete operations
  4. Data Management: FileStateManager for metadata operations, systematic filename generation, and comprehensive audit trails
  5. Performance Features: Base64 content processing, cache headers for downloads and public files, and optimized Rio storage integration
  6. External Integrations: Rio native file storage system for persistent file management
  7. Validation System: Multi-layer validation including file format, MIME type verification, size limits (5MB for images/JSON, 10MB for documents), and content analysis with support for three file types (IMAGE, JSON, DOCUMENT)
  8. Audit/Logging: Complete file operation tracking with actor attribution, timestamps, and status management

Class Relations

The following diagram illustrates how FileManager integrates with other system components:

FileManager Relations

ContentManager

Overview

ContentManager is a singleton class that provides comprehensive content management capabilities for the Rio platform. It manages dynamic content for login, onboarding, and homepage screens with schema-based validation, automatic image processing, and workflow-based approval integration.

General Purpose:

  • Dynamic Content Management: Manages content for login screens, onboarding flows, and homepage sections
  • Schema-Based Validation: Enforces content structure through predefined schemas for each content type
  • Automatic Image Processing: Detects base64 images, uploads to FileManager, and generates public URLs
  • Workflow Integration: Supports approval workflows for content creation and status changes
  • Architectural Pattern: Singleton instance with 'default' instanceId

Data Structure

State Schema

interface ContentManagerState {
  private: {
    contents: Content[]
  }
  public: {}
}

Content Structure

interface Content {
  id: string
  contentKey: ContentKey
  contentGroupKey: ContentGroupKey
  contentTitle: string            // Content title (mandatory)
  status: ContentStatus
  startDate?: string              // ISO 8601 datetime
  endDate?: string                // ISO 8601 datetime
  order?: number                  // Display order for sorting
  fields: Record<string, any>     // Schema-validated content fields
  createdBy: string
  createdAt: string
  updatedAt: string
}

Enums and Types

enum ContentStatus {
  PENDING = 'pending',
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum ContentGroupKey {
  LOGIN = 'login',
  ONBOARDING = 'onboarding',
  HOMEPAGE = 'homepage'
}

enum ContentKey {
  LOGIN_LOGIN = 'login_login',
  ONBOARDING_ONBOARDING = 'onboarding_onboarding',
  HOMEPAGE_HERO_BANNER = 'homepage_hero_banner',
  HOMEPAGE_TOP_SLIDER = 'homepage_top_slider',
  HOMEPAGE_BOTTOM_SLIDER = 'homepage_bottom_slider',
  HOMEPAGE_SECTION = 'homepage_section'
}

enum ContentFieldType {
  BOOLEAN = 'boolean',
  TEXT = 'text',
  NUMBER = 'number',
  RICHTEXT = 'richtext',
  IMAGE = 'image',
  DATETIME = 'datetime',
  ARRAY = 'array',
  ENUM = 'enum',
  COLOR = 'color'
}

enum ContentEvents {
  CONTENT_CREATE = 'content_create',
  CONTENT_UPDATE = 'content_update',
  CONTENT_STATUS_UPDATE = 'content_status_update'
}

Content Groups and Schemas

Content Groups organize related content types:

  • Login: Login screen backgrounds and visuals
  • Onboarding: Onboarding screen content with titles, descriptions, images
  • Homepage: Hero banners, sliders, and dynamic sections

Content Schemas define field structure for each content type:

  • Login Login: Background image field
  • Onboarding: Title, description, image, gradient color
  • Homepage Hero Banner: Image and optional description
  • Homepage Slider: Image and action URL
  • Homepage Section: Entity type, sort field, and filter configuration

Homepage Section Filter Fields: The Homepage Section content type includes comprehensive filter fields for dynamic entity queries:

  • entityType (ENUM): offer | voucher | event - Required field to specify entity type
  • sortField (ENUM): relevance | distance | newest | featured - Required sort order
  • filterOfferTypes (ENUM, multi-select): Filter by offer types (values from OfferType enum)
  • filterCategories (ENUM, multi-select): Filter by categories (dynamic values fetched from active BenefitCategory records at request time)
  • filterSubcategories (ENUM, multi-select): Filter by subcategories (dynamic values fetched from active BenefitCategory subcategories at request time)
  • filterFeaturedOnly (BOOLEAN): Show only featured offers
  • filterCreatedAtStart / filterCreatedAtEnd (DATETIME): Filter by creation date range
  • filterStartDateStart / filterStartDateEnd (DATETIME): Filter by offer start date range
  • filterViewStartDateStart / filterViewStartDateEnd (DATETIME): Filter by visibility date range

Enum Value Format: All ENUM fields return key/value pairs for UI rendering:

interface EnumKeyValue {
    key: string   // For static enums: Enum key (e.g., 'DISCOUNT')
                  // For dynamic enums: Database ID (e.g., '507f1f77bcf86cd799439011')
    value: string // For static enums: Enum value (e.g., 'discount')
                  // For dynamic enums: Display name (e.g., 'Health & Wellness')
}

Dynamic Enum Loading:

  • Category and subcategory enum values are fetched dynamically from BenefitCategory collection
  • Only active categories/subcategories are returned
  • Values are populated at request time in getContentSchemas endpoint
  • Categories include id (key) and name (value)
  • Subcategories include id (key) and name (value)

Core Functionality

Content Management

  • CRUD Operations: Create, read, update content with comprehensive validation
  • Status Management: Control content lifecycle (pending, active, inactive)
  • Date-Based Publishing: Support for start/end dates to control content visibility
  • Order Management: Optional ordering for content display sequences
  • Filtering: Filter content by group, key, or status

Image Processing

  • Automatic Detection: Identifies base64-encoded images in content fields
  • FileManager Integration: Uploads images to FileManager with systematic naming
  • Public URL Generation: Enhances responses with public image URLs in nested images object
  • Format Support: JPEG, PNG, GIF, WebP with MIME type validation
  • Filename Management: Generates unique filenames for uploaded images

Schema-Based Validation

  • Field Validation: Validates content fields against contentKey-specific Zod schemas
  • Type Safety: Ensures field types match schema definitions
  • Group Constraints: Validates contentKey is allowed in specified contentGroupKey
  • Date Validation: Ensures startDate is before endDate when both provided
  • Required Fields: Enforces mandatory fields based on content type

Metadata Operations

  • Content Group Definitions: Provides metadata about available content groups
  • Schema Definitions: Returns field definitions for UI rendering (type, label, validation rules)
  • Public Access: Metadata endpoints accessible without authentication
  • UI Support: Field metadata includes placeholders, validation rules, and optional flags

Workflow Integration

ContentManager extends WorkflowCompatibleStateManager to support approval workflows:

  • Status Transitions: Workflow rules can control status changes between pending, active, and inactive
  • Events: Three workflow events trigger processing:
    • CONTENT_CREATE: Fired when new content is created
    • CONTENT_UPDATE: Fired when content fields are updated
    • CONTENT_STATUS_UPDATE: Fired when content status changes
  • Approval Integration: Works with ApprovalManager for multi-step approval processes
  • Business Rules: Workflow configuration defines allowed transitions and approval requirements

API Methods

Content CRUD Operations

  • createContent (WRITE) - Create new content with automatic image processing

    • Validates contentKey is allowed in contentGroupKey
    • Processes base64 images and uploads to FileManager
    • Validates fields against contentKey schema
    • Executes workflow for approval processing
    • Returns created content ID
  • updateContent (WRITE) - Update existing content with optional image processing

    • All fields optional except ID
    • Processes new base64 images if provided
    • Validates updated fields against schema
    • Executes workflow for approval processing
    • Returns updated content ID
  • updateContentStatus (WRITE) - Update content status

    • Changes status between pending, active, inactive
    • Executes workflow for approval processing
    • Returns updated content ID
  • getContent (READ) - Retrieve single content by ID

    • Returns content with enhanced image URLs
    • Images accessible via nested fields.images object
    • Public URLs generated via FileManager
  • getContents (READ) - List active contents with filtering (client access)

    • Only returns contents with status 'active'
    • Filter by contentGroupKeys or contentKeys (query string parameters)
    • Three-tier sorting: 1) Schema order (descending), 2) Content order (descending), 3) updatedAt (descending)
    • All images enhanced with public URLs
    • Returns simplified content objects with id, contentKey, contentGroupKey, status, order, fields
    • Accessible by all user identities
  • getContentsForBackoffice (READ) - List all contents with filtering (backoffice access)

    • Returns contents with any status (pending, active, inactive)
    • Filter by contentGroupKeys, contentKeys, or statuses (body parameters)
    • Sorted by order (descending) then updatedAt (descending)
    • All images enhanced with public URLs
    • Returns full content objects
    • Only accessible by program_management_user

Metadata Operations

  • getContentGroup (READ) - Get content group definition

    • Returns group metadata including allowed content keys
    • No authentication required
  • listContentGroups (READ) - List all content group definitions

    • Returns all available content groups
    • No authentication required
  • getContentSchemas (READ) - Get content schema definitions

    • Returns field metadata for UI rendering
    • Filter by contentGroupKey or contentKey
    • Includes field types, labels, validation rules, placeholders
    • ENUM fields return key/value pairs with enumValues: [{ key, value }]
    • Multi-select ENUMs indicated by isMultiSelect: true field property
    • Dynamic enums (filterCategories, filterSubcategories) fetched from active BenefitCategory records at request time
    • Static enums (entityType, sortField, filterOfferTypes) use enum-to-key-value conversion
    • No authentication required

Approval Operations

  • approveContent (QUEUED_WRITE) - Approve content changes
    • Called internally by ApprovalManager
    • Updates content status based on approval record
    • Only accessible by ApprovalManager class

Method Types:

  • WRITE - Sync state mutation (1-30s)
  • READ - Sync state access (1-30s)
  • QUEUED_WRITE - Async state mutation (1-890s)

Key Features

  1. Architecture Pattern: Singleton class with 'default' instanceId for centralized content management across all content types
  2. Integration Points: Deep integration with FileManager for image storage, WorkflowExecuter for approval flows, and ApprovalManager for status change approvals
  3. Workflow Support: Full workflow integration with status-based approval rules, supports content creation, update, and status change events
  4. Schema-Based Validation: Comprehensive Zod schema validation for each content type, ensures data integrity and type safety
  5. Image Processing: Automatic base64 detection, FileManager upload integration, public URL generation
  6. Data Management: ContentManagerStateManager for state operations, supports filtering, sorting, pagination, and date-based content visibility
  7. Metadata System: Public endpoints for content group and schema definitions, supports dynamic UI generation based on field metadata, dynamic enum loading for categories/subcategories from BenefitCategory
  8. Security Features: Role-based authorization for CRUD operations, public access for metadata endpoints, ApprovalManager-only access for approval methods
  9. Audit/Logging: Complete content lifecycle tracking with createdBy, createdAt, updatedAt timestamps, and LogManager integration
  10. Content Organization: Three-tier structure (ContentGroup → ContentKey → Fields) with validation at each level, supports multiple content types per group

SystemEmail

Overview

The SystemEmail class manages email template configuration and email delivery services across the platform. It provides template-based email management with approval workflows and AWS SES integration for email delivery.

General Purpose:

  • Email template management with dynamic content and approval workflows
  • Email delivery for member, program management, and system notifications
  • Template-based email system with parameter mapping and rendering capabilities
  • Template-based architecture using template IDs as instance identifiers
  • Integration with approval workflows for template changes and email operations

Data Structure

State Schema

interface SystemEmailState {
  private: {
    template: EmailTemplate
  }
  public: object
}

Enums and Types

enum SystemEmailEvents {
  SYSTEM_EMAIL_UPDATE = 'system_email_update',
  SYSTEM_EMAIL_STATUS_UPDATE = 'system_email_status_update'
}

enum SystemEmailType {
  MEMBER = 'member',
  PROGRAM_MANAGEMENT = 'program_management',
  SYSTEM = 'system'
}

enum SystemEmailStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

Additional Structures

interface EmailTemplate {
  type: SystemEmailType
  status: SystemEmailStatus
  to: string[]
  title: string
  subject: string
  json: string
  html: string
}

interface CreateSystemEmailInput {
  templateId: SystemEmailTemplateIds
  to?: string[]
  status: SystemEmailStatus
  subject: string
  html: string
  json: string
  title: string
  type: SystemEmailType
}

interface UpdateSystemEmailTemplateInput {
  to?: string[]
  subject: string
  html: string
  json: string
  title: string
}

interface SendSystemEmailInput {
  to?: string[]
  parameters: any
}

Core Functionality

Main Feature Groups

  • Template Management: Email template creation, modification, and lifecycle management with approval workflows
  • Email Delivery: Email sending with parameter mapping and dynamic content rendering using AWS SES
  • Approval Integration: Workflow-based approval system for template changes and email operations
  • Content Rendering: Template rendering with parameter substitution and dynamic content generation
  • Multi-Type Support: Support for member notifications, program management communications, and system alerts
  • Status Management: Template activation/deactivation with workflow integration for operational control

Workflow Integration

The SystemEmail class extends WorkflowCompatibleStateManager and integrates with the workflow system:

  • Status Transitions: Workflow rules manage template status changes between active and inactive states
  • Events: System email update and status update events trigger workflow processing
  • Approval Integration: Template modifications require approval through ApprovalManager integration
  • Business Rules: Configurable workflow rules control template lifecycle and operational constraints

API Methods

Template Management

  • updateSystemEmailTemplate (WRITE) - Update system email template

    • Modify existing email templates with approval workflow integration
    • Supports dynamic content updates and recipient list modifications
  • getSystemEmailTemplate (READ) - Get system email template

    • Retrieve specific email template details and configuration
  • listSystemEmailTemplates (READ) - Get all system email templates

    • Access complete template library with filtering and status information
  • getSystemEmailTemplateFields (READ) - Get system email template fields

    • Retrieve template field definitions and parameter mapping information

Email Operations

  • sendSystemEmail (QUEUED_WRITE) - Send system emails
    • Execute email delivery with parameter mapping and template rendering
    • Support for dynamic recipient lists and content personalization

Approval Operations

  • approve (QUEUED_WRITE) - Approve email template changes
    • Process approval workflows for template modifications and status changes

Key Features

  1. Architecture Pattern: Template-based instances with template IDs as instance identifiers for template-specific management
  2. Integration Points: Authorized for use by all classes but implementation not yet present in other classes
  3. Workflow Support: Full workflow integration for template approval and status management operations
  4. Security Features: Approval-based template modifications and role-based access control for email operations
  5. Data Management: Template-based state management with workflow-compatible state transitions
  6. External Integrations: AWS SES integration for email delivery with support for HTML and text content
  7. Performance Features: Template rendering with parameter mapping and dynamic content generation
  8. Audit/Logging: Complete tracking of template changes, email deliveries, and approval workflows

Class Relations

The following diagram illustrates how SystemEmail integrates with other system components:

SystemEmail Relations

Otp

Overview

The Otp class provides One-Time Password (OTP) record storage and management for authentication flows. It functions as a storage service that manages OTP records and their validation history, enabling other classes to implement secure authentication workflows.

General Purpose:

  • OTP record storage and history tracking for authentication workflows
  • Instance-based architecture with classKey_entityId instance IDs for entity-specific OTP management
  • State-based persistence with comprehensive audit trails for all validation attempts
  • Integration point for classes requiring OTP-based authentication (Member registration, verification flows)

Data Structure

State Schema

interface OTPState {
  private: {
    associatedClassKey: ClassKey
    associatedEntityId: string
    records: Array<OTP & { history: OTPCheckHistoryRecord[] }>
  }
  public: object
}

Enums and Types

enum TokenType {
  ALPHA_NUMERIC = 'alphanumeric',
  NUMERIC = 'numeric',
  UUID = 'uuid'
}

enum CheckOTPResult {
  RETRY_LIMIT_EXCEED = 'retry_limit_exceed',
  OTP_LIMIT_EXCEED = 'otp_limit_exceed',
  NO_ACTIVE_OTP = 'no_active_otp',
  INVALID_TOKEN = 'invalid_token'
}

Error Responses:

The OTP class defines the following error responses with proper HTTP status codes and localized messages:

  • OTP_LIMIT_EXCEEDED (6001, 429): Thrown when too many OTP creation requests are made within the allowed time window
  • OTP_RETRY_LIMIT_EXCEEDED (6002, 429): Thrown when too many failed OTP validation attempts occur within the retry window

These errors are thrown as ErrorResponse objects by the OTPManager service and can be caught and handled by consuming classes like Member.


### Additional Structures

```typescript
interface OTP {
  id: string
  otpType: string
  token: string
  tokenType: TokenType
  createdAt: Date
  usedAt?: Date
  additionalData?: Record<string, any>
}

interface OTPCheckHistoryRecord {
  timestamp: Date
  isSuccessful: boolean
  validationResult?: CheckOTPResult
  requestedBy: string
  requesterDetails: {
    identity: string
    userAgent?: string
    ipAddress?: string
  }
  additionalData?: Record<string, any>
}

interface OTPConfig {
  otpLimit: number
  otpExpireTimeInSeconds: number
  retryLimit: number
  retryExpireTimeInSeconds: number
}

Core Functionality

Main Feature Groups

  • OTP Record Storage: Persistent storage of OTP records with comprehensive metadata including token type, creation time, and usage status
  • History Tracking: Complete audit trail of all validation attempts with requester details, timestamps, and validation results
  • Type-Based Filtering: Ability to retrieve OTP records filtered by type for different authentication workflows
  • Entity Association: Each OTP instance is associated with a specific class and entity through the instance ID pattern
  • State Management: Centralized state management through OtpStateManager for consistent data handling

Internal Architecture

  • OtpStateManager: Core state management service extending StateManager pattern for consistent OTP data handling
  • OTP Storage Model: Direct state-based storage using the Rio instance state system
  • History Management: Embedded history records within each OTP for complete audit trails

API Methods

OTP Management

  • createOtpRecord (QUEUED_WRITE) - Create a new OTP record

    • Stores OTP record with comprehensive metadata (token, type, timestamps)
    • Initializes empty history array for future validation tracking
  • createOtpCheckRecord (QUEUED_WRITE) - Create a new OTP check record

    • Adds validation attempt history to existing OTP record
    • Records requester details, success status, and additional metadata
  • getOtpRecords (READ) - Retrieve OTP records

    • Filters and returns OTP records by type with complete validation history
    • Enables type-specific OTP retrieval for different authentication flows

Key Features

  1. Architecture Pattern: Instance-based with classKey_entityId format for entity-specific OTP management
  2. Integration Points: Storage service for classes requiring OTP authentication (Member, ProgramManagementUser)
  3. Data Management: State-based persistence with OtpStateManager following established StateManager patterns
  4. Security Features: Complete audit trails with validation history and requester tracking
  5. Token Support: Supports multiple token types (ALPHA_NUMERIC, NUMERIC, UUID) with flexible metadata
  6. Authorization: Restricted access - only ProgramManagementUser and Member class identities can access OTP methods
  7. Audit/Logging: Comprehensive history tracking for all validation attempts with timestamps and requester details
  8. Performance Features: Type-based filtering for efficient OTP retrieval in authentication workflows
  9. Error Handling: Proper error responses with HTTP 429 status codes for rate limiting violations (OTP creation limits and retry limits)

Class Relations

The following diagram illustrates how Otp integrates with other system components:

Otp Relations

Setting

< - Configuration Management

Overview

The Setting class manages system configuration and reference data for the entire platform. It provides centralized configuration management including company groups, member types, tier definitions, and global settings with streaming capabilities for data distribution.

General Purpose:

  • System configuration and reference data management
  • Centralized settings for company groups, member types, and tier configurations
  • Global settings with streaming capabilities for real-time data distribution
  • Singleton architecture with 'default' instance ID
  • Integration point for all classes requiring configuration data

Data Structure

State Schema

interface SettingState {
  private: {
    settings: {
      [SettingTypes.CompanyGroups]: {
        title: string
        description: string
        value: CompanyGroupSettingValue[]
      }
      [SettingTypes.MemberSubType]: {
        title: string
        description: string
        value: MemberSubTypeSettingValue[]
      }
      [SettingTypes.TierTypes]: {
        title: string
        description: string
        value: TierTypeSettingValue[]
      }
      [SettingTypes.TierConfig]: {
        title: string
        description: string
        value: TierConfigSettingValue
      }
      [SettingTypes.MemberType]: {
        title: string
        description: string
        value: MemberTypeSettingValue[]
      }
    }
  }
  public: object
}

Enums and Types

enum CompanyGroupStatus {
  PENDING = 'pending',
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum MemberSubTypeStatus {
  PENDING = 'pending',
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum TierGroup {
  BASE = 'base',
  UPGRADE = 'upgrade',
  ADD_ON = 'add_on'
}

enum TierPaymentType {
  CREDIT_CARD = 'credit_card',
  SALARY_DEDUCTION = 'salary_deduction'
}

enum TierTypeStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum CompanyGroupType {
  INTERNAL = 'internal',
  EXTERNAL = 'external'
}

enum MemberTypeStatus {
  PENDING = 'pending',
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

// Updatable status definitions using const object pattern for better type safety
const UpdatableCompanyGroupStatus = {
  ACTIVE: CompanyGroupStatus.ACTIVE,
  INACTIVE: CompanyGroupStatus.INACTIVE
} as const

const UpdatableMemberSubTypeStatus = {
  ACTIVE: MemberSubTypeStatus.ACTIVE,
  INACTIVE: MemberSubTypeStatus.INACTIVE
} as const

const UpdatableTierTypeStatus = {
  ACTIVE: TierTypeStatus.ACTIVE,
  INACTIVE: TierTypeStatus.INACTIVE
} as const

const UpdatableMemberTypeStatus = {
  ACTIVE: MemberTypeStatus.ACTIVE,
  INACTIVE: MemberTypeStatus.INACTIVE
} as const

Additional Structures

interface CompanyGroupSettingValue {
  id: string
  name: string
  description?: string
  status: CompanyGroupStatus
  type: CompanyGroupType
  createdBy: StateManagerActor
  createdAt: Date
  updatedAt: Date
}

interface TierTypeSettingValue {
  id: string
  tierGroup: TierGroup
  name: string
  description?: string
  status: TierTypeStatus
  createdBy: StateManagerActor
  createdAt: Date
  updatedAt: Date
}

interface TierConfigSettingValue {
  paymentPeriods: PaymentPeriodSettingValue[]
}

interface PaymentPeriodSettingValue {
  key: string
  label: string
}

interface MemberTypeSettingValue {
  id: string
  name: string
  description?: string
  status: MemberTypeStatus
  systemIdentifier: string
  createdBy: StateManagerActor
  createdAt: Date
  updatedAt: Date
}

Core Functionality

Main Feature Groups

  • Global Settings Management: Centralized storage and retrieval of system-wide configuration settings
  • Company Group Configuration: Management of company groupings with status tracking and categorization
  • Member Type Management: Definition and management of member types with lifecycle control
  • Member Subtype Management: Granular member categorization with status and approval workflows
  • Tier Configuration: Comprehensive tier type management with payment configurations and grouping
  • Streaming Capabilities: Real-time data distribution to MongoDB for external system integration
  • Program Configuration: Management of program-specific settings and business rules

API Methods

Configuration Management

  • setState (WRITE) - Set the class state from rio console

    • Administrative state management for configuration updates
  • getSetting (READ) - Get setting for client

    • Retrieve specific setting values with client-appropriate formatting
  • listSettings (READ) - List settings

    • Returns complete settings overview for administrative interfaces

Company Group Management

  • listCompanyGroups (READ) - List company groups

    • Retrieve all company groups with filtering and pagination
  • getCompanyGroup (READ) - Get company group by id

    • Fetch specific company group details
  • updateCompanyGroup (WRITE) - Update company group by id

    • Modify existing company group with audit tracking
  • createCompanyGroup (WRITE) - Create new company group

    • Add new company groupings with validation and streaming
  • updateCompanyGroupStatus (WRITE) - Update company group status by id

    • Update company group status (active/inactive) with audit tracking

Member Type Management

  • createMemberType (WRITE) - Create new member type

    • Define new member types with status tracking
  • updateMemberType (WRITE) - Update member type by id

    • Modify existing member type configurations
  • getMemberType (READ) - Get member type by id

    • Retrieve specific member type details
  • listMemberTypes (READ) - List member types

    • Access all member types with filtering options
  • updateMemberTypeStatus (WRITE) - Update member type status by id

    • Update member type status (active/inactive) with audit tracking

Member Subtype Management

  • createMemberSubType (WRITE) - Create new member subtype

    • Define granular member categorizations
  • updateMemberSubType (WRITE) - Update member subtype by id

    • Modify existing member subtype definitions
  • getMemberSubType (READ) - Get member subtype by id

    • Retrieve specific member subtype details
  • listMemberSubTypes (READ) - List member subtypes

    • Access all member subtypes with status filtering
  • updateMemberSubTypeStatus (WRITE) - Update member subtype status by id

    • Update member subtype status (active/inactive) with audit tracking

Tier Management

  • createTierType (WRITE) - Create new tier type

    • Define tier types with payment configurations and grouping
  • updateTierType (WRITE) - Update tier type by id

    • Modify existing tier type settings and configurations
  • getTierType (READ) - Get tier type by id

    • Retrieve specific tier type details with payment configurations
  • listTierTypes (READ) - List tier types

    • Access all tier types with filtering by group and status
  • updateTierTypeStatus (WRITE) - Update tier type status by id

    • Update tier type status (active/inactive) with audit tracking
  • getPaymentPeriods (READ) - Get payment periods configuration

    • Retrieve available payment period configurations for tier setup

Program Configuration

  • getProgramManagementConfig (READ) - Get program management configuration
    • Retrieve current program configuration settings including all entity status enums

Data Streaming

  • streamTierType (WRITE) - Stream tier type data to MongoDB

    • Real-time streaming of tier type data to external MongoDB collection
  • streamMemberType (WRITE) - Stream member type data to MongoDB

    • Real-time streaming of member type data to external MongoDB collection
  • streamMemberSubType (WRITE) - Stream member subtype data to MongoDB

    • Real-time streaming of member subtype data to external MongoDB collection
  • streamCompanyGroup (WRITE) - Stream company group data to MongoDB

    • Real-time streaming of company group data to external MongoDB collection

Key Features

  1. Architecture Pattern: Singleton class with 'default' instance ID for centralized configuration management
  2. Integration Points: Core dependency for Member, Company, Tier, and other entity classes requiring configuration data
  3. Security Features: Role-based access control for configuration management and audit tracking for all changes
  4. Data Management: State with real-time streaming to MongoDB
  5. Performance Features: Centralized caching of configuration data for optimal performance across the platform
  6. Audit/Logging: Complete tracking of all configuration changes with actor information and timestamps
  7. Program Configuration: Provides centralized management of all entity status configurations and enums

Class Relations

The following diagram illustrates how Setting integrates with other system components:

Setting Relations

NotificationManager

Overview

The NotificationManager class is responsible for managing notification templates and delivering multi-channel notifications (email, in-app, SMS) across the platform. It combines template management with notification delivery capabilities in a single Rio class.

General Purpose:

  • Manage notification templates with multi-channel configurations
  • Send notifications via email, in-app, and SMS channels
  • Support templated content with dynamic parameter substitution
  • Integrate with workflow and approval systems for template changes
  • Provide centralized notification orchestration for the platform

Architecture Pattern:

  • Instance-based class where each instance represents a notification template
  • instanceId = templateId (e.g., OTP_PROGRAM_MANAGEMENT_INVITE)
  • Templates are stored in both Rio state and MongoDB for efficient querying

Data Structure

State Schema

interface NotificationManagerState {
    private: {
        template: NotificationTemplateData
    }
    public: {}
}

interface NotificationTemplateData {
    templateId: string
    title: string
    description: string
    status: NotificationTemplateStatus
    channels: Record<NotificationChannel, NotificationChannelContent>
}

Enums and Types

enum NotificationChannel {
    EMAIL = 'email',
    IN_APP = 'in_app',
    SMS = 'sms'
}

enum NotificationTemplateStatus {
    ACTIVE = 'active',
    INACTIVE = 'inactive'
}

enum NotificationTemplateEvents {
    TEMPLATE_UPDATE = 'template_update',
    CHANNEL_UPDATE = 'channel_update',
    STATUS_UPDATE = 'status_update'
}

Channel Content Structures

Each notification channel has its own content structure:

Email Channel:

{
    channel: NotificationChannel.EMAIL,
    enabled: boolean,
    to: string[],           // Default recipient emails
    subject: string,        // Email subject template
    json: string,          // JSON email template
    html: string           // HTML email template
}

In-App Channel:

{
    channel: NotificationChannel.IN_APP,
    enabled: boolean,
    subject: string,        // Notification title
    content: string,        // Notification content template
    metadata?: Record<string, any>  // Optional metadata
}

SMS Channel:

{
    channel: NotificationChannel.SMS,
    enabled: boolean,
    content: string,        // SMS message template
    to?: string[]          // Optional default phone numbers
}

Core Functionality

Template Management

  • Template Creation: Initialize notification templates with default configurations
  • Template Updates: Modify template title, description, and metadata
  • Channel Configuration: Update individual channel settings (email, in-app, SMS)
  • Status Management: Activate or deactivate templates
  • MongoDB Sync: Templates are automatically synced to MongoDB for efficient querying

Multi-Channel Notification Delivery

The sendNotification method orchestrates notification delivery across configured channels:

  1. Template Retrieval: Gets template from instance state (instanceId = templateId)
  2. Status Check: Only sends if template status is ACTIVE
  3. Channel Processing:
    • Email: Renders HTML/JSON templates and sends via AWS SES
    • In-App: Creates tasks to add notifications to UserNotification instances
    • SMS: (Future implementation)
  4. Template Rendering: Supports dynamic parameter substitution using {{parameter}} syntax

Workflow Integration

NotificationManager extends WorkflowCompatibleStateManager and integrates with the approval system:

  • Events: TEMPLATE_UPDATE, CHANNEL_UPDATE, STATUS_UPDATE
  • Approval Integration: Template changes can require approval based on workflow rules
  • Status Transitions: Workflow rules control status changes (active ↔ inactive)

API Methods

Notification Delivery

  • sendNotification (READ) - Send notification via configured channels
    • Permission: All ClassIdentities (internal service method)
    • instanceId: Template ID (e.g., OTP_PROGRAM_MANAGEMENT_INVITE)
    • Input: { to: string[], parameters: Record<string, any> }
    • Returns: 204 No Content on success

Template Management Methods

  • updateNotificationTemplate (WRITE) - Update template title and description

    • Permission: program_management_user
    • Input: { title?: string, description?: string }
    • Workflow: Triggers TEMPLATE_UPDATE event
  • updateNotificationChannel (WRITE) - Update channel configuration

    • Permission: program_management_user
    • Input: { channel: NotificationChannel, content: NotificationChannelContent }
    • Workflow: Triggers CHANNEL_UPDATE event
  • updateNotificationTemplateStatus (WRITE) - Change template status

    • Permission: program_management_user
    • Input: { status: NotificationTemplateStatus }
    • Workflow: Triggers STATUS_UPDATE event
  • approve (WRITE) - Approve template changes (internal)

    • Permission: ApprovalManager
    • Input: CommonApprovalInput with optional JSON patch

Template Retrieval

  • getNotificationTemplate (READ) - Get template details

    • Permission: program_management_user, NotificationManager (for internal calls)
    • Returns: Template object
  • listNotificationTemplates (STATIC) - List all templates with pagination

    • Permission: program_management_user
    • Input: { page?: number, limit?: number, status?: NotificationTemplateStatus, search?: string }
    • Returns: Paginated list of templates from MongoDB

Key Features

  1. Multi-Channel Support

    • Email delivery via AWS SES
    • In-app notifications via UserNotification class
    • SMS support (placeholder for future implementation)
  2. Template Rendering

    • Dynamic parameter substitution using {{parameter}} syntax
    • Separate templates for each channel
    • Fallback to template title for missing subjects
  3. Flexible Recipient Management

    • Runtime recipients (passed in to parameter)
    • Default recipients (configured in channel settings)
    • Automatic merging of both recipient lists
  4. Approval & Workflow

    • All template changes can be routed through approval workflow
    • JSON patch support for granular approvals
    • Event-driven architecture for status transitions
  5. MongoDB Integration

    • Templates automatically streamed to MongoDB
    • Efficient querying and search capabilities
    • Pagination support for large template lists

Integration Guide

Sending Notifications from Other Classes

Use the createNotificationTask utility function:

import { createNotificationTask } from '../NotificationManager/util/notification.task'
import { NotificationTemplateIds } from 'common/common.models'

// In your method handler (async function)
await createNotificationTask(
    NotificationTemplateIds.Values.OTP_PROGRAM_MANAGEMENT_INVITE,
    {
        to: ['user@example.com'],
        parameters: {
            otp: '123456',
            userName: 'John Doe',
        },
    },
)

Auto-Initialization:
The utility automatically initializes notification templates on first use. If the template instance doesn't exist, it will:

  1. Create the template with default settings
  2. Retry sending the notification
  3. Subsequent calls will send immediately

Important Notes:

  • The function is async - always use await
  • No need to pass data.tasks - uses direct RDK method calls
  • Template is auto-created if missing (404 error handling)
  • All parameters must be strings (for template rendering)

Template Parameter Examples

Templates use {{parameterName}} syntax for substitution:

Email Template:

<h1>Welcome {{userName}}!</h1>
<p>Your OTP code is: <strong>{{otp}}</strong></p>

Parameters:

{
    userName: 'John Doe',
    otp: '123456'
}

Rendered Output:

<h1>Welcome John Doe!</h1>
<p>Your OTP code is: <strong>123456</strong></p>

Template Defaults

Template defaults are defined in constants/template.defaults.ts:

  • OTP_PROGRAM_MANAGEMENT_INVITE
  • OTP_PROGRAM_MANAGEMENT_LOGIN
  • OTP_PROGRAM_MANAGEMENT_PASSWORD_RESET
  • SSO_USER_INTIVATION_PROGRAM_MANAGEMENT

Each template must be initialized with a title and description before use.

UserNotification

Overview

The UserNotification class manages in-app notifications for individual users. It stores and tracks notifications delivered to users through the platform's notification system, providing read/unread tracking, status management, and pagination support.

General Purpose:

  • Store and manage in-app notifications for individual users
  • Track notification read/unread status and timestamps
  • Support notification archival and deletion
  • Provide paginated notification lists with filtering
  • Serve both program management users and end users (members)

Architecture Pattern:

  • Instance-based class where each instance represents a user's notification inbox
  • instanceId format: uses prefixed user ID (M{userId} for members, PM{userId} for program management users)
  • Notifications are added automatically by the NotificationManager when in-app channel is enabled

Data Structure

State Schema

interface UserNotificationState {
    private: {
        userId: string
        notifications: UserNotificationItem[]
    }
    public: {}
}

interface UserNotificationItem {
    id: string
    userId: string
    templateId: string
    subject?: string
    content: string
    metadata?: Record<string, any>
    status: UserNotificationStatus
    createdAt: Date
    readAt?: Date
}

Enums and Types

enum UserNotificationStatus {
    UNREAD = 'unread',
    READ = 'read',
    ARCHIVED = 'archived'
}

Core Functionality

Notification Management

  • Add Notification: Internal method called by NotificationManager to add new notifications
  • Mark as Read: Update notification status to read and set readAt timestamp
  • Update Status: Change notification status (unread, read, archived)
  • Delete Notification: Permanently remove a notification from user's inbox
  • List Notifications: Retrieve paginated list with optional status filtering
  • Unread Count: Get quick count of unread notifications

User Identity Resolution

The class supports two user types with prefixed instance IDs:

  • Members (End Users): instanceId = M{userId}
  • Program Management Users: instanceId = PM{userId}

The authorizer ensures users can only access their own notifications:

  • enduser identity can only access member notifications (M prefix) matching their userId
  • program_management_user identity can only access PM notifications (PM prefix) matching their userId

API Methods

Notification Operations

  • addNotification (WRITE) - Add a notification for the user (internal)

    • Permission: All ClassIdentities (internal service method)
    • Input: { templateId: string, subject?: string, content: string, metadata?: Record<string, any> }
    • Returns: Created notification object
  • markNotificationAsRead (WRITE) - Mark a notification as read

    • Permission: program_management_user, enduser
    • Input: { notificationId: string }
    • Returns: 204 No Content
  • updateNotificationStatus (WRITE) - Update notification status

    • Permission: program_management_user, enduser
    • Input: { notificationId: string, status: UserNotificationStatus }
    • Returns: 204 No Content
  • deleteNotification (WRITE) - Delete a notification

    • Permission: program_management_user, enduser
    • Input: { notificationId: string }
    • Returns: 204 No Content

Notification Queries

  • listUserNotifications (READ) - List user notifications

    • Permission: program_management_user, enduser
    • Input: { status?: UserNotificationStatus, page?: number, limit?: number }
    • Returns: { notifications: UserNotificationItem[], totalCount: number, page: number, limit: number, totalPages: number }
  • getUnreadCount (READ) - Get count of unread notifications

    • Permission: program_management_user, enduser
    • Returns: { unreadCount: number }

Key Features

  1. User-Specific Notifications

    • Each user has their own notification instance
    • Isolated notification storage per user
    • Automatic instance creation on first notification
  2. Multi-User Type Support

    • Supports both member (enduser) and program management user notifications
    • Prefixed instance IDs for user type identification
    • Authorizer enforces user-specific access control
  3. Status Tracking

    • Three status levels: unread, read, archived
    • Automatic readAt timestamp on mark as read
    • Status filtering in list queries
  4. Pagination Support

    • Standard pagination structure (page, limit, totalCount, totalPages)
    • Configurable page size (1-100 items per page)
    • Default 10 items per page
  5. Integration with NotificationManager

    • Automatically receives notifications from NotificationManager
    • Notifications added via tasks when in-app channel is enabled
    • Template ID reference for notification source tracking
  6. Metadata Support

    • Optional metadata field for custom data
    • Flexible structure for additional notification context
    • Preserved through notification lifecycle

Program Management User

Overview

The ProgramManagementUser class manages administrative users who operate the loyalty program system. These users have role-based access to manage members, companies, tiers, and other system entities. The class handles user lifecycle, authentication, and permission management.

General Purpose:

  • Administrative user management for program operators
  • Role-based access control integration
  • Multi-method authentication (email/password, OTP)
  • User invitation and approval workflows
  • Scoped access control (company-specific users)

Data Structure

State Schema

The ProgramManagementUser class maintains a singleton state with all users:

interface ProgramManagementUserState {
  private: {
    users: ProgramManagementUser[]
  }
}

User Types and Status

enum ProgramManagementUserType {
  INTERNAL = 'internal',    // Internal system administrators
  COMPANY = 'company'       // Company-scoped users
}

enum ProgramManagementUserStatus {
  PENDING = 'pending',      // Pending invitation acceptance
  ACTIVE = 'active',        // Active user
  INACTIVE = 'inactive'     // Deactivated user
}

Authentication Methods

enum ProgramManagementLoginMethod {
  SSO = 'sso',                    // Single Sign-On
  EMAIL_PASSWORD = 'email_password' // Email and password
}

Core Functionality

User Management

  • User Creation: Create new administrative users with role assignment
  • User Updates: Modify user profiles, roles, and company associations
  • Status Management: Activate, deactivate, and manage user lifecycle
  • Listing & Filtering: User search and filtering capabilities

Authentication & Login

  • Multi-Method Auth: Support for SSO (SAML 2.0) and email/password authentication
  • SSO Integration: Azure Active Directory and SAML-compliant identity providers
  • Domain-based Discovery: Automatic authentication method detection based on email domain
  • OTP Integration: Two-factor authentication via email OTP for email/password method
  • Session Management: Login tracking and audit trails
  • Token Generation: JWT token creation with user claims and permissions

Password Management

  • Password Reset: Secure password reset via email tokens
  • Invitation Flow: New user invitation with secure password setup
  • Password Security: Hashed password storage and validation

Approval Workflows

  • User Creation Approval: Optional approval workflow for new users
  • General Approval: Integration with ApprovalManager for user operations
  • Invitation Acceptance: Secure invitation token validation

API Methods

User Management Methods

  • createUser (WRITE) - Create new administrative user

    • Triggers invitation email for password setup
  • updateUser (WRITE) - Update existing user

  • getUser (READ) - Retrieve specific user by ID

  • listUsers (READ) - List and filter users

  • updateUserStatus (WRITE) - Update user status

    • Change user status between PENDING, ACTIVE, and INACTIVE
    • Validates email uniqueness when activating users
    • Triggers workflow for status change approval
  • getPermissions (READ) - Get permissions for logged-in user

    • Returns permissions grouped by class key based on user's roles

Authentication Methods

  • discoverAuthMethod (STATIC) - Determine user's authentication method by email domain

    • Returns SSO login URL for configured domains
    • Supports email/password fallback for non-SSO domains
  • singleSignOn (WRITE) - Process SAML authentication response

    • Validates SAML response from identity provider
    • Generates JWT token and redirects to web application
    • Supports Azure AD and other SAML 2.0 providers
  • login (WRITE) - Email/password authentication

    • Traditional username/password authentication
    • Triggers OTP for additional security
  • checkOtp (WRITE) - Validate OTP during login

  • resendOtp (WRITE) - Resend OTP for authentication

Password Management Methods

Status Management

Key Features

  1. Singleton Architecture: Single instance (default) manages all program management users
  2. Role Integration: Deep integration with RoleManager for permission-based access
  3. Company Scoping: Company-type users restricted to their assigned company operations
  4. SSO Authentication: Full SAML 2.0 support with Azure AD integration and domain-based discovery
  5. Multi-Auth Support: Flexible authentication methods including SSO and email/password with OTP
  6. Workflow Compatible: Extends WorkflowCompatibleStateManager for approval processes
  7. Audit Trail: Login attempt tracking and comprehensive user activity logging
  8. Security Features: Secure password handling, SAML validation, token-based operations, and OTP validation

Class Relations

The following diagram illustrates how ProgramManagementUser integrates with other system components:

Program Management User Relations

Member

Overview

The Member class manages individual loyalty program member profiles and their complete lifecycle. Each member is represented as a separate instance. The class handles member registration, profile updates, family management, photo verification, eligibility processing, and company member type validation.

General Purpose:

  • Individual member profile and lifecycle management
  • Tab-based profile organization (Personal, Membership, Employment, Contact, Dependants) (Program Management)
  • Multi-tier membership support with payment integration
  • Family member and dependant management
  • Photo verification and approval workflows
  • Authentication method determination based on email domain
  • Eligibility rule processing for tier qualification
  • Workflow integration for status transitions and approvals

Data Structure

State Schema

Each Member instance maintains a singleton state with the member's complete profile:

interface MemberState {
  private: {
    profile: MemberProfile
  }
  public: {}
}

interface MemberProfile {
  id: string
  status: MemberStatus
  name: string
  middleName?: string
  surname: string
  staffId: string
  email: string
  phone: string
  company: { id: string }
  grade: string
  idPhoto?: string
  loginMethod: MemberLoginMethod
  address: { country: string; address: string }
  memberType: string
  memberSubType?: string
  memberships: Membership[]
  primaryMemberId?: string
  relation?: string
  family?: FamilyMember[]
  createdBy: Actor
  note?: string
  permissions?: MemberPermissions
  createdAt: Date
  updatedAt: Date
}

Member Status Lifecycle

enum MemberStatus {
  PENDING_INVITE = 'pending_invite',                  // Awaiting invitation email to be sent
  PENDING_INVITATION_ACCEPTANCE = 'pending_invitation_acceptance', // Invitation email sent, awaiting acceptance
  PENDING_APPROVAL = 'pending_approval',              // Awaiting approval after creation
  PENDING_ID_PHOTO = 'pending_id_photo',              // Awaiting photo upload
  PENDING_TIER = 'pending_tier',                      // Awaiting tier assignment
  ACTIVE = 'active',                                  // Fully activated member
  INACTIVE = 'inactive',                              // Deactivated member
  SUSPENDED = 'suspended',                            // Temporarily suspended member
  REJECTED = 'rejected'                               // Member creation/update rejected
}

Authentication Methods

enum MemberLoginMethod {
  SSO = 'sso',                    // Single Sign-On (domain-based)
  EMAIL_PASSWORD = 'email_password' // Email and password authentication
}

Payment Types

enum PaymentType {
  DDS = 'dds',    // Direct Debit System
  CPG = 'cpg'     // Corporate Payment Gateway
}

Core Functionality

Tab-Based Profile Management

  • Personal Tab: Name, staff ID, member type/subtype (with company eligibility validation)
  • Membership Tab: Tier assignments, payment configurations, membership periods
  • Employment Tab: Company association, grade/position information
  • Contact Tab: Phone, address, communication permissions
  • Dependants Tab: Family member management and relationships

Family Member Management

  • Family Addition: Add dependants with relationship tracking
  • Family Updates: Modify family member information and status
  • Family Removal: Remove dependants from member profile
  • Membership Status: Independent membership status for each family member

Photo Management

  • ID Photo Upload: Secure photo upload for verification with previous photo tracking
  • Photo Approval: Workflow-driven photo approval process with photo comparison support
  • Status Transitions: Automatic status updates based on photo lifecycle
  • Secure Access: File access tokens with expiration for photo URLs
  • Approval Context: Previous and new photo tracking for approval workflows

Document Management

  • Document Upload: Secure upload of images and documents with file type validation
  • Document Storage: Metadata stored in Member state, files managed by FileManager
  • Document Listing: Paginated list of documents with status enrichment
  • Status Tracking: Active and archived status for document lifecycle management
  • Secure Download: Temporary access URLs with expiration for both active and archived documents
  • Archival System: Archive/unarchive functionality with separate download permissions

Eligibility Rules

  • Rule Processing: Complex eligibility evaluation for tier qualification
  • Cross-Entity Lookups: Support for member, company, and external data sources
  • Field Definitions: Available through Tier class getEligibilityRuleDefinitions method

Status Management & Workflows

  • Lifecycle Management: Automated status transitions through workflow rules
  • Approval Integration: ApprovalManager integration for member operations
  • Event Tracking: Comprehensive event logging for all member activities
  • Business Rules: Configurable workflow rules for status changes
  • Validation Rules: Company member type eligibility validation during member creation and updates

API Methods

Personal Tab Methods

  • updateMemberPersonal (WRITE) - Update member personal information

    • Updates name, staff ID, member type/subtype (validates eligibility against company)
  • getMemberPersonal (READ) - Get member personal information

    • Returns personal data with secure file access tokens for photos
    • Includes pending approval information with old/new photo comparison data

Membership Tab Methods

  • addMembership (WRITE) - Add new membership to member

    • Adds tier membership with payment configuration
    • Validates tier status and company-paid payment type
    • Automatically sets membership periods and payment schedules
  • listMemberships (READ) - List member memberships with pagination and filtering

    • Returns paginated list of memberships with tier details enrichment
    • Supports filtering by tier ID, tier group (base/upgrade/add-on), and membership status (active/expired/inactive/suspended)
    • Status is stored in the membership record
    • Enriches each membership with tier name, tier type (group, label), and fee information
    • Response includes: { memberships: EnrichedMembership[], totalCount, page, limit, totalPages }

Employment Tab Methods

  • updateMemberEmployment (WRITE) - Update member employment information

    • Updates grade/position information (company association cannot be changed after member creation)
  • getMemberEmployment (READ) - Get member employment information

Contact Tab Methods

Dependants Tab Methods

Photo Management Methods

  • uploadMemberIdPhoto (WRITE) - Upload member's ID photo (program_management_user)

    • Secure photo upload with validation
    • Tracks previous photo path for approval workflow context
    • Status transition: PENDING_ID_PHOTO → ACTIVE (with active membership) or PENDING_TIER (no active membership)
  • uploadMyIdPhoto (WRITE) - Upload member's own ID photo (enduser)

    • Allows logged-in members to upload their own ID photo
    • Status validation: Only ACTIVE or PENDING_ID_PHOTO members can upload
    • Same workflow and approval process as uploadMemberIdPhoto
    • Status transition: PENDING_ID_PHOTO → ACTIVE (with active membership) or PENDING_TIER (no active membership)
    • Returns secure access URLs with expiration times
  • approveMemberIdPhoto (QUEUED_WRITE) - Approve or reject member's ID photo

    • Workflow-driven approval process

Status and Approval Methods

  • updateMemberStatus (WRITE) - Update member status

    • Direct status updates with workflow integration
    • System-only statuses (pending_invite, pending_invitation_acceptance, pending_id_photo, pending_tier) cannot be set manually
  • sendInviteEmail (WRITE) - Send invitation email to member

    • Only applicable for EMAIL_PASSWORD login method users
    • SSO users receive welcome email automatically upon member creation approval (via approveMemberCreate)
    • Member must have at least one active membership to receive invitation
    • Sends invitation email and updates status from pending_invite to pending_invitation_acceptance
    • Can re-send invitations to members already in pending_invitation_acceptance status (creates new OTP token)
    • Only callable by program_management_user
  • approveMember (QUEUED_WRITE) - Approve member operations (create/update)

    • General approval workflow for member operations
    • After member creation approval:
      • For SSO users: Welcome email is sent automatically upon approval
      • For EMAIL_PASSWORD users: Status changes to pending_invite (invitation sent separately via sendInviteEmail)

Listing Methods

  • listMembers (READ) - List members with filtering and pagination
    • Filtering, search, and pagination capabilities

Data Streaming Methods

  • streamMember (WRITE) - Manually stream member data to MongoDB
    • Manual data synchronization to MongoDB collections

Integration Service Methods

  • updateEmployeePhoto (WRITE) - Update employee photo via integration service
    • Allows external HR systems to update employee photos using base64-encoded photo data
    • Uses integration_user authentication for secure API key-based access
    • Automatically manages FileManager operations for photo storage
    • Implements robust error handling with specific error wrapping:
      • Catches FileManager upload errors and wraps them in EMPLOYEE_PHOTO_UPLOAD_FAILED (code: 10018)
      • Preserves original error details (message and code) for debugging
      • Ensures clear error messages for integration consumers
    • Triggers MEMBER_ID_PHOTO_UPLOAD workflow event for approval processing

Document Management Methods

  • uploadDocument (WRITE) - Upload a document or image for the member

    • Supports images (max 5MB: jpeg, jpg, png, gif, webp) and documents (max 10MB: pdf, doc, docx, xls, xlsx, txt, csv)
    • Document metadata is stored in Member state for efficient tracking
    • Uses FileManager for secure file storage
    • Returns temporary download URL (expires in 5 minutes) along with document ID
  • listDocuments (READ) - List member documents with pagination

    • Returns paginated list of documents with metadata
    • Supports filtering by status (active/archived) through status field
    • Sorted by upload date (newest first)
    • Includes enriched status information with labels and isArchived flag
    • Response includes: { documents, totalCount, page, limit, totalPages }
  • downloadDocument (READ) - Download an active member document

    • Returns temporary access URL for active documents (expires in 5 minutes)
    • Prevents download of archived documents (use downloadArchivedDocument instead)
    • Returns error if document not found or archived
  • archiveDocument (WRITE) - Archive a member document

    • Changes document status to archived
    • Archived documents cannot be downloaded via regular downloadDocument endpoint
    • Returns document ID on successful archival
  • unarchiveDocument (WRITE) - Unarchive a member document

    • Changes document status back to active
    • Makes document accessible through regular downloadDocument endpoint
    • Returns document ID on successful unarchival
  • downloadArchivedDocument (READ) - Download an archived member document

    • Specifically for accessing archived documents with separate permissions
    • Returns temporary access URL (expires in 5 minutes)
    • Can also download active documents (separate permission control)

Member Authentication Methods

  • discoverAuthMethod (STATIC) - Discover authentication method for member email

    • Determines SSO or EMAIL_PASSWORD based on email domain
    • For SSO domains, returns SSO login URL for identity provider
    • For EMAIL_PASSWORD, checks if member exists and initiates OTP registration flow if not
    • Public endpoint (no authentication required)
  • singleSignOn (STATIC) - Process SSO SAML response and authenticate member

    • Handles SSO callback from identity provider (Azure AD, etc.)
    • Validates SAML response and extracts user email
    • Verifies member exists and is authorized for SSO login
    • Activates pending members (pending_invitation_acceptance) automatically
    • Generates JWT token and redirects to member web application
    • Public endpoint (no authentication required)
  • acceptInvitation (WRITE) - Accept member invitation and set password

    • Validates invitation token and sets member password
    • Transitions member to active status
    • Public endpoint (no authentication required)
  • inviteRedirect (STATIC) - HTML redirect endpoint for member invitations

    • Redirect handler for email invitation links
    • Public endpoint (no authentication required)
  • login (STATIC) - Authenticate member with email and password

    • Verifies credentials and sends OTP to email
    • Public endpoint (no authentication required)
  • checkOtp (WRITE) - Verify login OTP and issue access token

    • Validates OTP and generates authentication token
    • Requires member_otp identity
  • resendOtp (WRITE) - Resend login OTP to member email

    • Re-sends OTP for failed delivery or expiration
    • Requires member_otp identity
  • getMemberProfile (READ) - Get basic member profile information

    • Returns member's core profile data (name, email, phone, company, status)
    • Includes hasWaitingApproval boolean flag indicating pending ID photo approval
    • Includes approval object with photo URLs when approval is pending
    • Only accessible by the member themselves (enduser identity)

Password Management Methods

  • sendPasswordResetEmail (STATIC) - Send password reset email with token

    • Sends password reset link to member email
    • Public endpoint (no authentication required)
  • resetPassword (WRITE) - Reset password using token from email

    • Validates reset token and updates password
    • Public endpoint (no authentication required)
  • changePassword (WRITE) - Change password for logged-in member

    • Requires current password verification
    • Requires enduser identity (logged-in member)

Key Features

  1. Instance-Based Architecture: Each member is a separate Rio instance with unique state
  2. Tab-Based Organization: Profile organized into logical tabs for better management
  3. Family Support: Comprehensive family member and dependant management
  4. Authentication Integration: Automatic login method determination based on email domain
  5. Photo Verification: Complete photo upload and approval workflow
  6. Document Management: Secure document upload, listing, download, and archival with status tracking
  7. Eligibility Processing: Rule processing for tier qualification and membership eligibility
  8. Workflow Compatible: Extends WorkflowCompatibleStateManager for business process automation
  9. MongoDB Integration: Automatic data streaming to MongoDB for analytics and reporting
  10. Permission Management: Granular communication permissions (SMS, email)
  11. Audit Trail: Complete audit logging through LogManager integration

Class Relations

The following diagram illustrates how Member integrates with other system components:

Member Class Relations

Company

Overview

The Company class manages company entities and their relationships within the system, serving as a central registry for organizations and their configurations.

General Purpose:

  • Manages company creation, updates, and status changes with workflow approval integration
  • Maintains company group relationships and HR contact information
  • Defines member type eligibility and dependant management policies with runtime validation
  • Provides data streaming capabilities to MongoDB for external synchronization
  • Singleton instance with 'default' ID managing all company records

Data Structure

State Schema

interface CompanyState {
  private: {
    companies: Company[]
  }
  public: object
}

interface Company {
  id: string
  name: string
  description?: string
  companyGroupId: string
  hrContact: HRContact
  status: CompanyStatus
  createdBy: Actor
  createdAt: Date
  updatedAt: Date
  eligibleMemberTypes: string[]
  memberSubTypes: CompanyMemberSubTypes[]
  maxFreeDependants: number
}

Enums and Types

enum CompanyStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  PENDING = 'pending'
}

enum CompanyEvents {
  COMPANY_CREATE = 'company_create',
  UPDATE_COMPANY = 'update_company',
  UPDATE_COMPANY_STATUS = 'update_company_status'
}

Additional Structures

interface HRContact {
  name: string
  email: string
}

interface CompanyMemberSubTypes {
  memberSubTypeId: string
  maxDependants: number
}

interface Actor {
  id: string
}

Core Functionality

Main Feature Groups

  • Company Lifecycle Management: Create, update, and manage company information with workflow integration
  • Status Management: Control company status transitions (waiting → active/inactive) through approval workflows
  • Search and Filtering: Search capabilities by name, description, status, and company group
  • Member Type Configuration: Define eligible member types and dependant policies for each company
  • Member Type Validation: Validate member type eligibility during member creation and updates
  • Data Synchronization: Stream company data to MongoDB for external system integration

Workflow Integration

The Company class extends WorkflowCompatibleStateManager and integrates with the workflow system:

  • Status Transitions: Workflow rules manage company status changes from pending to active/inactive
  • Events: Company creation, updates, and status changes trigger workflow processing
  • Approval Integration: All significant operations go through approval workflows before final completion
  • Business Rules: Workflow configuration defines approval requirements and status transition logic

API Methods

Company Management

  • createCompany (WRITE) - Create a new company with workflow approval
    • Sets initial status to waiting and triggers company creation workflow
  • updateCompany (WRITE) - Update existing company information
    • Requires company existence validation and triggers update workflow
  • updateCompanyStatus (WRITE) - Update company status
    • Manages status transitions through workflow rules

Company Information

  • getCompany (READ) - Retrieve company details by ID
    • Accessible by program management users and Member class for member type validation
  • listCompanies (READ) - List companies with filtering and pagination
    • Supports filtering by status, company group, and search terms
    • Includes pagination with configurable page size and limits

Approval Operations

  • approveCompany (QUEUED_WRITE) - Process approval workflows
    • Applies JSON patches from approval records and triggers MongoDB streaming
  • streamCompany (READ) - Manual data streaming to MongoDB
    • Synchronizes specific company data with external MongoDB collections by company ID

Method Types:

  • WRITE - Sync state mutation (1-30s)
  • READ - Sync state access (1-30s)
  • QUEUED_WRITE - Async state mutation (1-890s)
  • STATIC - Stateless utility

Key Features

  1. Architecture Pattern: Singleton instance with 'default' ID managing all company records
  2. Integration Points: Integrates with ApprovalManager, Workflow system, and MongoDB streaming
  3. Workflow Support: Full workflow integration with approval processes for all major operations
  4. Security Features: Program management user authentication with comprehensive permission system
  5. Data Management: Extends WorkflowCompatibleStateManager for advanced state management
  6. External Integrations: MongoDB streaming capabilities for data synchronization
  7. Performance Features: Efficient search, filtering, and pagination support
  8. Audit/Logging: Complete activity tracking through workflow system and actor-based operations

Class Relations

The following diagram illustrates how Company integrates with other system components:

Company Relations

Tier

Overview

The Tier class manages individual membership tier instances with comprehensive eligibility rules, payment configurations, and approval workflows. It serves as the core tier management system with complex business logic for member eligibility validation and lifecycle management.

General Purpose:

  • Individual membership tier instance management with unique tier IDs
  • Complex eligibility rule system with conditional logic and quota management
  • Approval workflows for tier creation, updates, and status changes
  • Instance-based architecture with unique IDs for each tier entity
  • Integration with Setting class for tier type definitions and Member class for tier assignments
  • MongoDB streaming for real-time tier data persistence
  • Tier cloning capability through sourceTierId parameter to copy eligibility rules from existing tiers

Data Structure

State Schema

interface TierState {
  private: {
    tier: Tier
  }
  public: object
}

Enums and Types

enum TierStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  PENDING = 'pending',
  EXPIRED = 'expired'
}

enum UpdatableTierStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  PENDING = 'pending'
}

enum TierEvents {
  TIER_CREATE = 'tier_create',
  TIER_UPDATE = 'tier_update',
  TIER_STATUS_UPDATE = 'tier_status_update',
  ELIGIBILITY_RULE_ADD = 'eligibility_rule_add',
  ELIGIBILITY_RULE_UPDATE = 'eligibility_rule_update',
  ELIGIBILITY_RULE_DEACTIVATE = 'eligibility_rule_deactivate'
}

enum EligibilityRuleStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

Additional Structures

interface Tier {
  id: string
  name: string
  description?: string
  tierType: {
    id: string
    group: TierGroup
  }
  fee: number
  startDate: Date
  endDate: Date
  status: TierStatus
  eligibilityRules: EligibilityRule[]
  createdBy: StateManagerActor
  createdAt: Date
  updatedAt: Date
}

interface EligibilityRule {
  id: string
  name: string
  paymentTypes: TierPaymentType[]
  paymentPeriod: string
  quota?: number
  conditions: EligibilityRuleCondition[]
  status: EligibilityRuleStatus
}

interface EligibilityRuleCondition {
  key: string
  logicalOperator: EligibilityOperator
  value: string | number | boolean | unknown[]
}

Core Functionality

Main Feature Groups

  • Tier Lifecycle Management: Complete tier creation, modification, and status management with workflow integration
  • Eligibility Rule System: Complex conditional logic system for member eligibility with quota management and payment configurations
  • Tier Cloning: Ability to create new tiers based on existing ones by copying active eligibility rules using the sourceTierId parameter
  • Payment Configuration: Integration with Setting class for tier type definitions and payment method configurations
  • Approval Workflows: Comprehensive approval system for tier operations with automated status transitions
  • MongoDB Streaming: Real-time data streaming to MongoDB for external system integration and tier data querying
  • Static Utility Services: Tier group and payment type enumeration services for system configuration

Workflow Integration

The Tier class extends WorkflowCompatibleStateManager and integrates with the workflow system:

  • Status Transitions: Workflow rules manage tier status changes through active, inactive, waiting, and expired states
  • Events: Tier operations and eligibility rule changes trigger workflow processing for automated approvals
  • Approval Integration: Tier creation, updates, and rule modifications require approval through ApprovalManager
  • Business Rules: Configurable workflow rules control tier lifecycle, eligibility validation, and operational constraints

API Methods

Tier Management

  • updateTier (WRITE) - Update an existing tier

    • Modify tier details including name, description, fee, dates, and eligibility rules
    • Validates business rules and date constraints for tier updates
  • getTier (READ) - Get tier details

    • Retrieve complete tier information including eligibility rules and payment configurations
  • updateStatus (WRITE) - Update tier status

    • Change tier status between ACTIVE, INACTIVE, and PENDING states
    • Includes workflow validation and business rule enforcement
  • streamTier (WRITE) - Manually stream tier data to MongoDB

    • Force synchronization of tier data to MongoDB for external system access

Eligibility Rule Management

  • addEligibilityRule (WRITE) - Add new eligibility rule

    • Create complex eligibility rules with conditional logic and payment configurations
    • Supports quota management and multi-condition validation
  • updateEligibilityRule (WRITE) - Update existing eligibility rule

    • Modify eligibility rule parameters with validation and approval workflows
  • deactivateEligibilityRule (WRITE) - Deactivate eligibility rule

    • Set eligibility rule status to INACTIVE while maintaining audit trail

Static Utility Methods

  • listTiers (STATIC) - List tiers with filtering and pagination

    • Query tiers from MongoDB with filtering by status, tier type, and search criteria
    • Supports pagination and full-text search across tier names and descriptions
  • getTierGroups (STATIC) - Get available tier groups

    • Retrieve list of tier group types from Setting class configuration
  • getPaymentTypes (STATIC) - Get available payment types

    • Retrieve list of supported payment types from Setting class configuration
  • getEligibilityRuleDefinitions (STATIC) - Get eligibility rule field definitions

    • Returns available field groups and field definitions for building eligibility rules dynamically
    • Includes field types, operators, and resolved values for Member and Company entities
    • Used for building dynamic eligibility rule forms in UI applications

Approval Operations

  • approve (QUEUED_WRITE) - Approve tier creation or update
    • Process approval workflows for tier operations and eligibility rule changes

Initialization

  • INIT (WRITE) - Create a new tier instance
    • Creates a new tier with specified configuration and eligibility rules
    • Supports tier cloning via sourceTierId parameter to copy active eligibility rules
    • Validates tier type from Setting class and checks for date range overlaps

Utilities

The Tier class provides utility functions for internal class-to-class communication:

  • getTierDetails(tierId: string) - Fetch complete tier information via RDK method call
    • Used by other classes to retrieve tier data without direct state access
    • Used internally during tier creation when sourceTierId is provided to copy eligibility rules
    • Performs RDK methodCall to Tier.getTier with proper error handling
    • Returns enriched Tier object with eligibility rule conditions
    • Authorization: Tier class identity is allowed for internal communication

Tier Cloning Process

When creating a new tier with the sourceTierId parameter:

  1. The source tier is fetched using getTierDetails(sourceTierId)
  2. All active eligibility rules from the source tier are extracted
  3. New IDs are generated for each copied eligibility rule
  4. The eligibility rules are assigned to the new tier instance
  5. Inactive rules from the source tier are excluded from the copy

This feature enables rapid tier creation by reusing existing eligibility rule configurations, ensuring consistency across similar tier types while allowing customization of tier-specific properties (name, description, fee, dates, etc.).

Key Features

  1. Architecture Pattern: Instance-based class using unique tier IDs; extends WorkflowCompatibleStateManager
  2. Integration Points: Calls Setting.getTierType() for tier type validation; used by Member class for tier assignment logic
  3. Workflow Support: Implements workflow rules for tier status transitions (PENDING → ACTIVE → INACTIVE → EXPIRED)
  4. Authorization: Program management users only; all operations require specific permissions via RoleManager
  5. Data Management: Single Tier object in private state; automatic MongoDB streaming via tier.streaming utility
  6. External Integrations: MongoDB collection for external queries; no direct third-party API integrations
  7. State Tracking: createdBy/createdAt/updatedAt fields; eligibility rule modification history
  8. Tier Cloning: Supports tier creation from existing tiers via sourceTierId, copying only active eligibility rules with new IDs

Class Relations

The following diagram illustrates how Tier integrates with other system components:

Tier Relations

Partner

Overview

The Partner class manages partner entities and their associated venues, documents, and contract information within the system, serving as a central registry for partner organizations and their relationships.

General Purpose:

  • Manages partner creation, updates, and status changes with workflow approval integration
  • Maintains partner types, multiple subtypes per partner, tier assignments, and social media presence
  • Handles venue/location management with geographic coordinates and contact information
  • Provides document upload, storage, and retrieval capabilities through FileManager integration
  • Supports activity tracking and audit logging for all partner operations
  • Instance-based architecture where each partner has a unique instance ID
  • Streams partner and venue data to MongoDB for external synchronization

Terminology Note:

  • Internally, partner venues are referred to as "locations" with a type field to support different location types (e.g., venue, office, warehouse)
  • For backward compatibility, the client-facing API endpoints continue to use "venue" terminology
  • The type field is system-managed and defaults to venue - it is not settable by clients
  • All venues/locations include geographic coordinates for location-based features

Data Structure

State Schema

interface PartnerState {
  private: {
    partner: Partner
    locations: PartnerLocation[]      // Internally called 'locations', exposed as 'venues' in API
  }
  public: object
}

interface Partner {
  id: string

  // Details Tab
  legalName: string
  brandName: string
  brandLogoPath?: string
  partnerTier?: string
  socialMediaAccounts?: SocialMediaAccount[]

  // Contact Tab
  businessAddress: string
  city: string
  country: string
  website?: string
  primaryContact: PrimaryContact

  // Contract Tab
  partnerTypeId?: string
  partnerSubtypeIds?: string[]          // Multiple subtypes supported
  tradeLicenseNumber?: string
  contractId: string
  contractStartDate: Date
  contractEndDate: Date
  accountAgent?: string

  // System Fields
  status: PartnerStatus
  statusReason?: string
  createdBy: Actor
  createdAt: Date
  updatedAt: Date
}

Enums and Types

enum PartnerStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum DocumentStatus {
  ACTIVE = 'active',
  ARCHIVED = 'archived'
}

enum SocialMediaPlatform {
  FACEBOOK = 'facebook',
  INSTAGRAM = 'instagram',
  LINKEDIN = 'linkedin',
  TWITTER = 'x',
  YOUTUBE = 'youtube',
  TIKTOK = 'tiktok'
}

enum PartnerEvents {
  PARTNER_CREATE = 'partner_create',
  UPDATE_PARTNER_DETAILS = 'update_partner_details',
  UPDATE_PARTNER_BRAND_LOGO = 'update_partner_brand_logo',
  UPDATE_PARTNER_CONTACT = 'update_partner_contact',
  UPDATE_PARTNER_CONTRACT = 'update_partner_contract',
  UPDATE_PARTNER_STATUS = 'update_partner_status'
}

enum VenueStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive'
}

enum LocationType {
  VENUE = 'venue'
}

enum VenueEvents {
  VENUE_CREATE = 'venue_create',
  VENUE_UPDATE = 'venue_update',
  VENUE_STATUS_UPDATE = 'venue_status_update'
}

Additional Structures

interface PrimaryContact {
  name: string
  email: string
  phone: string
}

interface SocialMediaAccount {
  platform: SocialMediaPlatform
  url: string
}

interface PartnerLocation {
  id: string
  partnerId: string
  venueName: string                  // Note: field name kept as 'venueName' for API compatibility
  address: string
  contactName: string
  contactEmail: string
  contactPhone: string
  mapCoordinates: MapCoordinates
  type: LocationType                // Location type (system-managed, not client-settable)
  status: VenueStatus
  createdBy: Actor
  createdAt: Date
  updatedAt: Date
}

interface MapCoordinates {
  latitude: number
  longitude: number
}

interface Actor {
  id: string
}

interface PartnerDocument {
  id: string
  filename: string
  originalFilename: string
  uploadedBy: Actor
  uploadedAt: Date
  status: DocumentStatus           // Document status (active/archived)
}

Core Functionality

Main Feature Groups

  • Partner Lifecycle Management: Create, update, and manage partner information with workflow integration across three tabs (Details, Contact, Contract)
  • Status Management: Control partner status transitions through approval workflows with optional status reasons
  • Venue Management: Create, update, and list venues associated with partners, including geographic coordinates
  • Document Management: Upload, list, download, archive, and unarchive documents through FileManager integration with status-based access control
  • Search and Filtering: List partners with filtering by status, partner type, multiple subtypes, and search query with pagination
  • Brand Management: Handle brand logos and social media account links for marketing purposes
  • Contract Tracking: Manage partner contracts with expiry dates and trade license numbers
  • Data Streaming: Synchronize partner and venue data to MongoDB for external system integration
  • Activity Logging: Track all partner-related operations through LogManager integration

Workflow Integration

The Partner class extends WorkflowCompatibleStateManager to integrate with the workflow system:

  • Status Transitions: Workflow rules manage partner status changes from creation to active/inactive states
  • Events: Partner lifecycle events trigger workflow processing (create, update details/contact/contract, status update)
  • Approval Integration: Uses PartnerApprovalManager for handling approval workflows
  • Business Rules: Workflow configuration defines approval requirements for partner operations
  • Venue Workflows: Separate workflow rules for venue creation, updates, and status changes

API Methods

Partner Management

  • init (WRITE) - Initialize a new partner with details, contact, and contract information

    • Uploads brand logo to FileManager if provided
    • Triggers workflow approval process
    • Streams partner data to MongoDB
  • listPartners (STATIC) - List partners with filtering and pagination

    • Filter by status, partner type, multiple subtypes, and search query
    • Subtype filtering returns partners that have any of the specified subtypes
    • Returns paginated results with total count

Partner Information

  • getPartnerDetails (READ) - Get partner details tab information

    • Returns legal name, brand name, logo path, tier, and social media accounts
  • getPartnerContact (READ) - Get partner contact tab information

    • Returns business address, city, country, website, and primary contact
  • getPartnerContract (READ) - Get partner contract tab information

    • Returns partner type, subtypes (array), trade license, contract ID, and expiry date
  • updatePartnerDetails (WRITE) - Update partner details tab

    • Updates legal name, brand information, tier, and social media
    • Triggers workflow event for approval
  • updatePartnerBrandLogo (WRITE) - Update partner brand logo

    • Uploads new brand logo to FileManager
    • Updates brandLogoPath in partner state
    • Triggers workflow event for approval
  • updatePartnerContact (WRITE) - Update partner contact tab

    • Updates address, city, country, website, and primary contact
    • Triggers workflow event for approval
  • updatePartnerContract (WRITE) - Update partner contract tab

    • Updates partner type, subtypes (array), trade license, contract ID, and expiry date
    • Supports multiple subtypes per partner for flexible categorization
    • Triggers workflow event for approval
  • updatePartnerStatus (WRITE) - Update partner status

    • Changes partner status (active/inactive) with optional reason
    • Triggers workflow event for approval

Venue Management

  • createVenue (WRITE) - Create a new venue for the partner

    • Includes venue name, address, contact info, and map coordinates
    • Streams venue data to MongoDB
  • getVenue (READ) - Get a specific venue by ID

    • Retrieves venue details from MongoDB
  • listVenues (READ) - List venues for the partner

    • Filter by status and search query with pagination
    • Returns venues associated with the partner instance
  • updateVenue (WRITE) - Update an existing venue

    • Updates venue name, address, contact info, and coordinates
    • Streams updated data to MongoDB
  • updateVenueStatus (WRITE) - Update venue status

    • Changes venue status (active/inactive)

Document Management

  • uploadDocument (WRITE) - Upload a document or image

    • Supports IMAGE (max 5MB) and DOCUMENT (max 10MB) file types
    • Accepts images (jpeg, png, gif, webp) and documents (pdf, doc, docx, xls, xlsx, txt, csv)
    • Stores documents through FileManager integration
    • Documents are created with ACTIVE status by default
    • Returns document ID and filename
  • listDocuments (READ) - List documents with pagination

    • Returns all documents (both active and archived) associated with the partner
    • Documents are sorted by uploadedAt in descending order (newest first)
    • Includes document status and status label (Active/Archived) for each document
    • Includes pagination support
  • downloadDocument (READ) - Download an active document

    • Retrieves active documents from FileManager by document ID
    • Prevents access to archived documents (returns error code 14008)
    • Use downloadArchivedDocument endpoint for archived documents
  • archiveDocument (WRITE) - Archive a document

    • Changes document status to ARCHIVED
    • Archived documents cannot be accessed via regular downloadDocument endpoint
    • Document remains in storage but requires special permissions to access
  • unarchiveDocument (WRITE) - Unarchive a document

    • Changes document status back to ACTIVE
    • Makes document accessible through regular downloadDocument endpoint
  • downloadArchivedDocument (READ) - Download an archived document

    • Retrieves archived documents from FileManager by document ID
    • Separate endpoint with dedicated permissions for accessing archived documents
    • Enables permission separation between active and archived document access

Approval Operations

  • approvePartner (QUEUED_WRITE) - Approve partner operations
    • Processes approval/rejection for partner workflows
    • Uses CommonApprovalInput pattern

History Operations

  • getLogEntries (STATIC) - Get log entries for a specific partner

    • Returns paginated log entries with filtering by date range and search
    • Retrieves activity history from LogManager
  • getLog (STATIC) - Get a specific log entry with complete details

    • Returns full details of a single log entry by log ID

Key Features

  1. Architecture Pattern: Instance-based architecture where each partner has a unique instance ID generated via getInstanceId()
  2. Integration Points: Integrates with FileManager for document storage, LogManager for activity tracking, MongoDB for data persistence, and Workflow/ApprovalManager for approval processes
  3. Workflow Support: Extends WorkflowCompatibleStateManager with separate workflow configurations for partner and venue operations
  4. Tabbed Data Model: Organizes partner information into three logical tabs (Details, Contact, Contract) for better UX and granular updates
  5. Venue Management: Supports multiple venues per partner with geographic coordinates for location-based features
  6. Document Storage: Leverages FileManager for secure document upload, storage, and retrieval with status-based archiving (active/archived) for access control and permission separation
  7. Data Streaming: Automatically streams partner and venue data to MongoDB for external system synchronization
  8. Audit Logging: Tracks all operations through LogManager with comprehensive history retrieval
  9. Brand Assets: Handles brand logos via FileManager and manages social media presence
  10. Contract Management: Tracks contract expiry dates and trade licenses for compliance

PartnerUser

Overview

The PartnerUser class manages partner application users who operate within partner organizations, providing user account management with multi-partner and multi-venue support.

General Purpose:

  • Manages partner user creation, updates, and status changes with workflow approval integration
  • Supports per-partner role assignments allowing users to have different roles at different partners
  • Handles multi-partner associations where a single user can work for multiple partner organizations
  • Provides multi-venue access management for location-based permissions
  • Implements simple enum-based role system (ADMIN, MANAGER, STAFF) independent of the complex RoleManager system
  • Instance-based architecture where each partner user has a unique instance ID
  • Streams user data to MongoDB for external synchronization and querying
  • Designed for phase 1 implementation with authentication and authorization planned for future phases

Data Structure

State Schema

interface PartnerUserState {
  private: {
    user: PartnerUser
  }
  public: object
}

interface PartnerUser {
  id: string
  fullName: string
  email: string
  partners: PartnerAssociation[]    // User can belong to multiple partners
  venues: VenueAssociation[]        // User can access multiple venues
  status: PartnerUserStatus
  createdBy: string
  updatedBy: string
  createdAt: number
  updatedAt: number
}

Enums and Types

enum PartnerUserRole {
  ADMIN = 'admin',      // Full administrative access
  MANAGER = 'manager',  // Management-level access
  STAFF = 'staff'       // Standard staff access
}

enum PartnerUserStatus {
  PENDING = 'pending',   // Awaiting approval
  ACTIVE = 'active',     // Active user account
  INACTIVE = 'inactive'  // Deactivated account
}

enum PartnerUserEvents {
  USER_CREATE = 'user_create',
  USER_UPDATE = 'user_update',
  USER_STATUS_UPDATE = 'user_status_update'
}

Additional Structures

interface PartnerAssociation {
  partnerId: string
  role: PartnerUserRole    // Role specific to this partner
}

interface VenueAssociation {
  partnerId: string
  venueId: string
}

Key Design Points:

  • Each partner association includes a role, allowing users to have different roles at different partners (e.g., ADMIN at Partner A, STAFF at Partner B)
  • Venue associations link users to specific locations within partners for location-based access control
  • Simple enum-based roles eliminate dependency on the complex RoleManager system used by ProgramManagementUser

Core Functionality

Main Feature Groups

  • User Account Management: Complete CRUD operations for partner user accounts with approval workflow integration
  • Multi-Partner Support: Users can be associated with multiple partner organizations with per-partner role assignments
  • Venue Access Control: Granular venue-level access management allowing users to be assigned to specific locations
  • Status Management: User status lifecycle management (PENDING → ACTIVE → INACTIVE) with approval requirements
  • Role Information: Client-facing API to retrieve available role options for UI dropdowns and forms
  • User Discovery: Paginated user listing with filtering by status, partner, and search terms

Workflow Integration

The PartnerUser class extends WorkflowCompatibleStateManager and integrates with the approval workflow system:

  • Status Transitions: User creation starts with PENDING status and transitions to ACTIVE upon approval
  • Events: Three main events trigger workflow processing:
    • USER_CREATE: Triggered when a new partner user is created
    • USER_UPDATE: Triggered when user details (name, email, partners, venues) are modified
    • USER_STATUS_UPDATE: Triggered when user status changes
  • Approval Integration: All workflow events can be configured to require approval through the ApprovalManager
  • Business Rules: Workflow configuration determines approval requirements and status transitions based on current state and event type

API Methods

User Management

  • init (INIT) - Create a new partner user account

    • Initializes user with PENDING status
    • Triggers approval workflow for user creation
    • Streams user data to MongoDB
    • Input: fullName, email, partners (with roles), venues (optional)
  • getUser (READ) - Retrieve partner user details

    • Returns user profile with partner associations and venue assignments
    • Accessible by ProgramManagementUser identity
  • updateUser (WRITE) - Update partner user information

    • Updates fullName, email, partner associations, and venue assignments
    • Triggers approval workflow for updates
    • All fields are required (no partial updates)
  • updateStatus (WRITE) - Change user status

    • Updates user status (PENDING/ACTIVE/INACTIVE)
    • Triggers approval workflow for status changes
    • Optional statusReason parameter for audit trail
  • listPartnerUsers (STATIC) - List all partner users

    • Paginated listing with filtering support
    • Filter by status, partnerId, or search term (fullName/email)
    • Returns users with totalCount, page, limit, and totalPages
    • Queries MongoDB for efficient large-scale retrieval

Venue Management

  • addVenues (WRITE) - Add venues to user

    • Assigns additional venues to partner user
    • Prevents duplicate venue assignments
    • Input: array of venue associations (partnerId + venueId)
  • removeVenues (WRITE) - Remove venues from user

    • Removes venue access from partner user
    • Input: array of venueIds to remove
  • listVenues (READ) - List user's venues

    • Returns all venue associations for the partner user

Role Information

  • getRoles (STATIC) - Get available partner user roles
    • Returns all available PartnerUserRole enum values
    • Formatted for client-side dropdowns and forms
    • Output includes key, value, and human-readable label
    • Stateless method requiring no instance

Approval Operations

  • approveUser (WRITE) - Approve workflow action
    • Internal method called by ApprovalManager
    • Applies JSON patch updates to user state
    • Restricted to ApprovalManager class identity

Key Features

  1. Instance-Based Architecture: Each partner user has a unique instance ID, allowing independent state management and scalability

  2. Multi-Partner Support: Users can be associated with multiple partner organizations simultaneously, each with their own role assignment

  3. Per-Partner Role System: Simple enum-based roles (ADMIN, MANAGER, STAFF) assigned per partner rather than globally, enabling flexible access control

  4. Multi-Venue Access: Granular venue-level assignments allow users to access specific locations within their partner organizations

  5. Workflow Approval Integration: All user creation, updates, and status changes can be configured to require approval through the workflow system

  6. MongoDB Streaming: User data is automatically synchronized to MongoDB for efficient querying and external system integration

  7. Independent Role Management: Deliberately uses simple enum-based roles instead of the complex RoleManager system to simplify partner application architecture

  8. Phase 1 Implementation: Current implementation focuses on user account management; authentication and authorization are planned for future phases

  9. Audit Trail: All state changes are tracked with createdBy, updatedBy, createdAt, and updatedAt timestamps

  10. Scalable Query Support: STATIC listPartnerUsers method leverages MongoDB for efficient pagination and filtering across large user datasets

Register Flows

Register Separation Flow

Emirates Employee Register Flow

Prerequired Integrations:

  • Employee Detail API - HR System
  • Employee EPC Member ID Update API - HR System
  • User ID Card API - HR System/ID Card System

Sequence Diagram

Employee Register Integration Flow

Employee Detail API (HR System)

The Employee Detail API should return the following fields:

Request

FieldTypeDescriptionOptional
emailstringfalse

Response

FieldTypeDescriptionOptional
employeeIdstringfalse
birthdatedatefalse
emailstringfalse
namestringfalse
surnamestringfalse
phonestringfalse
gradestringfalse
isCabinCrewbooleanfalse
employmentTypestringfalse
companyIdstringfalse
statusstringfalse
lastStatusUpdatedAtdatefalse
addressstringfalse
countrystringfalse
familyarrayList of family membersfalse
family.idstringfalse
family.typestringfalse
family.namestringfalse
family.surnamestringfalse
family.emailstringfalse
family.birthdatedatefalse

Member Id Update API (HR System)

Update the member ID for an employee in the HR system. This API is used to update the member ID of an employee in the HR system when a employee becomes a member of the EPC.

Request

FieldTypeDescriptionOptional
employeeIdstringfalse
memberIdstringfalse

Response

A response indicates whether the operation is successfull or not

Emirates Retired Employee Register Flow

Prerequired Integrations:

  • Employee Detail API - HR System
  • Employee EPC Member ID Update API - HR System
  • User ID Card API - HR System/ID Card System

Sequence Diagram

Retired Employee Register Integration Flow

Employee Detail API (HR System)

The Employee Detail API should return the following fields:

Request

FieldTypeDescriptionOptional
emailstringfalse

Response

FieldTypeDescriptionOptional
employeeIdstringfalse
birthdatedatefalse
emailstringfalse
namestringfalse
surnamestringfalse
phonestringfalse
gradestringfalse
isCabinCrewbooleanfalse
employmentTypestringfalse
companyIdstringfalse
statusstringfalse
lastStatusUpdatedAtdatefalse
addressstringfalse
countrystringfalse
familyarrayList of family membersfalse
family.idstringfalse
family.typestringfalse
family.namestringfalse
family.surnamestringfalse
family.emailstringfalse
family.birthdatedatefalse

Member Id Update API (HR System)

Update the member ID for an employee in the HR system. This API is used to update the member ID of an employee in the HR system when a employee becomes a member of the EPC.

Request

FieldTypeDescriptionOptional
employeeIdstringfalse
memberIdstringfalse

Response

A response indicates whether the operation is successfull or not

Associated Company Employee Register Flow

Sequence Diagram

Associated Company Employee Register Integration Flow

Dependant Employee Register Flow

Sequence Diagram

Dependant Register Integration Flow

Update Flows

Emirates Employee Update Flow

Prerequired Integrations:

  • Member Update API - EPC
  • Member Update API Call On Employee Update - HR System

Sequence Diagram

Employee Update Integration Flow

Member Update API (EPC)

The details of the Member Update API exist in the following documentation:

Emirates Employee Photo Update Flow

Prerequired Integrations:

  • Member Photo Update API - EPC
  • Member Photo Update API Call On Employee Photo Update - HR System

Sequence Diagram

Employee Photo Update Integration Flow

Member Photo Update API (EPC)

The details of the Member Photo Update API exist in the following documentation:

Migration

Member

Migration Option With HR API

The migration of existing members in the HR system might be handled via member register integration.

Migration Option Without HR API

Possible Excel Fields

Member Excel

FieldTypeDescriptionSource field
employeeIdstringstaffId
oldEmployeeIdstring(optional)oldStaffId
dependantIdstringid of the dependantserialNumber
emailstring
namestring
middleNamestring(optional)
surnamestring
idPhotostringimage id, get img from api
phonestringformat will be provided
gradestringequilentGrade
isCabinCrewbooleanaccording to grade
employmentTypestringPermanent/Temporary/Retire/Dependant/Associated Company
companyIdstring
birthdatestringISO 8601 date
addressCountrystringcountry code
addressstring
primaryMemberTypestringRegular/Club/Premium
secondaryMemberTypestring(optional)Face
dependantTypestringspouse/child/sibling/in-law/parentrelation
membershipStatusstringactive/inactiveisActive
membershipStartstringISO 8601 datestartDate
membershipEndstringISO 8601 dateexpireDate
membershipLastRenewalstringISO 8601 date (it will be check)
membershipPaymentTypestringDDS/Credit Card/Company Paid (according to employment Type)
membershipPaymentPeriodstringmap according to employment/member type
createdAtstring(optional)ISO 8601 datememberCreationDatetime
updatedAtstring(optional)ISO 8601 dateupdatedDatetime

Family Member Excel

FieldTypeDescriptionSource field
employeeIdstringstaffId
dependantIdstringid of the dependant(optional)serial_number
relationstringspouse/child/sibling/in-law/parent
namestring
middleNamestring(optional)
surnamestring
phonestring
emailstring
birthdatestringISO 8601 date

Partner

Partner Location

FieldTypeDescription
idstringUnique identifier
partnerIdstringPartner's ID
statusPartnerLocationStatusLocation status
addressstringAddress
coordinateLatnumberLatitude
coordinateLongnumberLongitude
contactPersonFullNamestringContact person details
contactPersonEmailstringContact person details
contactPersonPhonestringContact person details
createdAtstringCreation timestamp
updatedAtstringLast update timestamp

Partner Staff User

FieldTypeDescription
idstringUnique identifier
namestringStaff user name
locationIdsstring[]Associated location IDs
statusPartnerStaffUserStatusStaff user status
createdAtDateCreation timestamp
updatedAtDateLast update timestamp

Partner

FieldTypeDescription
idstring
legalNamestringLegal name
brandNamestringBrand name
partnerTierstringPartner tier
logostringLogo URL or path
categoryIdstringCategory ID
subCategoryIdstringCategory ID
addressstringAddress
coordinateLatnumberLatitude
coordinateLongnumberLongitude
countrystringCountry
citystringCity
websitestringWebsite URL
contactEmailstringContact email
contactPhonestringContact phone
contracts?the id, start date and end dates of contracts
createdAtDateCreation timestamp
updatedAtDateLast update timestamp

Offer Migration

Offers will migrate via Excel file.

OfferCategory

Possible Excel Fields

FieldTypeDescription
idstring
namestring
subcategoriesstringcomma separated
keywordsstringcomma separated
createdAtstringISO 8601 date
updatedAtstringISO 8601 date

Offer

Possible Excel Fields

FieldTypeDescriptionSource field
idstringunique id(numeric on old system)offerId
partnerIdstringit must be compatible with salesforce partner id
statusstringpublished/unpublished/expired
keywordsstring
offerTypestring
startDatestringISO 8601 date
endDatestringISO 8601 date
imagesstringimage urls, comma separated
shortDescriptionstring
titlestring
descriptionstring
categoryIdsstringcomma separated
startDatestringISO 8601 date
endDatestringISO 8601 date
createdAtstringISO 8601 date
updatedAtstringISO 8601 date

Glosarry

KeywordExplanation
EPCEmirates Platinum Card
CPGEmirates Payment Gateway
PCI DDSPayment Card Industry Data Security Standard
RIORetter's Serverless Framework