

# Service Design Specification
**aifitapp-aicoach-service** documentation
**Version:** `1.0.116`

## Scope

This document provides a structured architectural overview of the `aiCoach` 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.



## `AiCoach` Service Settings

AI-powered fitness coaching service that generates personalized evidence-based training programs and nutrition plans, manages chatbowt interactions with full validation chains, handles dynamic program modifications via AI tool calls, tracks weaight measurements, enforces moderation and quotas, and provides admin endpoints for moderation history and usage analytics.a

### Service Overview

This service is configured to listen for HTTP requests on port `3001`, 
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 `aifitapp-aicoach-service`.

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

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



### Custom Environment Variables

The following custom variables are defined in the service configuration. They will be injected into the service’s runtime environment:

| Variable Name                               | Value                   |
| ------------------------------------------- | ----------------------- |
                       
| `OPENAI_API_KEY`                      | `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` |
                       
| `ADMIN_TOKEN`                      | `DEFAULT` |
                                   
                                 

### 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 `aifitapp-aicoach-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 |
|-------------|-------------|---------------|
| `chatMessage` | Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata. | accessProtected | 
| `coachConversation` | Chat conversation container per user for the AI fitness coach chatbot. | accessPrivate | 
| `mealPlan` | Stores AI-generated meal plans per user including calorie targets, macro distribution, and training/rest day differentiation. Created and modified exclusively by AI tool calls. | accessPrivate | 
| `moderationRecord` | Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review. | accessPrivate | 
| `planMeal` | Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls. | accessProtected | 
| `programExercise` | Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls. | accessProtected | 
| `quotaConfig` | System-wide message quota configuration. Admin-managed single record that defines message limits per period. | accessProtected | 
| `trainingProgram` | Stores AI-generated training programs per user including split type, deload schedule, cardio guidelines, and step targets. Created and modified exclusively by AI tool calls. | accessPrivate | 
| `userQuota` | Per-user message quota consumption tracking against the system-wide quota configuration. | accessPrivate | 
| `weightLog` | User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach. | accessPrivate | 
| `banAppeals` | No description | accessPrivate | 
| `additionalQuota` | No description | accessPrivate | 
| `sys_additionalQuotaPayment` | A payment storage object to store the payment life cyle of orders based on additionalQuota 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 | 




## chatMessage Data Object

### Object Overview
**Description:** Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata.

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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `content` | Text | Yes | Message content |
| `conversationId` | ID | Yes | Reference to the parent conversation |
| `flagged` | Boolean | No | True if the message was detected as off-topic or abusive |
| `role` | Enum | Yes | Message sender role |
| `toolCallData` | Text | No | JSON string of tool call metadata from AI processing |
* 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.

- **content**: 'text'
- **conversationId**: '00000000-0000-0000-0000-000000000000'
- **role**: "user"


### Constant Properties

`conversationId` `role`

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

`content` `flagged` `toolCallData`

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.

- **role**: [user, assistant, system]


 

 

### Elastic Search Indexing

`content` `conversationId` `flagged` `role`

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

`conversationId` `flagged`

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.






### Relation Properties

`conversationId`

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.

- **conversationId**: ID
Relation to `coachConversation`.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





### Filter Properties

`conversationId` `flagged` `role`

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.

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

- **flagged**: Boolean  has a filter named `flagged`

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





## coachConversation Data Object

### Object Overview
**Description:** Chat conversation container per user for the AI fitness coach chatbot.

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 |
|----------|------|----------|-------------|
| `status` | Enum | Yes | Conversation status |
| `userId` | ID | Yes | Reference to the user who owns this conversation |
* 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.

- **status**: active
- **userId**: '00000000-0000-0000-0000-000000000000'


### Constant Properties

`userId`

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

`status`

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**: [active, closed]


 

 

### Elastic Search Indexing

`status` `userId`

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

`status` `userId`

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.






### Relation Properties

`userId`

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.

- **userId**: 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

`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

`status` `userId`

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.

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

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





## mealPlan Data Object

### Object Overview
**Description:** Stores AI-generated meal plans per user including calorie targets, macro distribution, and training/rest day differentiation. Created and modified exclusively by AI tool calls.

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 |
|----------|------|----------|-------------|
| `carbGrams` | Float | Yes | Daily carbohydrate target in grams |
| `dailyCalorieTarget` | Integer | Yes | Daily calorie target in kcal |
| `fatGrams` | Float | Yes | Daily fat target in grams |
| `notes` | Text | No | Additional AI-generated nutritional guidance |
| `proteinGrams` | Float | Yes | Daily protein target in grams |
| `restDayCalories` | Integer | No | Calorie target on rest days |
| `restDayCarbGrams` | Float | No | Carb target on rest days |
| `status` | Enum | Yes | Meal plan status |
| `trainingDayCalories` | Integer | No | Calorie target on training days |
| `trainingDayCarbGrams` | Float | No | Carb target on training days |
| `userId` | ID | Yes | Reference to the user who owns this meal plan |
* 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.

- **carbGrams**: 0.0
- **dailyCalorieTarget**: 0
- **fatGrams**: 0.0
- **proteinGrams**: 0.0
- **status**: active
- **userId**: '00000000-0000-0000-0000-000000000000'


### Constant Properties

`userId`

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

`carbGrams` `dailyCalorieTarget` `fatGrams` `notes` `proteinGrams` `restDayCalories` `restDayCarbGrams` `status` `trainingDayCalories` `trainingDayCarbGrams`

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**: [active, archived]


 

 

### Elastic Search Indexing

`carbGrams` `dailyCalorieTarget` `fatGrams` `notes` `proteinGrams` `restDayCalories` `restDayCarbGrams` `status` `trainingDayCalories` `trainingDayCarbGrams` `userId`

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

`status` `userId`

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.






### Relation Properties

`userId`

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.

- **userId**: 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

`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

`status` `userId`

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.

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

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





## moderationRecord Data Object

### Object Overview
**Description:** Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review.

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:** Disabled — 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 |
|----------|------|----------|-------------|
| `action` | Enum | Yes | Moderation action taken |
| `offenseType` | String | Yes | Description of the violation |
| `reason` | Text | No | Detailed reason for the moderation action |
| `suspensionExpiresAt` | Date | No | When a temporary suspension ends (null for lifetime bans and reversals) |
| `userId` | ID | Yes | Reference to the user who was moderated |
| `content` | String | Yes |  |
* 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.

- **action**: "suspension24h"
- **offenseType**: 'default'
- **userId**: '00000000-0000-0000-0000-000000000000'
- **content**: 'default'


### Constant Properties

`offenseType` `reason` `suspensionExpiresAt` `userId`

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

`content`

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.

- **action**: [suspension24h, suspension1week, lifetimeBan, banReversal]


 

 

### Elastic Search Indexing

`action` `offenseType` `reason` `suspensionExpiresAt` `userId` `content`

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

`action` `suspensionExpiresAt` `userId` `content`

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.






### Relation Properties

`userId`

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.

- **userId**: 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





### Filter Properties

`action` `userId`

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.

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

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





## planMeal Data Object

### Object Overview
**Description:** Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls.

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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


**Display Label Property:** `mealLabel` — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `carbs` | Float | Yes | Carb grams for this meal |
| `fat` | Float | Yes | Fat grams for this meal |
| `foods` | Text | Yes | Food items and quantities description |
| `mealLabel` | String | Yes | Meal label (e.g. breakfast, lunch, dinner, snack) |
| `mealPlanId` | ID | Yes | Reference to the parent meal plan |
| `protein` | Float | Yes | Protein grams for this meal |
| `sortOrder` | Integer | Yes | Display sort order within the meal plan |
| `totalCalories` | Integer | Yes | Total calories for this meal |
* 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.

- **carbs**: 0.0
- **fat**: 0.0
- **foods**: 'text'
- **mealLabel**: 'default'
- **mealPlanId**: '00000000-0000-0000-0000-000000000000'
- **protein**: 0.0
- **totalCalories**: 0


### Constant Properties

`mealPlanId`

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

`carbs` `fat` `foods` `mealLabel` `protein` `sortOrder` `totalCalories`

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

`carbs` `fat` `foods` `mealLabel` `mealPlanId` `protein` `sortOrder` `totalCalories`

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

`mealPlanId`

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.






### Relation Properties

`mealPlanId`

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.

- **mealPlanId**: ID
Relation to `mealPlan`.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





### Filter Properties

`mealPlanId`

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.

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





## programExercise Data Object

### Object Overview
**Description:** Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls.

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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


**Display Label Property:** `exerciseName` — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `dayLabel` | String | Yes | Training day label (e.g. pushDay, upperA, legDay) |
| `exerciseName` | String | Yes | Name of the exercise |
| `movementType` | Enum | Yes | Movement type classification |
| `muscleGroup` | String | Yes | Target muscle group |
| `progressionRule` | Text | No | Progression instructions (e.g. double progression model) |
| `repMax` | Integer | Yes | Maximum rep target |
| `repMin` | Integer | Yes | Minimum rep target |
| `rirTarget` | Integer | Yes | Reps In Reserve target (0-3) |
| `sets` | Integer | Yes | Number of working sets |
| `sortOrder` | Integer | Yes | Display sort order within the training day |
| `trainingProgramId` | ID | Yes | Reference to the parent training program |
* 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.

- **dayLabel**: 'default'
- **exerciseName**: 'default'
- **movementType**: "lengthened"
- **muscleGroup**: 'default'
- **repMax**: 0
- **repMin**: 0
- **rirTarget**: 0
- **sets**: 0
- **trainingProgramId**: '00000000-0000-0000-0000-000000000000'


### Constant Properties

`trainingProgramId`

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

`dayLabel` `exerciseName` `movementType` `muscleGroup` `progressionRule` `repMax` `repMin` `rirTarget` `sets` `sortOrder`

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.

- **movementType**: [lengthened, shortened, compound]


 

 

### Elastic Search Indexing

`dayLabel` `exerciseName` `movementType` `muscleGroup` `progressionRule` `repMax` `repMin` `rirTarget` `sets` `sortOrder` `trainingProgramId`

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

`trainingProgramId`

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.






### Relation Properties

`trainingProgramId`

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.

- **trainingProgramId**: ID
Relation to `trainingProgram`.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





### Filter Properties

`dayLabel` `muscleGroup` `trainingProgramId`

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.

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

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

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





## quotaConfig Data Object

### Object Overview
**Description:** System-wide message quota configuration. Admin-managed single record that defines message limits per period.

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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules.








### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `quotaLimit` | Integer | Yes | Maximum messages allowed per period |
| `quotaPeriod` | Enum | Yes | Period over which the quota is measured |
* 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.

- **quotaLimit**: 0
- **quotaPeriod**: "daily"



### Auto Update Properties

`quotaLimit` `quotaPeriod`

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.

- **quotaPeriod**: [daily, weekly, monthly]


 

 

### Elastic Search Indexing

`quotaLimit` `quotaPeriod`

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.















## trainingProgram Data Object

### Object Overview
**Description:** Stores AI-generated training programs per user including split type, deload schedule, cardio guidelines, and step targets. Created and modified exclusively by AI tool calls.

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


**Display Label Property:** `splitType` — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `cardioDurationMinutes` | Integer | No | Recommended cardio duration in minutes |
| `cardioFrequencyPerWeek` | Integer | No | Recommended cardio sessions per week |
| `cardioType` | String | No | Type of cardio recommended (e.g. zone2) |
| `dailyStepTarget` | Integer | No | Daily step target for NEAT (7000-12000) |
| `deloadIntervalWeeks` | Integer | No | Weeks between deload periods, typically 6-8 |
| `notes` | Text | No | Additional AI-generated notes and guidance |
| `splitType` | String | Yes | Training split type (e.g. fullBody, upperLower, pushPullLegs) |
| `status` | Enum | Yes | Program status |
| `userId` | ID | Yes | Reference to the user who owns this training program |
* 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.

- **dailyStepTarget**: 10000
- **deloadIntervalWeeks**: 6
- **splitType**: 'default'
- **status**: active
- **userId**: '00000000-0000-0000-0000-000000000000'


### Constant Properties

`userId`

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

`cardioDurationMinutes` `cardioFrequencyPerWeek` `cardioType` `dailyStepTarget` `deloadIntervalWeeks` `notes` `splitType` `status`

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**: [active, archived]


 

 

### Elastic Search Indexing

`cardioDurationMinutes` `cardioFrequencyPerWeek` `cardioType` `dailyStepTarget` `deloadIntervalWeeks` `notes` `splitType` `status` `userId`

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

`status` `userId`

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.






### Relation Properties

`userId`

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.

- **userId**: 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

`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

`status` `userId`

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.

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

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





## userQuota Data Object

### Object Overview
**Description:** Per-user message quota consumption tracking against the system-wide quota configuration.

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

- **userQuotaUserPeriod**: [userId, periodStart] 
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**: `doUpdate`

The existing record will be updated with the new data.No error will be thrown.






### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `messageCount` | Integer | Yes | Number of messages consumed in the current period |
| `periodEnd` | Date | Yes | End of the current quota period |
| `periodStart` | Date | Yes | Start of the current quota period |
| `userId` | ID | Yes | Reference to the user whose quota is being tracked |
* 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.

- **periodEnd**: new Date()
- **periodStart**: new Date()
- **userId**: '00000000-0000-0000-0000-000000000000'


### Constant Properties

`userId`

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

`messageCount` `periodEnd` `periodStart`

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

`messageCount` `periodEnd` `periodStart` `userId`

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

`periodEnd` `periodStart` `userId`

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.






### Relation Properties

`userId`

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.

- **userId**: 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

`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`

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`





## weightLog Data Object

### Object Overview
**Description:** User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach.

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 |
|----------|------|----------|-------------|
| `measuredAt` | Date | Yes | Date and time of measurement |
| `userId` | ID | Yes | Reference to the user who recorded this weight |
| `weightKg` | Float | Yes | Body weight in kilograms |
* 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.

- **measuredAt**: new Date()
- **userId**: '00000000-0000-0000-0000-000000000000'
- **weightKg**: 0.0


### Constant Properties

`measuredAt` `userId` `weightKg`

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`.


 



 

 

### Elastic Search Indexing

`measuredAt` `userId` `weightKg`

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

`measuredAt` `userId`

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.






### Relation Properties

`userId`

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.

- **userId**: 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

`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.









## banAppeals Data Object

### Object Overview
**Description:** No description provided.

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 |
|----------|------|----------|-------------|
| `moderationRecordId` | ID | Yes | id of the mod record |
| `userId` | ID | Yes |  |
| `appealReason` | String | Yes |  |
| `status` | Enum | Yes |  |
* 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.

- **moderationRecordId**: '00000000-0000-0000-0000-000000000000'
- **userId**: '00000000-0000-0000-0000-000000000000'
- **appealReason**: 'default'
- **status**: "pending"



### Auto Update Properties

`moderationRecordId` `userId` `appealReason` `status`

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]


 

 

### Elastic Search Indexing

`moderationRecordId` `userId` `appealReason` `status`

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

`moderationRecordId` `userId` `appealReason` `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.






### Relation Properties

`moderationRecordId`

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.

- **moderationRecordId**: ID
Relation to `moderationRecord`.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

`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.









## additionalQuota Data Object

### Object Overview
**Description:** No description provided.

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.







### Stripe Integration

This data object is configured to integrate with Stripe for order management of `additionalQuota`. 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**: `additionalQuota`

- **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**: &#39;additionalquota addition&#39;
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**: status
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**: statusUpdatedAt
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**: userId
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 `&#39;pending&#39;` and will be set to `status`property.
`paymentResultCanceled` status will be mapped to a local value using `&#39;cancelled&#39;` and will be set to `status` property.
`paymentResultFailed` status will be mapped to a local value using `&#39;failed&#39;` and will be set to `status` property.
`paymentResultSuccess` status will be mapped to a local value using `&#39;active&#39;` and will be set to `status` 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 |
|----------|------|----------|-------------|
| `userId` | String | Yes |  |
| `additionalMessage` | Integer | Yes |  |
| `status` | Enum | Yes |  |
| `currency` | String | Yes |  |
| `pricePaid` | Integer | Yes |  |
| `statusUpdatedAt` | Date | No |  |
| `activatedAt` | Date | No |  |
| `cancelledAt` | Date | No |  |
| `periodEnd` | Date | No |  |
| `periodStart` | Date | No |  |
| `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.



### 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.

- **userId**: 'default'
- **additionalMessage**: 0
- **status**: pending
- **currency**: 'default'
- **pricePaid**: 0
- **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.

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



### Auto Update Properties

`userId` `additionalMessage` `status` `currency` `pricePaid` `statusUpdatedAt` `activatedAt` `cancelledAt` `periodEnd` `periodStart`

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, cancelled, failed, active, expired]

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


 

 

### Elastic Search Indexing

`userId` `additionalMessage` `status` `currency` `pricePaid` `statusUpdatedAt` `activatedAt` `cancelledAt` `periodEnd` `periodStart` `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

`userId` `additionalMessage` `status` `currency` `pricePaid` `statusUpdatedAt` `activatedAt` `cancelledAt` `periodEnd` `periodStart` `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.



### 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**: String 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`





## sys_additionalQuotaPayment Data Object

### Object Overview
**Description:** A payment storage object to store the payment life cyle of orders based on additionalQuota 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 additionalQuota 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



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

* [Create Chatmessage](/businessLogic/createchatmessage)

* [Create Coachconversation](/businessLogic/createcoachconversation)

* [Create Quotaconfig](/businessLogic/createquotaconfig)

* [Create Weightlog](/businessLogic/createweightlog)

* [Get Chatmessage](/businessLogic/getchatmessage)

* [Get Coachconversation](/businessLogic/getcoachconversation)

* [Get Mealplan](/businessLogic/getmealplan)

* [Get Moderationrecord](/businessLogic/getmoderationrecord)

* [Get Myquota](/businessLogic/getmyquota)

* [Get Planmeal](/businessLogic/getplanmeal)

* [Get Programexercise](/businessLogic/getprogramexercise)

* [Get Quotaconfig](/businessLogic/getquotaconfig)

* [Get Trainingprogram](/businessLogic/gettrainingprogram)

* [Get Userquota](/businessLogic/getuserquota)

* [Get Weightlog](/businessLogic/getweightlog)

* [List Chatmessages](/businessLogic/listchatmessages)

* [List Coachconversations](/businessLogic/listcoachconversations)

* [List Mealplans](/businessLogic/listmealplans)

* [List Moderationrecords](/businessLogic/listmoderationrecords)

* [List Planmeals](/businessLogic/listplanmeals)

* [List Programexercises](/businessLogic/listprogramexercises)

* [List Quotaconfigs](/businessLogic/listquotaconfigs)

* [List Trainingprograms](/businessLogic/listtrainingprograms)

* [List Userquotas](/businessLogic/listuserquotas)

* [List Weightlogs](/businessLogic/listweightlogs)

* [Update Quotaconfig](/businessLogic/updatequotaconfig)

* [Delete Moderationrecord](/businessLogic/deletemoderationrecord)

* [Do Deletemealplan](/businessLogic/deletemealplan)

* [Do Deletetrainingprogram](/businessLogic/deletetrainingprogram)

* [Update Moderationrecord](/businessLogic/updatemoderationrecord)

* [Do Listmymoderationrecords](/businessLogic/listmymoderationrecords)

* [List Banappeals](/businessLogic/listbanappeals)

* [Create Banappeal](/businessLogic/createbanappeal)

* [Update Banappeal](/businessLogic/updatebanappeal)

* [Create Additionalquota](/businessLogic/createadditionalquota)

* [Get Myadditionalquota](/businessLogic/getmyadditionalquota)

* [Get Additionalquotapayment](/businessLogic/getadditionalquotapayment)

* [List Additionalquotapayments](/businessLogic/listadditionalquotapayments)

* [Create Additionalquotapayment](/businessLogic/createadditionalquotapayment)

* [Update Additionalquotapayment](/businessLogic/updateadditionalquotapayment)

* [Delete Additionalquotapayment](/businessLogic/deleteadditionalquotapayment)

* [Get Additionalquotapaymentbyorderid](/businessLogic/getadditionalquotapaymentbyorderid)

* [Get Additionalquotapaymentbypaymentid](/businessLogic/getadditionalquotapaymentbypaymentid)

* [Start Additionalquotapayment](/businessLogic/startadditionalquotapayment)

* [Refresh Additionalquotapayment](/businessLogic/refreshadditionalquotapayment)

* [Callback Additionalquotapayment](/businessLogic/callbackadditionalquotapayment)

* [Get Paymentcustomerbyuserid](/businessLogic/getpaymentcustomerbyuserid)

* [List Paymentcustomers](/businessLogic/listpaymentcustomers)

* [List Paymentcustomermethods](/businessLogic/listpaymentcustomermethods)















## Edge Controllers


### getUsageAnalyticsFn

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

**REST Settings:**
- **Path**: `/admin/usage-analytics`
- **Method**: 

---

### reverseBanFn

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

**REST Settings:**
- **Path**: `/admin/reverse-ban`
- **Method**: 

---





## Service Library


### Functions

#### checkBanStatusFn.js
```js
module.exports = async function checkBanStatusFn(userId) {
  const { getModerationRecordListByQuery } = require('dbLayer');
  try {
    const records = await getModerationRecordListByQuery({ userId });
    if (!records || records.length === 0) return { isBanned: false };
    /* Check lifetime ban - find most recent ban/reversal action */
    const banRelated = records.filter(r => r.action === 'lifetimeBan' || r.action === 'banReversal');
    if (banRelated.length > 0) {
      banRelated.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
      if (banRelated[0].action === 'lifetimeBan') {
        return { isBanned: true, reason: 'Lifetime ban', banType: 'lifetimeBan' };
      }
    }
    /* Check active suspension */
    const now = new Date();
    const activeSuspension = records.find(r =>
      (r.action === 'suspension24h' || r.action === 'suspension1week') &&
      r.suspensionExpiresAt && new Date(r.suspensionExpiresAt) > now
    );
    if (activeSuspension) {
      return { isBanned: true, reason: 'Chat suspended until ' + activeSuspension.suspensionExpiresAt, banType: activeSuspension.action };
    }
    return { isBanned: false };
  } catch (err) {
    console.error('checkBanStatusFn error:', err);
    return { isBanned: false };
  }
};
```

#### checkQuotaFn.js
```js
const { Op } = require("sequelize");
module.exports = async function checkQuotaFn(userId) {
  const { getQuotaConfigListByQuery, getUserQuotaByQuery, createUserQuota, updateUserQuotaById,getAdditionalQuotaByQuery } = require('dbLayer');
  try {
    /* Get system quota config */
    const configs = await getQuotaConfigListByQuery({});
    if (!configs || configs.length === 0) {
      /* No quota config set - allow by default */
      return { available: true, remaining: -1, noConfig: true };
    }
    const config = configs[0];
    const now = new Date();
    /* Calculate period boundaries */
    let periodStart, periodEnd;
    if (config.quotaPeriod === 'daily') {
      periodStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      periodEnd = new Date(periodStart.getTime() + 24 * 60 * 60 * 1000);
    } else if (config.quotaPeriod === 'weekly') {
      const day = now.getDay();
      periodStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day);
      periodEnd = new Date(periodStart.getTime() + 7 * 24 * 60 * 60 * 1000);
    } else {
      periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
      periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 1);
    }
    /* Get or create user quota */
let existQuota = await getUserQuotaByQuery({
  userId,
  periodStart: { [Op.lte]: now },
  periodEnd: { [Op.gt]: now },
});
    let quota;

// 2. if none → create new (new day)
if (!existQuota) {
  quota = await createUserQuota({
    userId,
    messageCount: 0,
    periodStart,
    periodEnd,
  });
}
    else{
      quota=existQuota
    }
    const additionalQuota=await getAdditionalQuotaByQuery({
  userId,
  status:'active',
  periodStart: { [Op.lte]: now },
  periodEnd: { [Op.gt]: now },
})

// 3. compute remaining
const remaining = (additionalQuota?.additionalMessage??0) +config.quotaLimit - (quota?.messageCount ?? 0);

return {
  available: remaining > 0,
  remaining,
  quotaId: quota.id,
  limit: config.quotaLimit,
  existQuota,
  additionalQuota
};
  } catch (err) {
    console.error('checkQuotaFn error:', err);
    return { available: true, remaining: -1 };
  }
};
```

#### incrementQuotaFn.js
```js
const { Op } = require("sequelize");
module.exports = async function incrementQuotaFn(userId, context) {
  const { getUserQuotaByQuery, createUserQuota, updateUserQuotaById } = require('dbLayer');

  try {
    const now = new Date();

    // Define DAILY boundaries (midnight → midnight)
    const periodStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const periodEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

    let quota = await getUserQuotaByQuery({
      userId,
  periodStart: { [Op.lte]: now },
  periodEnd: { [Op.gt]: now },
    });

    if (!quota) {
      quota = await createUserQuota({
        userId,
        messageCount: 1,
        periodStart,
        periodEnd,
      }, context);

      return;
    }

    await updateUserQuotaById(
      quota.id,
      { messageCount: (quota.messageCount || 0) + 1 },
      context
    );

  } catch (err) {
    console.error('incrementQuotaFn error:', err);
  }
};
```

#### applyPenaltyFn.js
```js
module.exports = async function applyPenaltyFn(userId, reason, context,content) {
  const { getModerationRecordListByQuery, createModerationRecord } = require('dbLayer');
  const COMMON = require('common');
  try {
    /* Count previous offenses (excluding reversals) */
    const records = await getModerationRecordListByQuery({ userId });
    const offenses = records.filter(r => r.action !== 'banReversal');
    const offenseCount = offenses.length;
    let action, suspensionExpiresAt = null;
    const now = new Date();
    if (offenseCount === 0) {
      /* First offense: 24h suspension */
      action = 'suspension24h';
      suspensionExpiresAt = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    } else if (offenseCount === 1) {
      /* Second offense: 1 week suspension */
      action = 'suspension1week';
      suspensionExpiresAt = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    } else {
      /* Third+ offense: lifetime ban */
      action = 'lifetimeBan';
    }
    await createModerationRecord({
      userId,
      offenseType: reason || 'Content policy violation',
      action,
      reason: 'Automated progressive penalty - offense #' + (offenseCount + 1),
      suspensionExpiresAt,
      content
    }, context);
    /* If lifetime ban, deactivate user in auth service */
    if (action === 'lifetimeBan') {
      try {
        await COMMON.sendRestRequest(
          process.env.AUTH_SERVICE_URL ? process.env.AUTH_SERVICE_URL + '/m2m/user/updateById' : 'http://auth:3000/m2m/user/updateById',
          'PUT',
          { id: userId, dataClause: { isActive: false } },
          { 'x-service-token': process.env.M2M_TOKEN || '' }
        );
      } catch (m2mErr) {
        console.error('Failed to deactivate user in auth service:', m2mErr);
      }
    }
    return { action, suspensionExpiresAt };
  } catch (err) {
    console.error('applyPenaltyFn error:', err);
    throw err;
  }
};
```

#### flagMessageContent.js
```js
module.exports = async function flagMessageContent(messageContent) {
  const OpenAI = require('openai');
  const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-4.1',
      messages: [
        {
          role: 'system',
          content: 'You are a content moderation system for a fitness and nutrition coaching platform.Youll be given full chat history of messages and the last message as users input. Youll analyze the last message but consider if its within the context or not. Analyze the user message and determine if it is: 1) Off-topic (not related to fitness, nutrition, health, exercise, diet, body composition, or wellness), 2) Trolling or abusive, 3) Attempting to misuse the AI for non-fitness purposes (e.g., asking to write code, generate non-fitness content). Respond with JSON: {"flagged": boolean, "reason": string}. Only flag clearly off-topic or abusive content. Fitness-adjacent topics like sleep, stress, supplements, motivation are NOT off-topic.It may look offtopic but there may be typo or some misunderstanding may happen time to time consider the last 3 messages by user to identify a need for ban. If user usually insists on trolling and of topic then apply the ban dont directly ban a user for a single misuse a typo and total trolling should be exact.'
        },
        ...messageContent
      ],
      response_format: { type: 'json_object' },
      temperature: 0.1,
      max_tokens: 200
    });
    const result = JSON.parse(response.choices[0].message.content);
    return { flagged: result.flagged === true, reason: result.reason || '',content:messageContent[messageContent.length - 1]?.content||'' };
  } catch (err) {
    console.error('flagMessageContent error:', err);
    return { flagged: false, reason: '' };
  }
};
```

#### getSystemPrompt.js
```js
module.exports = function getSystemPrompt(userProfile, trainingProgram, exercises, mealPlan, meals, weightLogs) {
  let prompt = 'You are an evidence-based AI fitness coach. You provide personalized training programs and nutrition plans based on scientific principles.\n\n';
  prompt += '## CORE RULES\n';
  prompt += '- NEVER recommend steroids, PEDs, extreme dieting (<1000kcal), or unsafe loads.\n';
  prompt += '- Always use Mifflin-St Jeor for BMR: Males: 10*kg + 6.25*cm - 5*age + 5. Females: 10*kg + 6.25*cm - 5*age - 161.\n';
  prompt += '- TDEE multipliers: Sedentary=1.2, Light=1.375, Moderate=1.55, Heavy=1.725, Athlete=1.9.\n';
  prompt += '- Cutting deficit: -300 to -700 kcal (-10-25% TDEE). Bulking surplus: +200 to +400 kcal (+5-10% TDEE).\n';
  prompt += '- Protein: 1.6-2.2g/kg (up to 2.6g/kg aggressive cut). Fat: min 0.6-1.0g/kg (never <15-20% calories). Remaining = carbs.\n';
  prompt += '- Higher carbs on training days, lower on rest days.\n';
  prompt += '- Training splits: 3 days=full body, 4 days=upper/lower, 5-6 days=PPL.\n';
  prompt += '- Each muscle: 1 lengthened + 1 shortened exercise min. Compounds: 6-12 reps, 1-3 RIR. Isolation: 8-15 reps, 0-2 RIR.\n';
  prompt += '- Volume: maintenance ~6 sets, growth 10-20, specialization 20-25 sets/muscle/week.\n';
  prompt += '- Double progression: hit top rep range all sets -> increase weight.\n';
  prompt += '- Deload every 6-8 weeks: volume -40-50%, intensity -10%.\n';
  prompt += '- Cardio: Zone 2 (60-70% HRmax), 20-40 min, 3-5x/week when goal supports it.\n';
  prompt += '- Daily steps: 7,000-12,000 for NEAT.\n';
  prompt += '- Weight tracking: 3-4 mornings/week, after waking/bathroom/before food. Use weekly averages only.\n';
  prompt += '- Cutting target: 0.5-1% BW/week. Bulking target: 0.25-0.5% BW/week.\n';
  prompt += '- If cutting loss <0.3%/wk: reduce 150-200 kcal. If >1.5%/wk: increase slightly.\n';
  prompt += '- If bulking gain <0.2%/wk: add 150 kcal. If >0.75%/wk: reduce.\n';
  prompt += '- Water retention: early cut drops mostly water (1g glycogen=3g water). Post-cheat 1-3kg is temporary. Wait 2-3 days.\n';
  prompt += '- Recovery check-ins weekly: sleep, soreness, performance. Reduce volume if poor recovery signals.\n';
  prompt += '- Regional food suggestions based on user country. Respect dietary restrictions.\n\n';
  if (userProfile) {
    prompt += '## USER PROFILE\n';
    prompt += 'Name: ' + (userProfile.fullname || 'N/A') + '\n';
    prompt += 'Sex: ' + (userProfile.sex || 'N/A') + ', Height: ' + (userProfile.height || 'N/A') + 'cm, Weight: ' + (userProfile.weight || 'N/A') + 'kg\n';
    prompt += 'DOB: ' + (userProfile.dateOfBirth || 'N/A') + ', Activity: ' + (userProfile.activityLevel || 'N/A') + '\n';
    prompt += 'Experience: ' + (userProfile.trainingExperience || 'N/A') + ', Training days/wk: ' + (userProfile.weeklyTrainingDays || 'N/A') + '\n';
    prompt += 'Goal: ' + (userProfile.fitnessGoal || 'N/A') + ', Country: ' + (userProfile.country || 'N/A') + '\n';
    prompt += 'Dietary restrictions: ' + (userProfile.dietaryRestrictions || 'None') + '\n';
    prompt += 'Equipment: ' + (userProfile.availableEquipment || 'N/A') + '\n\n';
  }
  if (trainingProgram) {
    prompt += '## CURRENT TRAINING PROGRAM\n';
    prompt += 'Split: ' + trainingProgram.splitType + ', Deload every ' + trainingProgram.deloadIntervalWeeks + ' weeks\n'+'id:'+trainingProgram.id;
    if (exercises && exercises.length > 0) {
      prompt += 'Exercises:\n';
      exercises.forEach(e => {
        prompt += '-id: '+e.id+'\n- ' + e.dayLabel + ': ' + e.exerciseName + ' (' + e.muscleGroup + ') ' + e.sets + 'x' + e.repMin + '-' + e.repMax + ' RIR ' + e.rirTarget + '\n';
      });
    }
    prompt += '\n';
  }
  if (mealPlan) {
    prompt += '## CURRENT MEAL PLAN\n';
    prompt += 'Calories: ' + mealPlan.dailyCalorieTarget + ' kcal, P: ' + mealPlan.proteinGrams + 'g, F: ' + mealPlan.fatGrams + 'g, C: ' + mealPlan.carbGrams + 'g\n'+'id:'+mealPlan.id;
    if (meals && meals.length > 0) {
      meals.forEach(m => { prompt += '-id:'+m.id+'\n- ' + m.mealLabel + ': ' + m.foods + ' (' + m.totalCalories + ' kcal)\n'; });
    }
    prompt += '\n';
  }
  if (weightLogs && weightLogs.length > 0) {
    prompt += '## RECENT WEIGHT DATA\n';
    weightLogs.slice(0, 14).forEach(w => { prompt += w.measuredAt + ': ' + w.weightKg + 'kg\n'; });
    prompt += '\n';
  }
  prompt += '## TOOL USAGE\n';
  prompt += 'To use the tools more efficently exercises are saved under training programs so create a training program then create the exercises. If any new training program is created then the old one gets archived so try to updateTrainingProgram if user wants small alterations. If user wants to abandon the training approach then you can create a new one. A new training program will come with 0 exercises when created. For meals same approach here createMealPlan creates a new meal plan with macros and caloric goals logged no meals are should be entered yet. you can add/update meals by addMeal/updateMeal tools. If user just make changes you can updateMealPlan for caloric changes. If user really wants a total different approach then create a new meal plan by createMealPlan tool. creating a new meal plan also comes with 0 meals connected to it so itll need a new meals list. for inner updates such as exercises and plans you can also update the main structure if changes are effective to approach. for example a new lunch changes the approx caloric goal of that meal plan then we can also update the meal plan. Dont forget to make big changes first create the main object createTrainingProgram then add exercises. For meals createMeal plan first then addMeals. Also while creating the main objects dont always create them each step add when necessary. If the operating fails on this the newly added exercises or meals wont be seen under current plan. Consider the active plan if exists first. '
  prompt += 'Use the provided tools to create/update training programs, exercises, meal plans, and meals when the user requests changes. Always use tools for data modifications. As you normally do you return them in text responses too keep that but main ideas are always must be handled via tools meals exercises training program and calories.\n';
  prompt += 'When reporting non-adherence, calculate realistic timeline impact and communicate constructively. If for example training program should be captured first before exercises there is a dependency be clear and tell them if they are trying to get dependent outcome first. exercise lists needs training program ids and plan meal that logs the meals itself need meal planId. always capture these with tools\n';
  return prompt;
};
```

#### getToolDefinitions.js
```js
module.exports = function getToolDefinitions() {
  return [
    { type: 'function', function: { name: 'createTrainingProgram', description: 'Create a new training program for the user. Archives any existing active program first.', parameters: { type: 'object', properties: { splitType: { type: 'string' }, deloadIntervalWeeks: { type: 'integer' }, cardioType: { type: 'string' }, cardioDurationMinutes: { type: 'integer' }, cardioFrequencyPerWeek: { type: 'integer' }, dailyStepTarget: { type: 'integer' }, notes: { type: 'string' } }, required: ['splitType'] } } },
    { type: 'function', function: { name: 'addExercise', description: 'Add an exercise to the current training program.', parameters: { type: 'object', properties: { dayLabel: { type: 'string' }, exerciseName: { type: 'string' }, muscleGroup: { type: 'string' }, movementType: { type: 'string', enum: ['lengthened', 'shortened', 'compound'] }, sets: { type: 'integer' }, repMin: { type: 'integer' }, repMax: { type: 'integer' }, rirTarget: { type: 'integer' }, progressionRule: { type: 'string' }, sortOrder: { type: 'integer' } }, required: ['dayLabel', 'exerciseName', 'muscleGroup', 'movementType', 'sets', 'repMin', 'repMax', 'rirTarget'] } } },
    { type: 'function', function: { name: 'updateExercise', description: 'Update an existing exercise by its ID.', parameters: { type: 'object', properties: { exerciseId: { type: 'string' }, exerciseName: { type: 'string' }, sets: { type: 'integer' }, repMin: { type: 'integer' }, repMax: { type: 'integer' }, rirTarget: { type: 'integer' }, progressionRule: { type: 'string' } }, required: ['exerciseId'] } } },
    { type: 'function', function: { name: 'removeExercise', description: 'Remove an exercise by its ID.', parameters: { type: 'object', properties: { exerciseId: { type: 'string' } }, required: ['exerciseId'] } } },
    { type: 'function', function: { name: 'createMealPlan', description: 'Create a new meal plan for the user. Archives any existing active plan first.', parameters: { type: 'object', properties: { dailyCalorieTarget: { type: 'integer' }, proteinGrams: { type: 'number' }, fatGrams: { type: 'number' }, carbGrams: { type: 'number' }, trainingDayCalories: { type: 'integer' }, restDayCalories: { type: 'integer' }, trainingDayCarbGrams: { type: 'number' }, restDayCarbGrams: { type: 'number' }, notes: { type: 'string' } }, required: ['dailyCalorieTarget', 'proteinGrams', 'fatGrams', 'carbGrams'] } } },
    { type: 'function', function: { name: 'addMeal', description: 'Add a meal to the current meal plan. while adding always mention the individual grams for each food while listing the foods. weights are always should be raw where people can easily weigh their foods. Or quantity for simple things such as nuts almonds eggs etc', parameters: { type: 'object', properties: { mealLabel: { type: 'string' }, foods: { type: 'string' }, totalCalories: { type: 'integer' }, protein: { type: 'number' }, fat: { type: 'number' }, carbs: { type: 'number' }, sortOrder: { type: 'integer' } }, required: ['mealLabel', 'foods', 'totalCalories', 'protein', 'fat', 'carbs'] } } },
    { type: 'function', function: { name: 'updateMealPlan', description: 'Update the current meal plan macros/calories.', parameters: { type: 'object', properties: { dailyCalorieTarget: { type: 'integer' }, proteinGrams: { type: 'number' }, fatGrams: { type: 'number' }, carbGrams: { type: 'number' }, trainingDayCalories: { type: 'integer' }, restDayCalories: { type: 'integer' }, trainingDayCarbGrams: { type: 'number' }, restDayCarbGrams: { type: 'number' }, notes: { type: 'string' } }, required: [] } } },
    { type: 'function', function: { name: 'updateMeal', description: 'Update an existing meal by its ID.', parameters: { type: 'object', properties: { mealId: { type: 'string' }, mealLabel: { type: 'string' }, foods: { type: 'string' }, totalCalories: { type: 'integer' }, protein: { type: 'number' }, fat: { type: 'number' }, carbs: { type: 'number' } }, required: ['mealId'] } } },
    { type: 'function', function: { name: 'removeMeal', description: 'Remove a meal by its ID.', parameters: { type: 'object', properties: { mealId: { type: 'string' } }, required: ['mealId'] } } },
    { type: 'function', function: { name: 'updateTrainingProgram', description: 'Update the current training program settings.', parameters: { type: 'object', properties: { deloadIntervalWeeks: { type: 'integer' }, cardioType: { type: 'string' }, cardioDurationMinutes: { type: 'integer' }, cardioFrequencyPerWeek: { type: 'integer' }, dailyStepTarget: { type: 'integer' }, notes: { type: 'string' } }, required: [] } } }
  ];
};
```

#### executeToolCall.js
```js
module.exports = async function executeToolCall(toolCall, userId, currentProgram, currentMealPlan, context) {
  const { createTrainingProgram, updateTrainingProgramById, updateTrainingProgramByQuery, createProgramExercise, updateProgramExerciseById, deleteProgramExerciseById, createMealPlan, updateMealPlanById, updateMealPlanByQuery, createPlanMeal, updatePlanMealById, deletePlanMealById, getTrainingProgramByQuery, getMealPlanByQuery } = require('dbLayer');
  const fnName = toolCall.function.name;
  const args = JSON.parse(toolCall.function.arguments);
  try {
    if (fnName === 'createTrainingProgram') {
      /* Archive existing active program */
      if (currentProgram) {
        await updateTrainingProgramById(currentProgram.id, { status: 'archived' }, context);
      }
      const prog = await createTrainingProgram({ userId, status: 'active', ...args }, context);
      return { success: true, programId: prog.id };
    }
    if (fnName === 'addExercise') {
      const prog =  await getTrainingProgramByQuery({ userId, status: 'active' });
      if (!prog) return { success: false, error: 'No active training program' };
      const ex = await createProgramExercise({ trainingProgramId: prog.id, ...args, sortOrder: args.sortOrder || 0 }, context);
      return { success: true, exerciseId: ex.id };
    }
    if (fnName === 'updateExercise') {
      const { exerciseId, ...data } = args;
      await updateProgramExerciseById(exerciseId, data, context);
      return { success: true };
    }
    if (fnName === 'removeExercise') {
      await deleteProgramExerciseById(args.exerciseId, context);
      return { success: true };
    }
    if (fnName === 'createMealPlan') {
      if (currentMealPlan) {
        await updateMealPlanById(currentMealPlan.id, { status: 'archived' }, context);
      }
      const plan = await createMealPlan({ userId, status: 'active', ...args }, context);
      return { success: true, mealPlanId: plan.id };
    }
    if (fnName === 'addMeal') {
      const plan =  await getMealPlanByQuery({ userId, status: 'active' });
      if (!plan) return { success: false, error: 'No active meal plan' };
      const meal = await createPlanMeal({ mealPlanId: plan.id, ...args, sortOrder: args.sortOrder || 0 }, context);
      return { success: true, mealId: meal.id };
    }
    if (fnName === 'updateMealPlan') {
      const plan = currentMealPlan || await getMealPlanByQuery({ userId, status: 'active' });
      if (!plan) return { success: false, error: 'No active meal plan' };
      await updateMealPlanById(plan.id, args, context);
      return { success: true };
    }
    if (fnName === 'updateMeal') {
      const { mealId, ...data } = args;
      await updatePlanMealById(mealId, data, context);
      return { success: true };
    }
    if (fnName === 'removeMeal') {
      await deletePlanMealById(args.mealId, context);
      return { success: true };
    }
    if (fnName === 'updateTrainingProgram') {
      const prog = currentProgram || await getTrainingProgramByQuery({ userId, status: 'active' });
      if (!prog) return { success: false, error: 'No active training program' };
      await updateTrainingProgramById(prog.id, args, context);
      return { success: true };
    }
    return { success: false, error: 'Unknown tool: ' + fnName };
  } catch (err) {
    console.error('executeToolCall error:', fnName, err);
    return { success: false, error: err.message };
  }
};
```

#### processMessagePipeline.js
```js
module.exports = async function processMessagePipeline(context) {
  const { createChatMessage, updateChatMessageById, getChatMessageListByQuery, getTrainingProgramByQuery, getMealPlanByQuery, getProgramExerciseListByQuery, getPlanMealListByQuery, getWeightLogListByQuery } = require('dbLayer');
  const { fetchRemoteObjectByMQuery } = require('serviceCommon');
  const OpenAI = require('openai');
  const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
  const chatMsg = context.chatMessage;
  const conversationId = chatMsg.conversationId;
  const userId = context.session.userId;
  const messageContent = chatMsg.content;
  /* Step 1: Content flagging */
   const recentMessages = await getChatMessageListByQuery({ conversationId });
    const flagCheckHistory = recentMessages.filter(m => !m.flagged).sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)).slice(-20);
    const flagCheckMessages=[]
  for (const msg of flagCheckHistory) {
     flagCheckMessages.push({ role: msg.role === 'user' ? 'user' : msg.role === 'assistant' ? 'assistant' : 'system', content: msg.content }); 
  }
  const flagResult = await LIB.flagMessageContent(flagCheckMessages);
  if (flagResult.flagged) {
    await updateChatMessageById(chatMsg.id, { flagged: true }, context);
    const penalty = await LIB.applyPenaltyFn(userId, flagResult.reason, context,flagResult.content);
    await LIB.incrementQuotaFn(userId, context);
    return { flagged: true, message: 'Your message was flagged as off-topic or inappropriate. ' + (penalty.action === 'suspension24h' ? 'You are suspended from chat for 24 hours.' : penalty.action === 'suspension1week' ? 'You are suspended from chat for 1 week.' : penalty.action === 'lifetimeBan' ? 'Your account has been permanently banned.' : ''), penalty: penalty.action };
  }
  /* Step 2: Load conversation history */
  const history = recentMessages.filter(m => !m.flagged).sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)).slice(-20);
  /* Step 3: Load user profile from auth */
  const userProfile = await fetchRemoteObjectByMQuery('User', { id: userId });
  /* Step 4: Load current programs */
  const trainingProgram = await getTrainingProgramByQuery({ userId, status: 'active' });
  let exercises = [];
  if (trainingProgram) { exercises = await getProgramExerciseListByQuery({ trainingProgramId: trainingProgram.id }); }
  const mealPlan = await getMealPlanByQuery({ userId, status: 'active' });
  let meals = [];
  if (mealPlan) { meals = await getPlanMealListByQuery({ mealPlanId: mealPlan.id }); }
  /* Load recent weight logs */
  const weightLogs = await getWeightLogListByQuery({ userId });
  const sortedWeights = weightLogs.sort((a, b) => new Date(b.measuredAt) - new Date(a.measuredAt)).slice(0, 14);
  /* Step 5: Build messages */
  const systemPrompt = LIB.getSystemPrompt(userProfile, trainingProgram, exercises, mealPlan, meals, sortedWeights);
  const messages = [{ role: 'system', content: systemPrompt }];
  for (const msg of history) {
    if (msg.id !== chatMsg.id) { messages.push({ role: msg.role === 'user' ? 'user' : msg.role === 'assistant' ? 'assistant' : 'system', content: msg.content }); }
  }
  messages.push({ role: 'user', content: messageContent });
  /* Step 6: Call OpenAI with tools */
  const tools = LIB.getToolDefinitions();
  let response = await openai.chat.completions.create({ model: 'gpt-4.1', messages, tools, temperature: 0.7, max_tokens: 10000 });
  let assistantMsg = response.choices[0].message;
  let toolCallsExecuted = [];
  /* Step 7: Handle tool call loop */
  while (assistantMsg.tool_calls && assistantMsg.tool_calls.length > 0) {
    messages.push(assistantMsg);
    for (const tc of assistantMsg.tool_calls) {
      const result = await LIB.executeToolCall(tc, userId, trainingProgram, mealPlan, context);
      toolCallsExecuted.push({ name: tc.function.name, result });
      messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) });
    }
    response = await openai.chat.completions.create({ model: 'gpt-4.1', messages, tools, temperature: 0.7, max_tokens: 10000 });
    assistantMsg = response.choices[0].message;
  }
  const aiContent = assistantMsg.content || '';
  /* Step 8: Save AI response */
  await createChatMessage({ conversationId, role: 'assistant', content: aiContent, flagged: false, toolCallData: toolCallsExecuted.length > 0 ? JSON.stringify(toolCallsExecuted) : null }, context);
  /* Step 9: Increment quota */
  await LIB.incrementQuotaFn(userId, context);
  return { flagged: false, message: aiContent, toolCalls: toolCallsExecuted };
};
```

#### fetchAdditionalQuota.js
```js
const { Op } = require("sequelize");
module.exports = async function fetchAdditionalQuota(userId) {
  const { getAdditionalQuotaByQuery } = require('dbLayer');
  try {
   
    const additionalQuota=await getAdditionalQuotaByQuery({
  userId,
  status:'active',
  periodStart: { [Op.lte]: now },
  periodEnd: { [Op.gt]: now },
})

// 3. compute remaining


return additionalQuota
  
  } catch (err) {
    console.error('fetchAdditionalQuota error:', err);
    return {}
      ;
  }
};
```

#### streamChatCompletion.js
```js
module.exports = async function* streamChatCompletion(context) {
  const { createChatMessage, updateChatMessageById, getChatMessageListByQuery, getTrainingProgramByQuery, getMealPlanByQuery, getProgramExerciseListByQuery, getPlanMealListByQuery, getWeightLogListByQuery } = require('dbLayer');
  const { fetchRemoteObjectByMQuery } = require('serviceCommon');
  const OpenAI = require('openai');
  const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
  
  const conversationId = context.conversationId;
  const userId = context.session.userId;
  const messageContent = context.content;
  
  /* Step 1: Content flagging with recent messages */
  const recentMessages = await getChatMessageListByQuery({ conversationId });
  const flagCheckHistory = recentMessages.filter(m => !m.flagged).sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)).slice(-20);
  const flagCheckMessages = [];
  for (const msg of flagCheckHistory) {
    flagCheckMessages.push({ role: msg.role === 'user' ? 'user' : msg.role === 'assistant' ? 'assistant' : 'system', content: msg.content });
  }
  
  const flagResult = await LIB.flagMessageContent(flagCheckMessages);
  if (flagResult.flagged) {
    yield { type: 'flagged', flagged: true, reason: flagResult.reason };
    return;
  }
  
  /* Step 2: Load conversation history */
  const history = recentMessages.filter(m => !m.flagged).sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)).slice(-20);
  
  /* Step 3: Load user profile from auth */
  const userProfile = await fetchRemoteObjectByMQuery('User', { id: userId });
  
  /* Step 4: Load current programs */
  const trainingProgram = await getTrainingProgramByQuery({ userId, status: 'active' });
  let exercises = [];
  if (trainingProgram) { 
    exercises = await getProgramExerciseListByQuery({ trainingProgramId: trainingProgram.id }); 
  }
  
  const mealPlan = await getMealPlanByQuery({ userId, status: 'active' });
  let meals = [];
  if (mealPlan) { 
    meals = await getPlanMealListByQuery({ mealPlanId: mealPlan.id }); 
  }
  
  /* Load recent weight logs */
  const weightLogs = await getWeightLogListByQuery({ userId });
  const sortedWeights = weightLogs.sort((a, b) => new Date(b.measuredAt) - new Date(a.measuredAt)).slice(0, 14);
  
  /* Step 5: Build messages */
  const systemPrompt = LIB.getSystemPrompt(userProfile, trainingProgram, exercises, mealPlan, meals, sortedWeights);
  const messages = [{ role: 'system', content: systemPrompt }];
  for (const msg of history) {
    messages.push({ role: msg.role === 'user' ? 'user' : msg.role === 'assistant' ? 'assistant' : 'system', content: msg.content });
  }
  messages.push({ role: 'user', content: messageContent });
  
  /* Step 6: Call OpenAI with streaming */
  const tools = LIB.getToolDefinitions();
  const stream = await openai.chat.completions.create({ 
    model: 'gpt-4.1', 
    messages, 
    tools, 
    temperature: 0.7, 
    max_tokens: 10000,
    stream: true 
  });
  
  let fullContent = '';
  let toolCallsBuffer = [];
  
  /* Stream tokens */
  for await (const chunk of stream) {
    const delta = chunk.choices[0]?.delta;
    
    if (delta?.content) {
      fullContent += delta.content;
      yield { type: 'token', token: delta.content };
    }
    
    if (delta?.tool_calls) {
      for (const tc of delta.tool_calls) {
        if (tc.id) {
          toolCallsBuffer.push({ id: tc.id, index: tc.index, function: { name: tc.function?.name || '', arguments: tc.function?.arguments || '' } });
        } else if (tc.function?.arguments) {
          const existing = toolCallsBuffer.find(t => t.index === tc.index);
          if (existing) {
            existing.function.arguments += tc.function.arguments;
          }
        }
      }
    }
  }
  
  /* Handle tool calls if any */
  if (toolCallsBuffer.length > 0) {
    yield { type: 'tool_calls', toolCalls: toolCallsBuffer };
    
    /* Execute tool calls */
    const toolResults = [];
    for (const tc of toolCallsBuffer) {
      const result = await LIB.executeToolCall(
        { id: tc.id, function: { name: tc.function.name, arguments: tc.function.arguments }, type: 'function' },
        userId,
        trainingProgram,
        mealPlan,
        context
      );
      toolResults.push({ tool_call_id: tc.id, role: 'tool', content: JSON.stringify(result) });
      yield { type: 'tool_result', name: tc.function.name, result };
    }
    
    /* Continue conversation with tool results */
    messages.push({ role: 'assistant', content: fullContent, tool_calls: toolCallsBuffer.map(tc => ({ id: tc.id, type: 'function', function: tc.function })) });
    for (const tr of toolResults) {
      messages.push(tr);
    }
    
    /* Get final response */
    const finalStream = await openai.chat.completions.create({ 
      model: 'gpt-4.1', 
      messages, 
      tools, 
      temperature: 0.7, 
      max_tokens: 10000,
      stream: true 
    });
    
    fullContent = '';
    for await (const chunk of finalStream) {
      const delta = chunk.choices[0]?.delta;
      if (delta?.content) {
        fullContent += delta.content;
        yield { type: 'token', token: delta.content };
      }
    }
  }
  
  /* Yield final completion */
  yield { type: 'complete', content: fullContent };
};
```




### Edge Functions

#### reverseBanFn.js
```js
module.exports = async (request) => {
  const COMMON = require('common');
  const { createModerationRecord, getModerationRecordListByQuery } = require('dbLayer');
  /* Validate admin access: check admin token from env or admin session */
  const adminToken = process.env.ADMIN_TOKEN;
  const providedToken = request.headers ? (request.headers['x-admin-token'] || request.headers['X-Admin-Token']) : null;
  const isAdminSession = request.session && ['admin', 'superAdmin'].includes(request.session.roleId);
  if (!isAdminSession && (!adminToken || providedToken !== adminToken)) {
    return { status: 403, message: 'Unauthorized: Admin access required' };
  }
  const userId = request.body ? request.body.userId : null;
  if (!userId) {
    return { status: 400, message: 'userId is required in request body' };
  }
  /* Check if user has a lifetime ban */
  const records = await getModerationRecordListByQuery({ userId });
  const banRelated = records.filter(r => r.action === 'lifetimeBan' || r.action === 'banReversal');
  banRelated.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  if (banRelated.length === 0 || banRelated[0].action !== 'lifetimeBan') {
    return { status: 404, message: 'No active lifetime ban found for this user' };
  }
  /* Create ban reversal record */
  await createModerationRecord({
    userId,
    offenseType: 'admin_reversal',
    action: 'banReversal',
    reason: 'Ban reversed by admin' + (isAdminSession ? ' (' + request.session.email + ')' : ' (via admin token)')
  });
  /* Reactivate user in auth service */
  try {
    await COMMON.sendRestRequest(
      process.env.AUTH_SERVICE_URL ? process.env.AUTH_SERVICE_URL + '/m2m/user/updateById' : 'http://auth:3000/m2m/user/updateById',
      'PUT',
      { id: userId, dataClause: { isActive: true } },
      { 'x-service-token': process.env.M2M_TOKEN || '' }
    );
  } catch (m2mErr) {
    console.error('Failed to reactivate user in auth service:', m2mErr);
    return { status: 500, message: 'Ban reversed in moderation records but failed to reactivate user in auth service' };
  }
  return { status: 200, message: 'Ban reversed successfully', userId };
};
```

#### getUsageAnalyticsFn.js
```js
module.exports = async (request) => {
  /* Validate admin access */
  const adminToken = process.env.ADMIN_TOKEN;
  const providedToken = request.headers ? (request.headers['x-admin-token'] || request.headers['X-Admin-Token']) : null;
  const isAdminSession = request.session && ['admin', 'superAdmin'].includes(request.session.roleId);
  if (!isAdminSession && (!adminToken || providedToken !== adminToken)) {
    return { status: 403, message: 'Unauthorized: Admin access required' };
  }
  const { getChatMessageStatsByQuery, getUserQuotaListByQuery, getQuotaConfigListByQuery } = require('dbLayer');
  try {
    /* Total messages */
    const totalMessages = await getChatMessageStatsByQuery({}, 'count');
    /* Flagged messages */
    const flaggedMessages = await getChatMessageStatsByQuery({ flagged: true }, 'count');
    /* User messages vs assistant messages */
    const userMessages = await getChatMessageStatsByQuery({ role: 'user' }, 'count');
    const assistantMessages = await getChatMessageStatsByQuery({ role: 'assistant' }, 'count');
    /* Quota config */
    const configs = await getQuotaConfigListByQuery({});
    const quotaConfig = configs.length > 0 ? configs[0] : null;
    /* User quotas - top consumers */
    const quotas = await getUserQuotaListByQuery({});
    const sortedQuotas = quotas.sort((a, b) => b.messageCount - a.messageCount).slice(0, 20);
    const totalQuotaUsage = quotas.reduce((sum, q) => sum + (q.messageCount || 0), 0);
    const avgQuotaUsage = quotas.length > 0 ? totalQuotaUsage / quotas.length : 0;
    return {
      status: 200,
      analytics: {
        totalMessages: totalMessages || 0,
        flaggedMessages: flaggedMessages || 0,
        userMessages: userMessages || 0,
        assistantMessages: assistantMessages || 0,
        flagRate: totalMessages > 0 ? ((flaggedMessages || 0) / totalMessages * 100).toFixed(2) + '%' : '0%',
        quotaConfig: quotaConfig ? { limit: quotaConfig.quotaLimit, period: quotaConfig.quotaPeriod } : null,
        activeUsers: quotas.length,
        avgQuotaUsage: Math.round(avgQuotaUsage),
        totalQuotaUsage,
        topConsumers: sortedQuotas.map(q => ({ userId: q.userId, messageCount: q.messageCount }))
      }
    };
  } catch (err) {
    console.error('getUsageAnalyticsFn error:', err);
    return { status: 500, message: 'Failed to retrieve analytics', error: err.message };
  }
};
```










---

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