

# Service Design Specification
**tutorhub-enrollmentmanagement-service** documentation
**Version:** `1.0.76`

## Scope

This document provides a structured architectural overview of the `enrollmentManagement` microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

* **Service architects** can use it to validate design decisions and ensure alignment with broader architectural goals.
* **Developers and maintainers** will find it useful for understanding the structure and behavior of the service, facilitating easier debugging, feature extension, and integration with other systems.
* **Stakeholders and reviewers** can use it to gain a clear understanding of the service's capabilities and domain logic.

> **Note for Frontend Developers**: While this document is valuable for understanding business logic and data interactions, please refer to the [Service API Documentation](#) for endpoint-level specifications and integration details.

> **Note for Backend Developers**: Since the code for this service is automatically generated by Mindbricks, you typically won't need to implement or modify it manually. However, this document is especially valuable when you're building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service's data contracts, business rules, and API structure, helping ensure compatibility and correct integration.



## `EnrollmentManagement` Service Settings

Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance.

### Service Overview

This service is configured to listen for HTTP requests on port `3003`, 
serving both the main API interface and default administrative endpoints.

The following routes are available by default:

* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`

The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-enrollmentmanagement-service`.

This service is accessible via the following environment-specific URLs:

* **Preview:** `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api`
* **Staging:** `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api`
* **Production:** `https://tutorhub.mindbricks.co/enrollmentmanagement-api`

                                 

### Authentication & Security
- **Login Required**: Yes

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity.
If a crud route also is configured to require login, 
it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

  
### Service Data Objects
The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-enrollmentmanagement-service`.

Data deletion is managed using a **soft delete** strategy. Instead of removing records from the database, they are flagged as inactive by setting the `isActive` field to `false`.



| Object Name | Description | Public Access |
|-------------|-------------|---------------|
| `enrollment` | Represents a student&#39;s enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. | accessPrivate | 
| `refundRequest` | A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. | accessPrivate | 
| `sys_enrollmentPayment` | A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object&#39;s checkout config | accessPrivate | 
| `sys_paymentCustomer` | A payment storage object to store the customer values of the payment platform | accessPrivate | 
| `sys_paymentMethod` | A payment storage object to store the payment methods of the platform customers | accessPrivate | 




## enrollment Data Object

### Object Overview
**Description:** Represents a student&#39;s enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.




### Composite Indexes

- **enrollment_unique_booking**: [studentId, coursePackId] 
This composite index is defined to optimize query performance for complex queries involving multiple fields.

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

**On Duplicate**: `throwError`

An error will be thrown, preventing the insertion of conflicting data.





### Stripe Integration

This data object is configured to integrate with Stripe for order management of `enrollment`. It is designed to handle payment processing and order tracking.
To manage payments, Mindbricks will design additional Business API routes arround this data object, which will be used checkout orders and charge customers.

- **Order Name**: `enrollment`

- **Order Id Property**: 
This MScript expression is used to extract the order's unique identifier from the data object.
- **Order Amount Property**: 
This MScript expression is used to determine the order amount for payment. It should return a numeric value representing the total amount to be charged.
- **Order Currency Property**: 
This MScript expression is used to determine the currency for the order. It should return a string representing the currency code (e.g., "USD", "EUR").
- **Order Description Property**: `Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}`
This MScript expression is used to provide a description for the order, which will be shown in Stripe and on customer receipts. It should return a string that describes the order.
- **Order Status Property**: paymentStatus
This property is selected as the order status property, which will be used to track the current status of the order.
It will be automatically updated based on payment results from Stripe.
- **Order Status Update Date Property**: updatedAt
This property is selected to record the timestamp of the last order status update. It will be automatically managed during payment events to reflect when the status was last changed.
- **Order Owner Id Property**: studentId
This property is selected as the order owner property, which will be used to track the user who owns the order.
It will be used to ensure correct access control in payment flows, allowing only the owner to manage their orders.
- **Map Payment Result to Order Status**:
This configuration defines how Stripe's payment results (e.g., started, success, failed, canceled) map to internal order statuses.,
`paymentResultStarted` status will be mapped to a local value using `&#34;pending&#34;` and will be set to `paymentStatus`property.
`paymentResultCanceled` status will be mapped to a local value using `&#34;pending&#34;` and will be set to `paymentStatus` property.
`paymentResultFailed` status will be mapped to a local value using `&#34;pending&#34;` and will be set to `paymentStatus` property.
`paymentResultSuccess` status will be mapped to a local value using `&#34;paid&#34;` and will be set to `paymentStatus` property.
- **On Checkout Error**: 

if an error occurs during the checkout process, the API will continue to execute, allowing for custom error handling.
In this case, the payment error will ve recorded as a status update. To make a retry a new checkout, a new order will be created with the same data as the original order.


### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `coursePackId` | ID | Yes | FK to purchased course pack. |
| `studentId` | ID | Yes | FK to enrolling student (auth:user). |
| `tutorProfileId` | ID | Yes | FK to the course&#39;s tutorProfile for admin/analytics. |
| `lessonSlotIds` | ID | Yes | IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). |
| `totalAmount` | Double | Yes | Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). |
| `currency` | String | Yes | 3-letter ISO currency code (e.g., &#39;USD&#39;, &#39;EUR&#39;). |
| `paymentStatus` | Enum | Yes | Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation). |
| `refundStatus` | Enum | Yes | Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. |
| `enrollmentStatus` | Enum | Yes | Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated). |
| `enrolledAt` | Date | No | Datetime of completed enrollment (post-payment). |
| `paymentConfirmation` | Enum | Yes | An automatic property that is used to check the confirmed status of the payment set by webhooks. |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.


### Array Properties 

`lessonSlotIds`

Array properties can hold multiple values and are indicated by the `[]` suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly.
Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.


### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **coursePackId**: '00000000-0000-0000-0000-000000000000'
- **studentId**: '00000000-0000-0000-0000-000000000000'
- **tutorProfileId**: '00000000-0000-0000-0000-000000000000'
- **lessonSlotIds**: []
- **totalAmount**: 0.0
- **currency**: USD
- **paymentStatus**: pending
- **refundStatus**: notRequested
- **enrollmentStatus**: pending
- **paymentConfirmation**: pending

### Always Create with Default Values
Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

- **paymentStatus**: Will be created with value `pending`

- **enrollmentStatus**: Will be created with value `pending`

- **paymentConfirmation**: Will be created with value `pending`


### Constant Properties

`coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` `totalAmount` `currency` `enrolledAt`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`paymentStatus` `refundStatus` `enrollmentStatus`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 


### Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. 
The enum options value will be stored as strings in the database, 
but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option.
You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

- **paymentStatus**: [pending, paid, refunded]

- **refundStatus**: [notRequested, eligible, processed, ineligible]

- **enrollmentStatus**: [pending, active, completed, canceled]

- **paymentConfirmation**: [pending, processing, paid, canceled]


 

 

### Elastic Search Indexing

`coursePackId` `studentId` `totalAmount` `currency` `paymentStatus` `refundStatus` `enrollmentStatus` `enrolledAt` `paymentConfirmation`

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. 
While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


### Database Indexing

`coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` `totalAmount` `paymentStatus` `refundStatus` `enrollmentStatus` `paymentConfirmation`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.





### Secondary Key Properties

`paymentConfirmation`

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns.
Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.


### Relation Properties

`coursePackId` `studentId` `tutorProfileId` `lessonSlotIds`

Mindbricks supports relations between data objects, allowing you to define how objects are linked together.
You can define relations in the data object properties, which will be used to create foreign key constraints in the database.
For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes.
Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

- **coursePackId**: ID
Relation to `coursePack`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes

- **studentId**: ID
Relation to `user`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes

- **tutorProfileId**: ID
Relation to `tutorProfile`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes

- **lessonSlotIds**: ID
Relation to `lessonSlot`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes


### Session Data Properties

`studentId`

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage.
If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations.
Note that session data properties can not be mutated by the user, but only by the system.

- **studentId**: ID property will be mapped to the session parameter `userId`.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.





### Filter Properties

`paymentConfirmation`

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria.
These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled.

- **paymentConfirmation**: Enum  has a filter named `paymentConfirmation`





## refundRequest Data Object

### Object Overview
**Description:** A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.




### Composite Indexes

- **unique_enrollment_refund**: [enrollmentId] 
This composite index is defined to optimize query performance for complex queries involving multiple fields.

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

**On Duplicate**: `throwError`

An error will be thrown, preventing the insertion of conflicting data.






### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `enrollmentId` | ID | Yes | FK to enrollment object for which refund is being requested (unique: one refund per enrollment). |
| `requestedBy` | ID | Yes | User (student) making the refund request (auth:user id). |
| `requestedAt` | Date | Yes | Datetime refund was requested. |
| `processedAt` | Date | No | When refund was processed by system (auto-approval). |
| `status` | Enum | Yes | Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). |
| `reason` | String | Yes | User-supplied reason for requesting refund. |
| `firstLessonCompleted` | Boolean | Yes | True if this refund is after first lesson (enforced by workflow); must be checked before approval. |
| `adminNote` | String | No | Admin note explaining the refund decision (approve/reject reason). |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.



### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **enrollmentId**: '00000000-0000-0000-0000-000000000000'
- **requestedBy**: '00000000-0000-0000-0000-000000000000'
- **requestedAt**: new Date()
- **status**: pending
- **reason**: 'default'
- **firstLessonCompleted**: false


### Constant Properties

`enrollmentId` `requestedBy` `requestedAt` `reason` `firstLessonCompleted`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`processedAt` `status` `adminNote`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 


### Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. 
The enum options value will be stored as strings in the database, 
but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option.
You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

- **status**: [pending, approved, rejected, autoApproved]


 

 


### Database Indexing

`enrollmentId` `requestedBy` `requestedAt` `processedAt` `status`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.


### Unique Properties

`enrollmentId`

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option.





### Relation Properties

`enrollmentId` `requestedBy`

Mindbricks supports relations between data objects, allowing you to define how objects are linked together.
You can define relations in the data object properties, which will be used to create foreign key constraints in the database.
For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes.
Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

- **enrollmentId**: ID
Relation to `enrollment`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes

- **requestedBy**: ID
Relation to `user`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes


### Session Data Properties

`requestedBy`

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage.
If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations.
Note that session data properties can not be mutated by the user, but only by the system.

- **requestedBy**: ID property will be mapped to the session parameter `userId`.









## sys_enrollmentPayment Data Object

### Object Overview
**Description:** A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object&#39;s checkout config

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `ownerId` | ID | No |  An ID value to represent owner user who created the order |
| `orderId` | ID | Yes | an ID value to represent the orderId which is the ID parameter of the source enrollment object |
| `paymentId` | String | Yes | A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type |
| `paymentStatus` | String | Yes | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. |
| `statusLiteral` | String | Yes | A string value to represent the logical payment status which belongs to the application lifecycle itself. |
| `redirectUrl` | String | No | A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.



### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **orderId**: '00000000-0000-0000-0000-000000000000'
- **paymentId**: 'default'
- **paymentStatus**: 'default'
- **statusLiteral**: started


### Constant Properties

`orderId`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 



 

 

### Elastic Search Indexing

`ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl`

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. 
While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


### Database Indexing

`ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.


### Unique Properties

`orderId`

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option.




### Secondary Key Properties

`orderId`

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns.
Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.



### Session Data Properties

`ownerId`

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage.
If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations.
Note that session data properties can not be mutated by the user, but only by the system.

- **ownerId**: ID property will be mapped to the session parameter `userId`.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.





### Filter Properties

`ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl`

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria.
These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled.

- **ownerId**: ID  has a filter named `ownerId`

- **orderId**: ID  has a filter named `orderId`

- **paymentId**: String  has a filter named `paymentId`

- **paymentStatus**: String  has a filter named `paymentStatus`

- **statusLiteral**: String  has a filter named `statusLiteral`

- **redirectUrl**: String  has a filter named `redirectUrl`





## sys_paymentCustomer Data Object

### Object Overview
**Description:** A payment storage object to store the customer values of the payment platform

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `userId` | ID | No |  An ID value to represent the user who is created as a stripe customer |
| `customerId` | String | Yes | A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway |
| `platform` | String | Yes | A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future. |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.



### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **customerId**: 'default'
- **platform**: stripe


### Constant Properties

`customerId` `platform`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`userId` `customerId` `platform`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 



 

 

### Elastic Search Indexing

`userId` `customerId` `platform`

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. 
While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


### Database Indexing

`userId` `customerId` `platform`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.


### Unique Properties

`userId` `customerId`

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option.




### Secondary Key Properties

`userId` `customerId`

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns.
Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.



### Session Data Properties

`userId`

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage.
If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations.
Note that session data properties can not be mutated by the user, but only by the system.

- **userId**: ID property will be mapped to the session parameter `userId`.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.





### Filter Properties

`userId` `customerId` `platform`

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria.
These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled.

- **userId**: ID  has a filter named `userId`

- **customerId**: String  has a filter named `customerId`

- **platform**: String  has a filter named `platform`





## sys_paymentMethod Data Object

### Object Overview
**Description:** A payment storage object to store the payment methods of the platform customers

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `paymentMethodId` | String | Yes | A string value to represent the id of the payment method on the payment platform. |
| `userId` | ID | Yes |  An ID value to represent the user who owns the payment method |
| `customerId` | String | Yes | A string value to represent the customer id which is generated on the payment gateway. |
| `cardHolderName` | String | No | A string value to represent the name of the card holder. It can be different than the registered customer. |
| `cardHolderZip` | String | No | A string value to represent the zip code of the card holder. It is used for address verification in specific countries. |
| `platform` | String | Yes | A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future. |
| `cardInfo` | Object | Yes | A Json value to store the card details of the payment method. |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.



### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **paymentMethodId**: 'default'
- **userId**: '00000000-0000-0000-0000-000000000000'
- **customerId**: 'default'
- **platform**: stripe
- **cardInfo**: {}


### Constant Properties

`paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` `cardInfo`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 



 

 

### Elastic Search Indexing

`paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` `cardInfo`

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. 
While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


### Database Indexing

`paymentMethodId` `userId` `customerId` `platform` `cardInfo`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.


### Unique Properties

`paymentMethodId`

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option.




### Secondary Key Properties

`paymentMethodId` `userId` `customerId`

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns.
Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.



### Session Data Properties

`userId`

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage.
If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations.
Note that session data properties can not be mutated by the user, but only by the system.

- **userId**: ID property will be mapped to the session parameter `userId`.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.





### Filter Properties

`paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` `cardInfo`

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria.
These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled.

- **paymentMethodId**: String  has a filter named `paymentMethodId`

- **userId**: ID  has a filter named `userId`

- **customerId**: String  has a filter named `customerId`

- **cardHolderName**: String  has a filter named `cardHolderName`

- **cardHolderZip**: String  has a filter named `cardHolderZip`

- **platform**: String  has a filter named `platform`

- **cardInfo**: Object  has a filter named `cardInfo`







## Business Logic



enrollmentManagement has got 26 Business APIs to manage its internal and crud logic. 
For the details of each business API refer to its chapter.

* [Create Enrollment](/businessLogic/createenrollment)

* [Get Enrollment](/businessLogic/getenrollment)

* [List Enrollments](/businessLogic/listenrollments)

* [Create Refundrequest](/businessLogic/createrefundrequest)

* [Get Refundrequest](/businessLogic/getrefundrequest)

* [List Refundrequests](/businessLogic/listrefundrequests)

* [Update Refundrequest](/businessLogic/updaterefundrequest)

* [Cancel Enrollment](/businessLogic/cancelenrollment)

* [Admin Refundenrollment](/businessLogic/adminrefundenrollment)

* [Cascade Tutorban](/businessLogic/cascadetutorban)

* [Cascade Courseremoval](/businessLogic/cascadecourseremoval)

* [Cleanup Pendingenrollments](/businessLogic/cleanuppendingenrollments)

* [Check Enrollmentcompletion](/businessLogic/checkenrollmentcompletion)

* [Get Enrollmentpayment](/businessLogic/getenrollmentpayment)

* [List Enrollmentpayments](/businessLogic/listenrollmentpayments)

* [Create Enrollmentpayment](/businessLogic/createenrollmentpayment)

* [Update Enrollmentpayment](/businessLogic/updateenrollmentpayment)

* [Delete Enrollmentpayment](/businessLogic/deleteenrollmentpayment)

* [Get Enrollmentpaymentbyorderid](/businessLogic/getenrollmentpaymentbyorderid)

* [Get Enrollmentpaymentbypaymentid](/businessLogic/getenrollmentpaymentbypaymentid)

* [Start Enrollmentpayment](/businessLogic/startenrollmentpayment)

* [Refresh Enrollmentpayment](/businessLogic/refreshenrollmentpayment)

* [Callback Enrollmentpayment](/businessLogic/callbackenrollmentpayment)

* [Get Paymentcustomerbyuserid](/businessLogic/getpaymentcustomerbyuserid)

* [List Paymentcustomers](/businessLogic/listpaymentcustomers)

* [List Paymentcustomermethods](/businessLogic/listpaymentcustomermethods)















## Edge Controllers


### deletePaymentMethodEdge

**Configuration:**
- **Function Name**: `deletePaymentMethodEdge`
- **Login Required**: Yes

**REST Settings:**
- **Path**: `/payment-methods/delete/:paymentMethodId`
- **Method**: 

---

### onRefundRequestCreated

**Configuration:**
- **Function Name**: `onRefundRequestCreated`
- **Login Required**: No

**REST Settings:**
- **Path**: ``
- **Method**: 

---

### onEnrollmentPaymentDone

**Configuration:**
- **Function Name**: `onEnrollmentPaymentDone`
- **Login Required**: No

**REST Settings:**
- **Path**: ``
- **Method**: 

---





## Service Library


### Functions

#### getTutorProfileIdsByTutorId.js
```js
module.exports = async function getTutorProfileIdsByTutorId(userId) {
  // Fetch all tutorProfiles for this user from tutorCatalog
  const { fetchRemoteListByMQuery } = require("serviceCommon");
  const profiles = await fetchRemoteListByMQuery("tutorProfile", { tutorId: userId });
  return profiles.map(p => p.id);
}
```

#### validateEnrollmentConstraints.js
```js
module.exports = function validateEnrollmentConstraints(coursePack, lessonSlotIds, screeningMeetings, studentId, tutorUser) {
  if (!coursePack) return { valid: false, error: 'Course pack not found.' };

  // 1. Course moderation check
  if (coursePack.moderationStatus === 'removed') {
    return { valid: false, error: 'This course has been removed and is no longer available for enrollment.' };
  }
  if (coursePack.moderationStatus === 'flagged') {
    return { valid: false, error: 'This course is currently under review and cannot accept new enrollments.' };
  }
  if (coursePack.isPublished === false) {
    return { valid: false, error: 'This course is not currently published.' };
  }

  // 2. Tutor status check
  if (tutorUser) {
    if (tutorUser.accountStatus === 'banned') {
      return { valid: false, error: 'This tutor\'s account has been suspended. Enrollment is not available.' };
    }
    if (tutorUser.accountStatus === 'suspended') {
      return { valid: false, error: 'This tutor\'s account is temporarily suspended. Please try again later.' };
    }
  }

  // 3. Screening check
  if (coursePack.preliminaryMeetingRequired) {
    const approved = (screeningMeetings || []).find(
      m => m.studentId === studentId && m.tutorDecision === 'approved'
    );
    if (!approved) return { valid: false, error: 'Screening approval is required before enrollment.' };
  }

  // lessonSlotIds is the array of IDs from the request
  const slots = Array.isArray(lessonSlotIds) ? lessonSlotIds : [];
  const slotCount = slots.length;
  if (slotCount === 0) return { valid: false, error: 'At least one lesson slot is required.' };

  // 4. Required classes count
  if (coursePack.requiredClassesCount && slotCount !== coursePack.requiredClassesCount) {
    return { valid: false, error: `This course requires exactly ${coursePack.requiredClassesCount} classes. Got ${slotCount}.` };
  }

  return { valid: true, error: null };
}
```

#### validateRefundEligibility.js
```js
module.exports = function validateRefundEligibility(enrollment, lessonSlots, paymentRecord) {
  if (!enrollment) return { eligible: false, error: 'Enrollment not found.' };

  // Must be an active enrollment
  if (enrollment.enrollmentStatus !== 'active') {
    return { eligible: false, error: 'Only active enrollments can be refunded.' };
  }

  // Must have paid status
  if (enrollment.paymentStatus !== 'paid') {
    return { eligible: false, error: 'Only paid enrollments can be refunded.' };
  }

  // Must not already be refunded
  if (enrollment.refundStatus === 'processed') {
    return { eligible: false, error: 'This enrollment has already been refunded.' };
  }

  // Must have a valid payment record with paymentId for Stripe refund
  if (!paymentRecord || !paymentRecord.paymentId) {
    return { eligible: false, error: 'No payment record found for this enrollment. Cannot process refund.' };
  }

  // Check lesson completion status
  const slots = lessonSlots || [];
  const completedSlots = slots.filter(s => s.status === 'completed');

  // --- PATH 1: Within 1 hour of enrollment → auto-approved instant refund ---
  const enrolledAt = enrollment.enrolledAt || enrollment.createdAt;
  const enrollmentTime = enrolledAt ? new Date(enrolledAt).getTime() : 0;
  const now = Date.now();
  const oneHourMs = 60 * 60 * 1000;
  const withinOneHour = enrollmentTime > 0 && (now - enrollmentTime) <= oneHourMs;

  if (withinOneHour) {
    return {
      eligible: true,
      error: null,
      refundType: 'autoApproved',
      firstLessonCompleted: completedSlots.length >= 1,
      stripePaymentIntentId: paymentRecord.paymentId,
      refundAmount: enrollment.totalAmount,
      currency: enrollment.currency
    };
  }

  // --- PATH 2: After first lesson completed (exactly 1) → pending admin review ---
  if (completedSlots.length === 1) {
    return {
      eligible: true,
      error: null,
      refundType: 'pendingReview',
      firstLessonCompleted: true,
      stripePaymentIntentId: paymentRecord.paymentId,
      refundAmount: enrollment.totalAmount,
      currency: enrollment.currency
    };
  }

  // --- DENIED: No lessons completed (past 1 hour) ---
  if (completedSlots.length === 0) {
    return { eligible: false, error: 'The 1-hour instant refund window has passed. Refund is available after your first lesson is completed.' };
  }

  // --- DENIED: More than 1 lesson completed ---
  return { eligible: false, error: 'Refund is no longer available after more than one lesson has been completed.' };
}
```

#### cancelEnrollmentLessonSlots.js
```js
module.exports = async function cancelEnrollmentLessonSlots(lessonSlotIds, session) {
  if (!lessonSlotIds || !Array.isArray(lessonSlotIds) || lessonSlotIds.length === 0) {
    return { canceled: 0, errors: [] };
  }

  const axios = require('axios');
  const { getServiceSecret } = require('common');

  // Build the courseScheduling M2M URL
  // In preview, services are on the same host with different routes
  const baseUrl = process.env.COURSESCHEDULING_API_URL || 'http://localhost:3002';
  const m2mUrl = `${baseUrl}/m2m/updateLessonSlotById`;

  const serviceSecret = getServiceSecret ? getServiceSecret() : process.env.SERVICE_SECRET_KEY;

  let canceled = 0;
  const errors = [];

  for (const slotId of lessonSlotIds) {
    try {
      await axios.patch(m2mUrl, {
        id: slotId,
        dataClause: { status: 'canceled' }
      }, {
        headers: {
          'Content-Type': 'application/json',
          ...(serviceSecret ? { 'x-service-secret': serviceSecret } : {}),
          ...(session?.token ? { 'Authorization': `Bearer ${session.token}` } : {})
        },
        timeout: 5000
      });
      canceled++;
    } catch (err) {
      errors.push({ slotId, error: err.message });
    }
  }

  return { canceled, total: lessonSlotIds.length, errors };
}
```

#### cancelAllTutorEnrollments.js
```js
module.exports = async function cancelAllTutorEnrollments(tutorProfileId, reason, session) {
  const { updateEnrollmentById } = require('dbLayer');
  const { ElasticIndexer } = require('serviceCommon');
  const { convertUserQueryToElasticQuery } = require('common');

  const userQuery = {
    $and: [
      { tutorProfileId: tutorProfileId },
      { enrollmentStatus: 'active' },
      { isActive: true }
    ]
  };
  const elasticQuery = convertUserQueryToElasticQuery(userQuery);
  const elasticIndex = new ElasticIndexer('enrollment');
  const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || [];

  if (enrollments.length === 0) {
    return { canceled: 0, total: 0, errors: [], affectedStudentIds: [] };
  }

  const context = { session, requestId: 'cascade-tutor-ban' };
  let canceled = 0;
  const errors = [];
  const affectedStudentIds = [];

  for (const enrollment of enrollments) {
    try {
      await updateEnrollmentById(enrollment.id, {
        enrollmentStatus: 'canceled',
        paymentStatus: 'refunded',
        refundStatus: 'processed'
      }, context);

      if (enrollment.studentId) affectedStudentIds.push(enrollment.studentId);

      if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) {
        try {
          const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots');
          await cancelSlots(enrollment.lessonSlotIds, session);
        } catch (slotErr) {
          console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message);
        }
      }

      canceled++;
    } catch (err) {
      errors.push({ enrollmentId: enrollment.id, error: err.message });
    }
  }

  return { canceled, total: enrollments.length, errors, affectedStudentIds: [...new Set(affectedStudentIds)] };
}
```

#### cancelAllCourseEnrollments.js
```js
module.exports = async function cancelAllCourseEnrollments(coursePackId, reason, session) {
  const { updateEnrollmentById } = require('dbLayer');
  const { ElasticIndexer } = require('serviceCommon');
  const { convertUserQueryToElasticQuery } = require('common');

  const userQuery = {
    $and: [
      { coursePackId: coursePackId },
      { enrollmentStatus: 'active' },
      { isActive: true }
    ]
  };
  const elasticQuery = convertUserQueryToElasticQuery(userQuery);
  const elasticIndex = new ElasticIndexer('enrollment');
  const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || [];

  if (enrollments.length === 0) {
    return { canceled: 0, total: 0, errors: [], affectedStudentIds: [] };
  }

  const context = { session, requestId: 'cascade-course-removal' };
  let canceled = 0;
  const errors = [];
  const affectedStudentIds = [];

  for (const enrollment of enrollments) {
    try {
      await updateEnrollmentById(enrollment.id, {
        enrollmentStatus: 'canceled',
        paymentStatus: 'refunded',
        refundStatus: 'processed'
      }, context);

      if (enrollment.studentId) affectedStudentIds.push(enrollment.studentId);

      if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) {
        try {
          const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots');
          await cancelSlots(enrollment.lessonSlotIds, session);
        } catch (slotErr) {
          console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message);
        }
      }

      canceled++;
    } catch (err) {
      errors.push({ enrollmentId: enrollment.id, error: err.message });
    }
  }

  return { canceled, total: enrollments.length, errors, affectedStudentIds: [...new Set(affectedStudentIds)] };
}
```

#### cleanupPendingEnrollments.js
```js
module.exports = async function cleanupPendingEnrollments(maxAgeMinutes, session) {
  const { updateEnrollmentById } = require('dbLayer');
  const { ElasticIndexer } = require('serviceCommon');
  const { convertUserQueryToElasticQuery } = require('common');

  const cutoff = new Date(Date.now() - (maxAgeMinutes || 60) * 60 * 1000).toISOString();

  // Find pending enrollments older than cutoff
  const userQuery = {
    $and: [
      { enrollmentStatus: 'pending' },
      { paymentStatus: 'pending' },
      { createdAt: { $lt: cutoff } },
      { isActive: true }
    ]
  };
  const elasticQuery = convertUserQueryToElasticQuery(userQuery);
  const elasticIndex = new ElasticIndexer('enrollment');
  const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || [];

  if (enrollments.length === 0) {
    return { cleaned: 0, total: 0, errors: [] };
  }

  const context = { session: session || {}, requestId: 'cleanup-pending-enrollments' };
  let cleaned = 0;
  const errors = [];

  for (const enrollment of enrollments) {
    try {
      // Cancel the enrollment
      await updateEnrollmentById(enrollment.id, {
        enrollmentStatus: 'canceled',
        refundStatus: 'ineligible'
      }, context);

      // Free lesson slots
      if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) {
        try {
          const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots');
          await cancelSlots(enrollment.lessonSlotIds, session);
        } catch (slotErr) {
          console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message);
        }
      }

      cleaned++;
    } catch (err) {
      errors.push({ enrollmentId: enrollment.id, error: err.message });
    }
  }

  return { cleaned, total: enrollments.length, errors };
}
```

#### checkEnrollmentCompletion.js
```js
module.exports = async function checkEnrollmentCompletion(enrollmentId, session) {
  const { getEnrollmentById, updateEnrollmentById } = require('dbLayer');
  const { ElasticIndexer } = require('serviceCommon');
  const { convertUserQueryToElasticQuery } = require('common');

  if (!enrollmentId) return { updated: false, reason: 'No enrollmentId' };

  // Fetch the enrollment
  const enrollment = await getEnrollmentById(enrollmentId);
  if (!enrollment) return { updated: false, reason: 'Enrollment not found' };
  if (enrollment.enrollmentStatus !== 'active') return { updated: false, reason: 'Not active' };

  const slotIds = enrollment.lessonSlotIds;
  if (!slotIds || !Array.isArray(slotIds) || slotIds.length === 0) {
    return { updated: false, reason: 'No lesson slots' };
  }

  // Fetch all lesson slots from Elasticsearch
  const userQuery = { id: { $in: slotIds } };
  const elasticQuery = convertUserQueryToElasticQuery(userQuery);
  const elasticIndex = new ElasticIndexer('lessonSlot');
  const slots = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || [];

  // Check if ALL slots are completed
  const allCompleted = slots.length > 0 && slots.length === slotIds.length && slots.every(s => s.status === 'completed');

  if (!allCompleted) {
    return { updated: false, reason: `${slots.filter(s => s.status === 'completed').length}/${slotIds.length} completed` };
  }

  // Mark enrollment as completed
  const context = { session: session || {}, requestId: 'auto-complete-enrollment' };
  await updateEnrollmentById(enrollmentId, { enrollmentStatus: 'completed' }, context);

  return { updated: true, enrollmentId };
}
```

#### publishEnrichedRefundEvent.js
```js
module.exports = async function publishEnrichedRefundEvent(refundRequest, enrollment) {
  const { elasticClient, sendMessageToKafka } = require('common');

  let student = null;
  let tutorUser = null;
  let coursePack = null;

  try {
    const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } });
    if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source;

    const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } });
    const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null;

    if (profile && profile.tutorId) {
      const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } });
      if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source;
    }

    const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category'], size: 1 } });
    if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source;
  } catch (err) {
    console.log('Warning: failed to fetch refund notification data from ES:', err.message);
  }

  const enrichedPayload = {
    id: refundRequest.id,
    enrollmentId: refundRequest.enrollmentId,
    status: refundRequest.status,
    reason: refundRequest.reason,
    requestedAt: refundRequest.requestedAt,
    processedAt: refundRequest.processedAt,
    totalAmount: enrollment.totalAmount,
    currency: enrollment.currency,
    student: student,
    tutorUser: tutorUser,
    coursePack: coursePack
  };

  try {
    const topic = refundRequest.status === 'autoApproved'
      ? 'tutorhub-enrollmentmanagement-service-refund-processed'
      : 'tutorhub-enrollmentmanagement-service-refund-requested';
    await sendMessageToKafka(topic, enrichedPayload);
  } catch (err) {
    console.log('Warning: failed to publish enriched refund event:', err.message);
  }
}
```




### Edge Functions

#### deletePaymentMethodEdge.js
```js
const { getSys_paymentMethodByPaymentMethodId, deleteSys_paymentMethodById } = require('dbLayer');
const { stripeGateway } = require('common');

module.exports = async (request) => {
  const session = request.session;
  const paymentMethodId = request.params.paymentMethodId;
  if (!paymentMethodId) {
    return { status: 400, result: 'ERR', message: 'paymentMethodId is required' };
  }

  const paymentMethodData = await getSys_paymentMethodByPaymentMethodId(paymentMethodId);
  if (!paymentMethodData) {
    return { status: 404, result: 'ERR', message: 'Payment method not found' };
  }
  if (paymentMethodData.userId !== session.userId) {
    return { status: 403, result: 'ERR', message: 'Not authorized to delete this payment method' };
  }

  try {
    if (Object.keys(stripeGateway).length > 0) {
      await stripeGateway.deletePaymentMethod(paymentMethodId);
    }
  } catch (stripeErr) {
    console.log('Stripe detach warning (proceeding with local delete):', stripeErr.message);
  }

  const deleted = await deleteSys_paymentMethodById(paymentMethodData.id);
  if (!deleted) {
    return { status: 500, result: 'ERR', message: 'Failed to delete payment method record' };
  }

  return { status: 200, result: 'OK', message: 'Payment method deleted', data: deleted };
};
```

#### onEnrollmentPaymentDone.js
```js
const { updateEnrollmentById } = require('dbLayer');
const { elasticClient, sendMessageToKafka } = require('common');

module.exports = async (request) => {
  const enrollment = request.enrollment;
  if (!enrollment || !enrollment.id) return { status: 200, message: 'No enrollment to update' };

  await updateEnrollmentById(enrollment.id, {
    enrollmentStatus: 'active',
    enrolledAt: new Date().toISOString()
  });

  let student = null;
  let tutorUser = null;
  let coursePack = null;

  try {
    const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } });
    if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source;

    const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } });
    const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null;

    if (profile && profile.tutorId) {
      const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } });
      if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source;
    }

    const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category', 'schedulingType'], size: 1 } });
    if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source;
  } catch (err) {
    console.log('Warning: failed to fetch notification data from ES:', err.message);
  }

  try {
    await sendMessageToKafka('tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed', {
      id: enrollment.id,
      studentId: enrollment.studentId,
      coursePackId: enrollment.coursePackId,
      tutorProfileId: enrollment.tutorProfileId,
      totalAmount: enrollment.totalAmount,
      currency: enrollment.currency,
      student: student,
      tutorUser: tutorUser,
      coursePack: coursePack
    });
  } catch (err) {
    console.log('Warning: failed to publish enriched enrollment event:', err.message);
  }

  return { status: 200, message: 'Enrollment activated' };
};
```

#### onRefundRequestCreated.js
```js
const { getEnrollmentById } = require('dbLayer');
const { elasticClient, sendMessageToKafka } = require('common');

module.exports = async (request) => {
  const payload = request.body || request.kafkaMessage || request;
  const dataSource = payload.dataSource || payload;

  if (!dataSource || !dataSource.enrollmentId) {
    console.log('onRefundRequestCreated: no enrollmentId in payload, skipping');
    return { status: 200, message: 'Skipped - no enrollmentId' };
  }

  const refundRequest = dataSource;
  let enrollment = null;
  try {
    enrollment = await getEnrollmentById(refundRequest.enrollmentId);
  } catch (err) {
    console.log('onRefundRequestCreated: failed to fetch enrollment:', err.message);
    return { status: 200, message: 'Skipped - enrollment not found' };
  }

  if (!enrollment) {
    console.log('onRefundRequestCreated: enrollment not found for', refundRequest.enrollmentId);
    return { status: 200, message: 'Skipped - enrollment not found' };
  }

  let student = null;
  let tutorUser = null;
  let coursePack = null;

  try {
    const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } });
    if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source;

    const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } });
    const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null;

    if (profile && profile.tutorId) {
      const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } });
      if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source;
    }

    const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category'], size: 1 } });
    if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source;
  } catch (err) {
    console.log('onRefundRequestCreated: failed to fetch enrichment data from ES:', err.message);
  }

  const enrichedPayload = {
    id: refundRequest.id,
    enrollmentId: refundRequest.enrollmentId,
    status: refundRequest.status,
    reason: refundRequest.reason,
    requestedAt: refundRequest.requestedAt,
    processedAt: refundRequest.processedAt,
    totalAmount: enrollment.totalAmount,
    currency: enrollment.currency,
    student: student,
    tutorUser: tutorUser,
    coursePack: coursePack
  };

  try {
    const isAutoApproved = refundRequest.status === 'autoApproved' || refundRequest.status === 'autoapproved';
    const topic = isAutoApproved
      ? 'tutorhub-enrollmentmanagement-service-refund-processed'
      : 'tutorhub-enrollmentmanagement-service-refund-requested';
    await sendMessageToKafka(topic, enrichedPayload);
    console.log('onRefundRequestCreated: published to', topic);
  } catch (err) {
    console.log('onRefundRequestCreated: failed to publish enriched refund event:', err.message);
  }

  return { status: 200, message: 'Refund notification published' };
};
```










---

*This document was generated from the service architecture definition and should be kept in sync with implementation changes.*